diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..691559ca60fe92a39e770cdb5d16c42a4c5651e1 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/__init__.py @@ -0,0 +1,3 @@ +from statsmodels.tools._test_runner import PytestTester + +test = PytestTester() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/_constraints.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/_constraints.py new file mode 100644 index 0000000000000000000000000000000000000000..0026849bb6f4b299f6515ae3d6cd0c5a00193295 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/_constraints.py @@ -0,0 +1,393 @@ +""" +Created on Thu May 15 16:36:05 2014 + +Author: Josef Perktold +License: BSD-3 + +""" + +import numpy as np + + +class LinearConstraints: + """Class to hold linear constraints information + + Affine constraints are defined as ``R b = q` where `R` is the constraints + matrix and `q` are the constraints values and `b` are the parameters. + + This is in analogy to patsy's LinearConstraints class but can be pickled. + + Parameters + ---------- + constraint_matrix : ndarray + R matrix, 2-dim with number of columns equal to the number of + parameters. Each row defines one constraint. + constraint_values : ndarray + 1-dim array of constant values + variable_names : list of strings + parameter names, used only for display + kwds : keyword arguments + keywords are attached to the instance. + + """ + + def __init__(self, constraint_matrix, constraint_values, + variable_names, **kwds): + + self.constraint_matrix = constraint_matrix + self.constraint_values = constraint_values + self.variable_names = variable_names + + # alias for patsy compatibility + self.coefs = constraint_matrix + self.constants = constraint_values + + self.__dict__.update(kwds) + self.tuple = (self.constraint_matrix, self.constraint_values) + + def __iter__(self): + yield from self.tuple + + def __getitem__(self, idx): + return self.tuple[idx] + + def __str__(self): + def prod_string(v, name): + v = np.abs(v) + if v != 1: + ss = str(v) + " * " + name + else: + ss = name + return ss + + constraints_strings = [] + for r, q in zip(*self): + ss = [] + for v, name in zip(r, self.variable_names): + if v != 0 and ss == []: + ss += prod_string(v, name) + elif v > 0: + ss += " + " + prod_string(v, name) + elif v < 0: + ss += " - " + prod_string(np.abs(v), name) + ss += " = " + str(q.item()) + constraints_strings.append(''.join(ss)) + + return '\n'.join(constraints_strings) + + @classmethod + def from_patsy(cls, lc): + """class method to create instance from patsy instance + + Parameters + ---------- + lc : instance + instance of patsy LinearConstraint, or other instances that have + attributes ``lc.coefs, lc.constants, lc.variable_names`` + + Returns + ------- + instance of this class + + """ + return cls(lc.coefs, lc.constants, lc.variable_names) + + +class TransformRestriction: + """Transformation for linear constraints `R params = q` + + Note, the transformation from the reduced to the full parameters is an + affine and not a linear transformation if q is not zero. + + + Parameters + ---------- + R : array_like + Linear restriction matrix + q : arraylike or None + values of the linear restrictions + + + Notes + ----- + The reduced parameters are not sorted with respect to constraints. + + TODO: error checking, eg. inconsistent constraints, how? + + Inconsistent constraints will raise an exception in the calculation of + the constant or offset. However, homogeneous constraints, where q=0, will + can have a solution where the relevant parameters are constraint to be + zero, as in the following example:: + + b1 + b2 = 0 and b1 + 2*b2 = 0, implies that b2 = 0. + + The transformation applied from full to reduced parameter space does not + raise and exception if the constraint does not hold. + TODO: maybe change this, what's the behavior in this case? + + + The `reduce` transform is applied to the array of explanatory variables, + `exog`, when transforming a linear model to impose the constraints. + """ + + def __init__(self, R, q=None): + + # The calculations are based on Stata manual for makecns + R = self.R = np.atleast_2d(R) + if q is not None: + q = self.q = np.asarray(q) + + k_constr, k_vars = R.shape + self.k_constr, self.k_vars = k_constr, k_vars + self.k_unconstr = k_vars - k_constr + + m = np.eye(k_vars) - R.T.dot(np.linalg.pinv(R).T) + evals, evecs = np.linalg.eigh(m) + + # This normalizes the transformation so the larges element is 1. + # It makes it easier to interpret simple restrictions, e.g. b1 + b2 = 0 + # TODO: make this work, there is something wrong, does not round-trip + # need to adjust constant + #evecs_maxabs = np.max(np.abs(evecs), 0) + #evecs = evecs / evecs_maxabs + + self.evals = evals + self.evecs = evecs # temporarily attach as attribute + L = self.L = evecs[:, :k_constr] + self.transf_mat = evecs[:, k_constr:] + + if q is not None: + # use solve instead of inv + #self.constant = q.T.dot(np.linalg.inv(L.T.dot(R.T)).dot(L.T)) + try: + self.constant = q.T.dot(np.linalg.solve(L.T.dot(R.T), L.T)) + except np.linalg.LinAlgError as e: + raise ValueError('possibly inconsistent constraints. error ' + 'generated by\n%r' % (e, )) + else: + self.constant = 0 + + def expand(self, params_reduced): + """transform from the reduced to the full parameter space + + Parameters + ---------- + params_reduced : array_like + parameters in the transformed space + + Returns + ------- + params : array_like + parameters in the original space + + Notes + ----- + If the restriction is not homogeneous, i.e. q is not equal to zero, + then this is an affine transform. + """ + params_reduced = np.asarray(params_reduced) + return self.transf_mat.dot(params_reduced.T).T + self.constant + + def reduce(self, params): + """transform from the full to the reduced parameter space + + Parameters + ---------- + params : array_like + parameters or data in the original space + + Returns + ------- + params_reduced : array_like + parameters in the transformed space + + This transform can be applied to the original parameters as well + as to the data. If params is 2-d, then each row is transformed. + """ + params = np.asarray(params) + return params.dot(self.transf_mat) + + +def transform_params_constraint(params, Sinv, R, q): + """find the parameters that statisfy linear constraint from unconstrained + + The linear constraint R params = q is imposed. + + Parameters + ---------- + params : array_like + unconstrained parameters + Sinv : ndarray, 2d, symmetric + covariance matrix of the parameter estimate + R : ndarray, 2d + constraint matrix + q : ndarray, 1d + values of the constraint + + Returns + ------- + params_constraint : ndarray + parameters of the same length as params satisfying the constraint + + Notes + ----- + This is the exact formula for OLS and other linear models. It will be + a local approximation for nonlinear models. + + TODO: Is Sinv always the covariance matrix? + In the linear case it can be (X'X)^{-1} or sigmahat^2 (X'X)^{-1}. + + My guess is that this is the point in the subspace that satisfies + the constraint that has minimum Mahalanobis distance. Proof ? + """ + + rsr = R.dot(Sinv).dot(R.T) + + reduction = Sinv.dot(R.T).dot(np.linalg.solve(rsr, R.dot(params) - q)) + return params - reduction + + +def fit_constrained(model, constraint_matrix, constraint_values, + start_params=None, fit_kwds=None): + # note: self is model instance + """fit model subject to linear equality constraints + + The constraints are of the form `R params = q` + where R is the constraint_matrix and q is the vector of constraint_values. + + The estimation creates a new model with transformed design matrix, + exog, and converts the results back to the original parameterization. + + + Parameters + ---------- + model: model instance + An instance of a model, see limitations in Notes section + constraint_matrix : array_like, 2D + This is R in the linear equality constraint `R params = q`. + The number of columns needs to be the same as the number of columns + in exog. + constraint_values : + This is `q` in the linear equality constraint `R params = q` + If it is a tuple, then the constraint needs to be given by two + arrays (constraint_matrix, constraint_value), i.e. (R, q). + Otherwise, the constraints can be given as strings or list of + strings. + see t_test for details + start_params : None or array_like + starting values for the optimization. `start_params` needs to be + given in the original parameter space and are internally + transformed. + **fit_kwds : keyword arguments + fit_kwds are used in the optimization of the transformed model. + + Returns + ------- + params : ndarray ? + estimated parameters (in the original parameterization + cov_params : ndarray + covariance matrix of the parameter estimates. This is a reverse + transformation of the covariance matrix of the transformed model given + by `cov_params()` + Note: `fit_kwds` can affect the choice of covariance, e.g. by + specifying `cov_type`, which will be reflected in the returned + covariance. + res_constr : results instance + This is the results instance for the created transformed model. + + + Notes + ----- + Limitations: + + Models where the number of parameters is different from the number of + columns of exog are not yet supported. + + Requires a model that implement an offset option. + """ + self = model # internal alias, used for methods + if fit_kwds is None: + fit_kwds = {} + + R, q = constraint_matrix, constraint_values + endog, exog = self.endog, self.exog + + transf = TransformRestriction(R, q) + + exogp_st = transf.reduce(exog) + + offset = exog.dot(transf.constant.squeeze()) + if hasattr(self, 'offset'): + offset += self.offset + + if start_params is not None: + start_params = transf.reduce(start_params) + + #need copy, because we do not want to change it, we do not need deepcopy + import copy + init_kwds = copy.copy(self._get_init_kwds()) + + # TODO: refactor to combine with above or offset_all + if 'offset' in init_kwds: + del init_kwds['offset'] + + # using offset as keywords is not supported in all modules + mod_constr = self.__class__(endog, exogp_st, offset=offset, **init_kwds) + res_constr = mod_constr.fit(start_params=start_params, **fit_kwds) + params_orig = transf.expand(res_constr.params).squeeze() + cov_params = transf.transf_mat.dot(res_constr.cov_params()).dot(transf.transf_mat.T) + + return params_orig, cov_params, res_constr + + +def fit_constrained_wrap(model, constraints, start_params=None, **fit_kwds): + """fit_constraint that returns a results instance + + This is a development version for fit_constrained methods or + fit_constrained as standalone function. + + It will not work correctly for all models because creating a new + results instance is not standardized for use outside the `fit` methods, + and might need adjustements for this. + + This is the prototype for the fit_constrained method that has been added + to Poisson and GLM. + """ + + self = model # alias for use as method + + #constraints = (R, q) + # TODO: temporary trailing underscore to not overwrite the monkey + # patched version + # TODO: decide whether to move the imports + from patsy import DesignInfo + # we need this import if we copy it to a different module + #from statsmodels.base._constraints import fit_constrained + + # same pattern as in base.LikelihoodModel.t_test + lc = DesignInfo(self.exog_names).linear_constraint(constraints) + R, q = lc.coefs, lc.constants + + # TODO: add start_params option, need access to tranformation + # fit_constrained needs to do the transformation + params, cov, res_constr = fit_constrained(self, R, q, + start_params=start_params, + fit_kwds=fit_kwds) + #create dummy results Instance, TODO: wire up properly + res = self.fit(start_params=params, maxiter=0, + warn_convergence=False) # we get a wrapper back + res._results.params = params + res._results.cov_params_default = cov + cov_type = fit_kwds.get('cov_type', 'nonrobust') + if cov_type == 'nonrobust': + res._results.normalized_cov_params = cov / res_constr.scale + else: + res._results.normalized_cov_params = None + + k_constr = len(q) + res._results.df_resid += k_constr + res._results.df_model -= k_constr + res._results.constraints = LinearConstraints.from_patsy(lc) + res._results.k_constr = k_constr + res._results.results_constrained = res_constr + return res diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/_parameter_inference.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/_parameter_inference.py new file mode 100644 index 0000000000000000000000000000000000000000..7e002423b2e551135aa1d6385258be7ffb9e32d6 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/_parameter_inference.py @@ -0,0 +1,403 @@ +""" +Created on Wed May 30 15:11:09 2018 + +@author: josef +""" + +import numpy as np +from scipy import stats + + +# this is a copy from stats._diagnostic_other to avoid circular imports +def _lm_robust(score, constraint_matrix, score_deriv_inv, cov_score, + cov_params=None): + '''general formula for score/LM test + + generalized score or lagrange multiplier test for implicit constraints + + `r(params) = 0`, with gradient `R = d r / d params` + + linear constraints are given by `R params - q = 0` + + It is assumed that all arrays are evaluated at the constrained estimates. + + + Parameters + ---------- + score : ndarray, 1-D + derivative of objective function at estimated parameters + of constrained model + constraint_matrix R : ndarray + Linear restriction matrix or Jacobian of nonlinear constraints + score_deriv_inv, Ainv : ndarray, symmetric, square + inverse of second derivative of objective function + TODO: could be inverse of OPG or any other estimator if information + matrix equality holds + cov_score B : ndarray, symmetric, square + covariance matrix of the score. This is the inner part of a sandwich + estimator. + cov_params V : ndarray, symmetric, square + covariance of full parameter vector evaluated at constrained parameter + estimate. This can be specified instead of cov_score B. + + Returns + ------- + lm_stat : float + score/lagrange multiplier statistic + p-value : float + p-value of the LM test based on chisquare distribution + + Notes + ----- + + ''' + # shorthand alias + R, Ainv, B, V = constraint_matrix, score_deriv_inv, cov_score, cov_params + + k_constraints = np.linalg.matrix_rank(R) + tmp = R.dot(Ainv) + wscore = tmp.dot(score) # C Ainv score + + if B is None and V is None: + # only Ainv is given, so we assume information matrix identity holds + # computational short cut, should be same if Ainv == inv(B) + lm_stat = score.dot(Ainv.dot(score)) + else: + # information matrix identity does not hold + if V is None: + inner = tmp.dot(B).dot(tmp.T) + else: + inner = R.dot(V).dot(R.T) + + #lm_stat2 = wscore.dot(np.linalg.pinv(inner).dot(wscore)) + # Let's assume inner is invertible, TODO: check if usecase for pinv exists + lm_stat = wscore.dot(np.linalg.solve(inner, wscore)) + pval = stats.chi2.sf(lm_stat, k_constraints) + return lm_stat, pval, k_constraints + + +def score_test(self, exog_extra=None, params_constrained=None, + hypothesis='joint', cov_type=None, cov_kwds=None, + k_constraints=None, r_matrix=None, scale=None, observed=True): + """score test for restrictions or for omitted variables + + Null Hypothesis : constraints are satisfied + + Alternative Hypothesis : at least one of the constraints does not hold + + This allows to specify restricted and unrestricted model properties in + three different ways + + - fit_constrained result: model contains score and hessian function for + the full, unrestricted model, but the parameter estimate in the results + instance is for the restricted model. This is the case if the model + was estimated with fit_constrained. + - restricted model with variable addition: If exog_extra is not None, then + it is assumed that the current model is a model with zero restrictions + and the unrestricted model is given by adding exog_extra as additional + explanatory variables. + - unrestricted model with restricted parameters explicitly provided. If + params_constrained is not None, then the model is assumed to be for the + unrestricted model, but the provided parameters are for the restricted + model. + TODO: This case will currently only work for `nonrobust` cov_type, + otherwise we will also need the restriction matrix provided by the user. + + + Parameters + ---------- + exog_extra : None or array_like + Explanatory variables that are jointly tested for inclusion in the + model, i.e. omitted variables. + params_constrained : array_like + estimated parameter of the restricted model. This can be the + parameter estimate for the current when testing for omitted + variables. + hypothesis : str, 'joint' (default) or 'separate' + If hypothesis is 'joint', then the chisquare test results for the + joint hypothesis that all constraints hold is returned. + If hypothesis is 'joint', then z-test results for each constraint + is returned. + This is currently only implemented for cov_type="nonrobust". + cov_type : str + Warning: only partially implemented so far, currently only "nonrobust" + and "HC0" are supported. + If cov_type is None, then the cov_type specified in fit for the Wald + tests is used. + If the cov_type argument is not None, then it will be used instead of + the Wald cov_type given in fit. + k_constraints : int or None + Number of constraints that were used in the estimation of params + restricted relative to the number of exog in the model. + This must be provided if no exog_extra are given. If exog_extra is + not None, then k_constraints is assumed to be zero if it is None. + observed : bool + If True, then the observed Hessian is used in calculating the + covariance matrix of the score. If false then the expected + information matrix is used. This currently only applies to GLM where + EIM is available. + Warning: This option might still change. + + Returns + ------- + chi2_stat : float + chisquare statistic for the score test + p-value : float + P-value of the score test based on the chisquare distribution. + df : int + Degrees of freedom used in the p-value calculation. This is equal + to the number of constraints. + + Notes + ----- + Status: experimental, several options are not implemented yet or are not + verified yet. Currently available ptions might also still change. + + cov_type is 'nonrobust': + + The covariance matrix for the score is based on the Hessian, i.e. + observed information matrix or optionally on the expected information + matrix. + + cov_type is 'HC0' + + The covariance matrix of the score is the simple empirical covariance of + score_obs without degrees of freedom correction. + """ + # TODO: we are computing unnecessary things for cov_type nonrobust + if hasattr(self, "_results"): + # use numpy if we have wrapper, not relevant if method + self = self._results + model = self.model + nobs = model.endog.shape[0] # model.nobs + # discrete Poisson does not have nobs + if params_constrained is None: + params_constrained = self.params + cov_type = cov_type if cov_type is not None else self.cov_type + + if observed is False: + hess_kwd = {'observed': False} + else: + hess_kwd = {} + + if exog_extra is None: + + if hasattr(self, 'constraints'): + if isinstance(self.constraints, tuple): + r_matrix = self.constraints[0] + else: + r_matrix = self.constraints.coefs + k_constraints = r_matrix.shape[0] + + else: + if k_constraints is None: + raise ValueError('if exog_extra is None, then k_constraints' + 'needs to be given') + + # we need to use results scale as additional parameter + if scale is not None: + # we need to use results scale as additional parameter, gh #7840 + score_kwd = {'scale': scale} + hess_kwd['scale'] = scale + else: + score_kwd = {} + + # duplicate computation of score, might not be needed + score = model.score(params_constrained, **score_kwd) + score_obs = model.score_obs(params_constrained, **score_kwd) + hessian = model.hessian(params_constrained, **hess_kwd) + + else: + if cov_type == 'V': + raise ValueError('if exog_extra is not None, then cov_type cannot ' + 'be V') + if hasattr(self, 'constraints'): + raise NotImplementedError('if exog_extra is not None, then self' + 'should not be a constrained fit result') + + if isinstance(exog_extra, tuple): + sh = _scorehess_extra(self, params_constrained, *exog_extra, + hess_kwds=hess_kwd) + score_obs, hessian, k_constraints, r_matrix = sh + score = score_obs.sum(0) + else: + exog_extra = np.asarray(exog_extra) + k_constraints = 0 + ex = np.column_stack((model.exog, exog_extra)) + # this uses shape not matrix rank to determine k_constraints + # requires nonsingular (no added perfect collinearity) + k_constraints += ex.shape[1] - model.exog.shape[1] + # TODO use diag instead of full np.eye + r_matrix = np.eye(len(self.params) + k_constraints + )[-k_constraints:] + + score_factor = model.score_factor(params_constrained) + if score_factor.ndim == 1: + score_obs = (score_factor[:, None] * ex) + else: + sf = score_factor + score_obs = np.column_stack((sf[:, :1] * ex, sf[:, 1:])) + score = score_obs.sum(0) + hessian_factor = model.hessian_factor(params_constrained, + **hess_kwd) + # see #4714 + from statsmodels.genmod.generalized_linear_model import GLM + if isinstance(model, GLM): + hessian_factor *= -1 + hessian = np.dot(ex.T * hessian_factor, ex) + + if cov_type == 'nonrobust': + cov_score_test = -hessian + elif cov_type.upper() == 'HC0': + hinv = -np.linalg.inv(hessian) + cov_score = nobs * np.cov(score_obs.T) + # temporary to try out + lm = _lm_robust(score, r_matrix, hinv, cov_score, cov_params=None) + return lm + # alternative is to use only the center, but it is singular + # https://github.com/statsmodels/statsmodels/pull/2096#issuecomment-393646205 + # cov_score_test_inv = cov_lm_robust(score, r_matrix, hinv, + # cov_score, cov_params=None) + elif cov_type.upper() == 'V': + # TODO: this does not work, V in fit_constrained results is singular + # we need cov_params without the zeros in it + hinv = -np.linalg.inv(hessian) + cov_score = nobs * np.cov(score_obs.T) + V = self.cov_params_default + # temporary to try out + chi2stat = _lm_robust(score, r_matrix, hinv, cov_score, cov_params=V) + pval = stats.chi2.sf(chi2stat, k_constraints) + return chi2stat, pval + else: + msg = 'Only cov_type "nonrobust" and "HC0" are available.' + raise NotImplementedError(msg) + + if hypothesis == 'joint': + chi2stat = score.dot(np.linalg.solve(cov_score_test, score[:, None])) + pval = stats.chi2.sf(chi2stat, k_constraints) + # return a stats results instance instead? Contrast? + return chi2stat, pval, k_constraints + elif hypothesis == 'separate': + diff = score + bse = np.sqrt(np.diag(cov_score_test)) + stat = diff / bse + pval = stats.norm.sf(np.abs(stat))*2 + return stat, pval + else: + raise NotImplementedError('only hypothesis "joint" is available') + + +def _scorehess_extra(self, params=None, exog_extra=None, + exog2_extra=None, hess_kwds=None): + """Experimental helper function for variable addition score test. + + This uses score and hessian factor at the params which should be the + params of the restricted model. + + """ + if hess_kwds is None: + hess_kwds = {} + # this corresponds to a model methods, so we need only the model + model = self.model + # as long as we have results instance, we can take params from it + if params is None: + params = self.params + + # get original exog from model, currently only if exactly 2 + exog_o1, exog_o2 = model._get_exogs() + + if exog_o2 is None: + # if extra params is scalar, as in NB, GPP + exog_o2 = np.ones((exog_o1.shape[0], 1)) + + k_mean = exog_o1.shape[1] + k_prec = exog_o2.shape[1] + if exog_extra is not None: + exog = np.column_stack((exog_o1, exog_extra)) + else: + exog = exog_o1 + + if exog2_extra is not None: + exog2 = np.column_stack((exog_o2, exog2_extra)) + else: + exog2 = exog_o2 + + k_mean_new = exog.shape[1] + k_prec_new = exog2.shape[1] + k_cm = k_mean_new - k_mean + k_cp = k_prec_new - k_prec + k_constraints = k_cm + k_cp + + index_mean = np.arange(k_mean, k_mean_new) + index_prec = np.arange(k_mean_new + k_prec, k_mean_new + k_prec_new) + + r_matrix = np.zeros((k_constraints, len(params) + k_constraints)) + # print(exog.shape, exog2.shape) + # print(r_matrix.shape, k_cm, k_cp, k_mean_new, k_prec_new) + # print(index_mean, index_prec) + r_matrix[:k_cm, index_mean] = np.eye(k_cm) + r_matrix[k_cm: k_cm + k_cp, index_prec] = np.eye(k_cp) + + if hasattr(model, "score_hessian_factor"): + sf, hf = model.score_hessian_factor(params, return_hessian=True, + **hess_kwds) + else: + sf = model.score_factor(params) + hf = model.hessian_factor(params, **hess_kwds) + + sf1, sf2 = sf + hf11, hf12, hf22 = hf + + # elementwise product for each row (observation) + d1 = sf1[:, None] * exog + d2 = sf2[:, None] * exog2 + score_obs = np.column_stack((d1, d2)) + + # elementwise product for each row (observation) + d11 = (exog.T * hf11).dot(exog) + d12 = (exog.T * hf12).dot(exog2) + d22 = (exog2.T * hf22).dot(exog2) + hessian = np.block([[d11, d12], [d12.T, d22]]) + return score_obs, hessian, k_constraints, r_matrix + + +def im_ratio(results): + res = getattr(results, "_results", results) # shortcut + hess = res.model.hessian(res.params) + if res.cov_type == "nonrobust": + score_obs = res.model.score_obs(res.params) + cov_score = score_obs.T @ score_obs + hessneg_inv = np.linalg.inv(-hess) + im_ratio = hessneg_inv @ cov_score + else: + im_ratio = res.cov_params() @ (-hess) + return im_ratio + + +def tic(results): + """Takeuchi information criterion for misspecified models + + """ + imr = getattr(results, "im_ratio", im_ratio(results)) + tic = - 2 * results.llf + 2 * np.trace(imr) + return tic + + +def gbic(results, gbicp=False): + """generalized BIC for misspecified models + + References + ---------- + Lv, Jinchi, and Jun S. Liu. 2014. "Model Selection Principles in + Misspecified Models." Journal of the Royal Statistical Society. + Series B (Statistical Methodology) 76 (1): 141–67. + + """ + self = getattr(results, "_results", results) + k_params = self.df_model + 1 + nobs = k_params + self.df_resid + imr = getattr(results, "im_ratio", im_ratio(results)) + imr_logdet = np.linalg.slogdet(imr)[1] + gbic = -2 * self.llf + k_params * np.log(nobs) - imr_logdet # LL equ. (20) + gbicp = gbic + np.trace(imr) # LL equ. (23) + return gbic, gbicp diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/_penalized.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/_penalized.py new file mode 100644 index 0000000000000000000000000000000000000000..e3a87fdaa1a8dc1315ecf8c0f9be177a7b73eb76 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/_penalized.py @@ -0,0 +1,226 @@ +""" +Created on Sun May 10 08:23:48 2015 + +Author: Josef Perktold +License: BSD-3 +""" + +import numpy as np +from ._penalties import NonePenalty +from statsmodels.tools.numdiff import approx_fprime_cs, approx_fprime + + +class PenalizedMixin: + """Mixin class for Maximum Penalized Likelihood + + Parameters + ---------- + args and kwds for the model super class + penal : None or instance of Penalized function class + If penal is None, then NonePenalty is used. + pen_weight : float or None + factor for weighting the penalization term. + If None, then pen_weight is set to nobs. + + + TODO: missing **kwds or explicit keywords + + TODO: do we adjust the inherited docstrings? + We would need templating to add the penalization parameters + """ + + def __init__(self, *args, **kwds): + + # pop extra kwds before calling super + self.penal = kwds.pop('penal', None) + self.pen_weight = kwds.pop('pen_weight', None) + + super().__init__(*args, **kwds) + + # TODO: define pen_weight as average pen_weight? i.e. per observation + # I would have prefered len(self.endog) * kwds.get('pen_weight', 1) + # or use pen_weight_factor in signature + if self.pen_weight is None: + self.pen_weight = len(self.endog) + + if self.penal is None: + # unpenalized by default + self.penal = NonePenalty() + self.pen_weight = 0 + + self._init_keys.extend(['penal', 'pen_weight']) + self._null_drop_keys = getattr(self, '_null_drop_keys', []) + self._null_drop_keys.extend(['penal', 'pen_weight']) + + def _handle_scale(self, params, scale=None, **kwds): + + if scale is None: + # special handling for GLM + if hasattr(self, 'scaletype'): + mu = self.predict(params) + scale = self.estimate_scale(mu) + else: + scale = 1 + + return scale + + def loglike(self, params, pen_weight=None, **kwds): + """ + Log-likelihood of model at params + """ + if pen_weight is None: + pen_weight = self.pen_weight + + llf = super().loglike(params, **kwds) + if pen_weight != 0: + scale = self._handle_scale(params, **kwds) + llf -= 1/scale * pen_weight * self.penal.func(params) + + return llf + + def loglikeobs(self, params, pen_weight=None, **kwds): + """ + Log-likelihood of model observations at params + """ + if pen_weight is None: + pen_weight = self.pen_weight + + llf = super().loglikeobs(params, **kwds) + nobs_llf = float(llf.shape[0]) + + if pen_weight != 0: + scale = self._handle_scale(params, **kwds) + llf -= 1/scale * pen_weight / nobs_llf * self.penal.func(params) + + return llf + + def score_numdiff(self, params, pen_weight=None, method='fd', **kwds): + """score based on finite difference derivative + """ + if pen_weight is None: + pen_weight = self.pen_weight + + loglike = lambda p: self.loglike(p, pen_weight=pen_weight, **kwds) + + if method == 'cs': + return approx_fprime_cs(params, loglike) + elif method == 'fd': + return approx_fprime(params, loglike, centered=True) + else: + raise ValueError('method not recognized, should be "fd" or "cs"') + + def score(self, params, pen_weight=None, **kwds): + """ + Gradient of model at params + """ + if pen_weight is None: + pen_weight = self.pen_weight + + sc = super().score(params, **kwds) + if pen_weight != 0: + scale = self._handle_scale(params, **kwds) + sc -= 1/scale * pen_weight * self.penal.deriv(params) + + return sc + + def score_obs(self, params, pen_weight=None, **kwds): + """ + Gradient of model observations at params + """ + if pen_weight is None: + pen_weight = self.pen_weight + + sc = super().score_obs(params, **kwds) + nobs_sc = float(sc.shape[0]) + if pen_weight != 0: + scale = self._handle_scale(params, **kwds) + sc -= 1/scale * pen_weight / nobs_sc * self.penal.deriv(params) + + return sc + + def hessian_numdiff(self, params, pen_weight=None, **kwds): + """hessian based on finite difference derivative + """ + if pen_weight is None: + pen_weight = self.pen_weight + loglike = lambda p: self.loglike(p, pen_weight=pen_weight, **kwds) + + from statsmodels.tools.numdiff import approx_hess + return approx_hess(params, loglike) + + def hessian(self, params, pen_weight=None, **kwds): + """ + Hessian of model at params + """ + if pen_weight is None: + pen_weight = self.pen_weight + + hess = super().hessian(params, **kwds) + if pen_weight != 0: + scale = self._handle_scale(params, **kwds) + h = self.penal.deriv2(params) + if h.ndim == 1: + hess -= 1/scale * np.diag(pen_weight * h) + else: + hess -= 1/scale * pen_weight * h + + return hess + + def fit(self, method=None, trim=None, **kwds): + """minimize negative penalized log-likelihood + + Parameters + ---------- + method : None or str + Method specifies the scipy optimizer as in nonlinear MLE models. + trim : {bool, float} + Default is False or None, which uses no trimming. + If trim is True or a float, then small parameters are set to zero. + If True, then a default threshold is used. If trim is a float, then + it will be used as threshold. + The default threshold is currently 1e-4, but it will change in + future and become penalty function dependent. + kwds : extra keyword arguments + This keyword arguments are treated in the same way as in the + fit method of the underlying model class. + Specifically, additional optimizer keywords and cov_type related + keywords can be added. + """ + # If method is None, then we choose a default method ourselves + + # TODO: temporary hack, need extra fit kwds + # we need to rule out fit methods in a model that will not work with + # penalization + from statsmodels.gam.generalized_additive_model import GLMGam + from statsmodels.genmod.generalized_linear_model import GLM + # Only for fit methods supporting max_start_irls + if isinstance(self, (GLM, GLMGam)): + kwds.update({'max_start_irls': 0}) + + # currently we use `bfgs` by default + if method is None: + method = 'bfgs' + + if trim is None: + trim = False + + res = super().fit(method=method, **kwds) + + if trim is False: + # note boolean check for "is False", not "False_like" + return res + else: + if trim is True: + trim = 1e-4 # trim threshold + # TODO: make it penal function dependent + # temporary standin, only checked for Poisson and GLM, + # and is computationally inefficient + drop_index = np.nonzero(np.abs(res.params) < trim)[0] + keep_index = np.nonzero(np.abs(res.params) > trim)[0] + + if drop_index.any(): + # TODO: do we need to add results attributes? + res_aux = self._fit_zeros(keep_index, **kwds) + return res_aux + else: + return res diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/_penalties.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/_penalties.py new file mode 100644 index 0000000000000000000000000000000000000000..d4fecdead60e778b3b0ca51177581094cd16932c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/_penalties.py @@ -0,0 +1,586 @@ +""" +A collection of smooth penalty functions. + +Penalties on vectors take a vector argument and return a scalar +penalty. The gradient of the penalty is a vector with the same shape +as the input value. + +Penalties on covariance matrices take two arguments: the matrix and +its inverse, both in unpacked (square) form. The returned penalty is +a scalar, and the gradient is returned as a vector that contains the +gradient with respect to the free elements in the lower triangle of +the covariance matrix. + +All penalties are subtracted from the log-likelihood, so greater +penalty values correspond to a greater degree of penalization. + +The penaties should be smooth so that they can be subtracted from log +likelihood functions and optimized using standard methods (i.e. L1 +penalties do not belong here). +""" +import numpy as np + + +class Penalty: + """ + A class for representing a scalar-value penalty. + + Parameters + ---------- + weights : array_like + A vector of weights that determines the weight of the penalty + for each parameter. + + Notes + ----- + The class has a member called `alpha` that scales the weights. + """ + + def __init__(self, weights=1.): + self.weights = weights + self.alpha = 1. + + def func(self, params): + """ + A penalty function on a vector of parameters. + + Parameters + ---------- + params : array_like + A vector of parameters. + + Returns + ------- + A scalar penaty value; greater values imply greater + penalization. + """ + raise NotImplementedError + + def deriv(self, params): + """ + The gradient of a penalty function. + + Parameters + ---------- + params : array_like + A vector of parameters + + Returns + ------- + The gradient of the penalty with respect to each element in + `params`. + """ + raise NotImplementedError + + def _null_weights(self, params): + """work around for Null model + + This will not be needed anymore when we can use `self._null_drop_keys` + as in DiscreteModels. + TODO: check other models + """ + if np.size(self.weights) > 1: + if len(params) == 1: + raise # raise to identify models where this would be needed + return 0. + + return self.weights + + +class NonePenalty(Penalty): + """ + A penalty that does not penalize. + """ + + def __init__(self, **kwds): + super().__init__() + if kwds: + import warnings + warnings.warn('keyword arguments are be ignored') + + def func(self, params): + if params.ndim == 2: + return np.zeros(params.shape[1:]) + else: + return 0 + + def deriv(self, params): + return np.zeros(params.shape) + + def deriv2(self, params): + # returns diagonal of hessian + return np.zeros(params.shape[0]) + + +class L2(Penalty): + """ + The L2 (ridge) penalty. + """ + + def __init__(self, weights=1.): + super().__init__(weights) + + def func(self, params): + return np.sum(self.weights * self.alpha * params**2) + + def deriv(self, params): + return 2 * self.weights * self.alpha * params + + def deriv2(self, params): + return 2 * self.weights * self.alpha * np.ones(len(params)) + + +class L2Univariate(Penalty): + """ + The L2 (ridge) penalty applied to each parameter. + """ + + def __init__(self, weights=None): + if weights is None: + self.weights = 1. + else: + self.weights = weights + + def func(self, params): + return self.weights * params**2 + + def deriv(self, params): + return 2 * self.weights * params + + def deriv2(self, params): + return 2 * self.weights * np.ones(len(params)) + + +class PseudoHuber(Penalty): + """ + The pseudo-Huber penalty. + """ + + def __init__(self, dlt, weights=1.): + super().__init__(weights) + self.dlt = dlt + + def func(self, params): + v = np.sqrt(1 + (params / self.dlt)**2) + v -= 1 + v *= self.dlt**2 + return np.sum(self.weights * self.alpha * v, 0) + + def deriv(self, params): + v = np.sqrt(1 + (params / self.dlt)**2) + return params * self.weights * self.alpha / v + + def deriv2(self, params): + v = np.power(1 + (params / self.dlt)**2, -3/2) + return self.weights * self.alpha * v + + +class SCAD(Penalty): + """ + The SCAD penalty of Fan and Li. + + The SCAD penalty is linear around zero as a L1 penalty up to threshold tau. + The SCAD penalty is constant for values larger than c*tau. + The middle segment is quadratic and connect the two segments with a continuous + derivative. + The penalty is symmetric around zero. + + Parameterization follows Boo, Johnson, Li and Tan 2011. + Fan and Li use lambda instead of tau, and a instead of c. Fan and Li + recommend setting c=3.7. + + f(x) = { tau |x| if 0 <= |x| < tau + { -(|x|^2 - 2 c tau |x| + tau^2) / (2 (c - 1)) if tau <= |x| < c tau + { (c + 1) tau^2 / 2 if c tau <= |x| + + Parameters + ---------- + tau : float + slope and threshold for linear segment + c : float + factor for second threshold which is c * tau + weights : None or array + weights for penalty of each parameter. If an entry is zero, then the + corresponding parameter will not be penalized. + + References + ---------- + Buu, Anne, Norman J. Johnson, Runze Li, and Xianming Tan. "New variable + selection methods for zero‐inflated count data with applications to the + substance abuse field." + Statistics in medicine 30, no. 18 (2011): 2326-2340. + + Fan, Jianqing, and Runze Li. "Variable selection via nonconcave penalized + likelihood and its oracle properties." + Journal of the American statistical Association 96, no. 456 (2001): + 1348-1360. + """ + + def __init__(self, tau, c=3.7, weights=1.): + super().__init__(weights) + self.tau = tau + self.c = c + + def func(self, params): + + # 3 segments in absolute value + tau = self.tau + p_abs = np.atleast_1d(np.abs(params)) + res = np.empty(p_abs.shape, p_abs.dtype) + res.fill(np.nan) + mask1 = p_abs < tau + mask3 = p_abs >= self.c * tau + res[mask1] = tau * p_abs[mask1] + mask2 = ~mask1 & ~mask3 + p_abs2 = p_abs[mask2] + tmp = (p_abs2**2 - 2 * self.c * tau * p_abs2 + tau**2) + res[mask2] = -tmp / (2 * (self.c - 1)) + res[mask3] = (self.c + 1) * tau**2 / 2. + + return (self.weights * res).sum(0) + + def deriv(self, params): + + # 3 segments in absolute value + tau = self.tau + p = np.atleast_1d(params) + p_abs = np.abs(p) + p_sign = np.sign(p) + res = np.empty(p_abs.shape) + res.fill(np.nan) + + mask1 = p_abs < tau + mask3 = p_abs >= self.c * tau + mask2 = ~mask1 & ~mask3 + res[mask1] = p_sign[mask1] * tau + tmp = p_sign[mask2] * (p_abs[mask2] - self.c * tau) + res[mask2] = -tmp / (self.c - 1) + res[mask3] = 0 + + return self.weights * res + + def deriv2(self, params): + """Second derivative of function + + This returns scalar or vector in same shape as params, not a square + Hessian. If the return is 1 dimensional, then it is the diagonal of + the Hessian. + """ + + # 3 segments in absolute value + tau = self.tau + p = np.atleast_1d(params) + p_abs = np.abs(p) + res = np.zeros(p_abs.shape) + + mask1 = p_abs < tau + mask3 = p_abs >= self.c * tau + mask2 = ~mask1 & ~mask3 + res[mask2] = -1 / (self.c - 1) + + return self.weights * res + + +class SCADSmoothed(SCAD): + """ + The SCAD penalty of Fan and Li, quadratically smoothed around zero. + + This follows Fan and Li 2001 equation (3.7). + + Parameterization follows Boo, Johnson, Li and Tan 2011 + see docstring of SCAD + + Parameters + ---------- + tau : float + slope and threshold for linear segment + c : float + factor for second threshold + c0 : float + threshold for quadratically smoothed segment + restriction : None or array + linear constraints for + + Notes + ----- + TODO: Use delegation instead of subclassing, so smoothing can be added to + all penalty classes. + """ + + def __init__(self, tau, c=3.7, c0=None, weights=1., restriction=None): + super().__init__(tau, c=c, weights=weights) + self.tau = tau + self.c = c + self.c0 = c0 if c0 is not None else tau * 0.1 + if self.c0 > tau: + raise ValueError('c0 cannot be larger than tau') + + # get coefficients for quadratic approximation + c0 = self.c0 + # need to temporarily override weights for call to super + weights = self.weights + self.weights = 1. + deriv_c0 = super().deriv(c0) + value_c0 = super().func(c0) + self.weights = weights + + self.aq1 = value_c0 - 0.5 * deriv_c0 * c0 + self.aq2 = 0.5 * deriv_c0 / c0 + self.restriction = restriction + + def func(self, params): + # workaround for Null model + weights = self._null_weights(params) + # TODO: `and np.size(params) > 1` is hack for llnull, need better solution + if self.restriction is not None and np.size(params) > 1: + params = self.restriction.dot(params) + # need to temporarily override weights for call to super + # Note: we have the same problem with `restriction` + self_weights = self.weights + self.weights = 1. + value = super().func(params[None, ...]) + self.weights = self_weights + + # shift down so func(0) == 0 + value -= self.aq1 + # change the segment corrsponding to quadratic approximation + p_abs = np.atleast_1d(np.abs(params)) + mask = p_abs < self.c0 + p_abs_masked = p_abs[mask] + value[mask] = self.aq2 * p_abs_masked**2 + + return (weights * value).sum(0) + + def deriv(self, params): + # workaround for Null model + weights = self._null_weights(params) + if self.restriction is not None and np.size(params) > 1: + params = self.restriction.dot(params) + # need to temporarily override weights for call to super + self_weights = self.weights + self.weights = 1. + value = super().deriv(params) + self.weights = self_weights + + #change the segment corrsponding to quadratic approximation + p = np.atleast_1d(params) + mask = np.abs(p) < self.c0 + value[mask] = 2 * self.aq2 * p[mask] + + if self.restriction is not None and np.size(params) > 1: + return weights * value.dot(self.restriction) + else: + return weights * value + + def deriv2(self, params): + # workaround for Null model + weights = self._null_weights(params) + if self.restriction is not None and np.size(params) > 1: + params = self.restriction.dot(params) + # need to temporarily override weights for call to super + self_weights = self.weights + self.weights = 1. + value = super().deriv2(params) + self.weights = self_weights + + # change the segment corrsponding to quadratic approximation + p = np.atleast_1d(params) + mask = np.abs(p) < self.c0 + value[mask] = 2 * self.aq2 + + if self.restriction is not None and np.size(params) > 1: + # note: super returns 1d array for diag, i.e. hessian_diag + # TODO: weights are missing + return (self.restriction.T * (weights * value) + ).dot(self.restriction) + else: + return weights * value + + +class ConstraintsPenalty: + """ + Penalty applied to linear transformation of parameters + + Parameters + ---------- + penalty: instance of penalty function + currently this requires an instance of a univariate, vectorized + penalty class + weights : None or ndarray + weights for adding penalties of transformed params + restriction : None or ndarray + If it is not None, then restriction defines a linear transformation + of the parameters. The penalty function is applied to each transformed + parameter independently. + + Notes + ----- + `restrictions` allows us to impose penalization on contrasts or stochastic + constraints of the original parameters. + Examples for these contrast are difference penalities or all pairs + penalties. + """ + + def __init__(self, penalty, weights=None, restriction=None): + + self.penalty = penalty + if weights is None: + self.weights = 1. + else: + self.weights = weights + + if restriction is not None: + restriction = np.asarray(restriction) + + self.restriction = restriction + + def func(self, params): + """evaluate penalty function at params + + Parameter + --------- + params : ndarray + array of parameters at which derivative is evaluated + + Returns + ------- + deriv2 : ndarray + value(s) of penalty function + """ + # TODO: `and np.size(params) > 1` is hack for llnull, need better solution + # Is this still needed? it seems to work without + if self.restriction is not None: + params = self.restriction.dot(params) + + value = self.penalty.func(params) + + return (self.weights * value.T).T.sum(0) + + def deriv(self, params): + """first derivative of penalty function w.r.t. params + + Parameter + --------- + params : ndarray + array of parameters at which derivative is evaluated + + Returns + ------- + deriv2 : ndarray + array of first partial derivatives + """ + if self.restriction is not None: + params = self.restriction.dot(params) + + value = self.penalty.deriv(params) + + if self.restriction is not None: + return self.weights * value.T.dot(self.restriction) + else: + return (self.weights * value.T) + + grad = deriv + + def deriv2(self, params): + """second derivative of penalty function w.r.t. params + + Parameter + --------- + params : ndarray + array of parameters at which derivative is evaluated + + Returns + ------- + deriv2 : ndarray, 2-D + second derivative matrix + """ + + if self.restriction is not None: + params = self.restriction.dot(params) + + value = self.penalty.deriv2(params) + + if self.restriction is not None: + # note: univariate penalty returns 1d array for diag, + # i.e. hessian_diag + v = (self.restriction.T * value * self.weights) + value = v.dot(self.restriction) + else: + value = np.diag(self.weights * value) + + return value + + +class L2ConstraintsPenalty(ConstraintsPenalty): + """convenience class of ConstraintsPenalty with L2 penalization + """ + + def __init__(self, weights=None, restriction=None, sigma_prior=None): + + if sigma_prior is not None: + raise NotImplementedError('sigma_prior is not implemented yet') + + penalty = L2Univariate() + + super().__init__(penalty, weights=weights, + restriction=restriction) + + +class CovariancePenalty: + + def __init__(self, weight): + # weight should be scalar + self.weight = weight + + def func(self, mat, mat_inv): + """ + Parameters + ---------- + mat : square matrix + The matrix to be penalized. + mat_inv : square matrix + The inverse of `mat`. + + Returns + ------- + A scalar penalty value + """ + raise NotImplementedError + + def deriv(self, mat, mat_inv): + """ + Parameters + ---------- + mat : square matrix + The matrix to be penalized. + mat_inv : square matrix + The inverse of `mat`. + + Returns + ------- + A vector containing the gradient of the penalty + with respect to each element in the lower triangle + of `mat`. + """ + raise NotImplementedError + + +class PSD(CovariancePenalty): + """ + A penalty that converges to +infinity as the argument matrix + approaches the boundary of the domain of symmetric, positive + definite matrices. + """ + + def func(self, mat, mat_inv): + try: + cy = np.linalg.cholesky(mat) + except np.linalg.LinAlgError: + return np.inf + return -2 * self.weight * np.sum(np.log(np.diag(cy))) + + def deriv(self, mat, mat_inv): + cy = mat_inv.copy() + cy = 2*cy - np.diag(np.diag(cy)) + i,j = np.tril_indices(mat.shape[0]) + return -self.weight * cy[i,j] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/_prediction_inference.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/_prediction_inference.py new file mode 100644 index 0000000000000000000000000000000000000000..7e95912761e5a2e985f0852655ec6906dee55091 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/_prediction_inference.py @@ -0,0 +1,845 @@ +""" +Created on Fri Dec 19 11:29:18 2014 + +Author: Josef Perktold +License: BSD-3 + +""" + +import numpy as np +from scipy import stats +import pandas as pd + + +# this is similar to ContrastResults after t_test, partially copied, adjusted +class PredictionResultsBase: + """Based class for get_prediction results + """ + + def __init__(self, predicted, var_pred, func=None, deriv=None, + df=None, dist=None, row_labels=None, **kwds): + self.predicted = predicted + self.var_pred = var_pred + self.func = func + self.deriv = deriv + self.df = df + self.row_labels = row_labels + self.__dict__.update(kwds) + + if dist is None or dist == 'norm': + self.dist = stats.norm + self.dist_args = () + elif dist == 't': + self.dist = stats.t + self.dist_args = (self.df,) + else: + self.dist = dist + self.dist_args = () + + @property + def se(self): + return np.sqrt(self.var_pred) + + @property + def tvalues(self): + return self.predicted / self.se + + def t_test(self, value=0, alternative='two-sided'): + '''z- or t-test for hypothesis that mean is equal to value + + Parameters + ---------- + value : array_like + value under the null hypothesis + alternative : str + 'two-sided', 'larger', 'smaller' + + Returns + ------- + stat : ndarray + test statistic + pvalue : ndarray + p-value of the hypothesis test, the distribution is given by + the attribute of the instance, specified in `__init__`. Default + if not specified is the normal distribution. + + ''' + # assumes symmetric distribution + stat = (self.predicted - value) / self.se + + if alternative in ['two-sided', '2-sided', '2s']: + pvalue = self.dist.sf(np.abs(stat), *self.dist_args)*2 + elif alternative in ['larger', 'l']: + pvalue = self.dist.sf(stat, *self.dist_args) + elif alternative in ['smaller', 's']: + pvalue = self.dist.cdf(stat, *self.dist_args) + else: + raise ValueError('invalid alternative') + return stat, pvalue + + def _conf_int_generic(self, center, se, alpha, dist_args=None): + """internal function to avoid code duplication + """ + if dist_args is None: + dist_args = () + + q = self.dist.ppf(1 - alpha / 2., *dist_args) + lower = center - q * se + upper = center + q * se + ci = np.column_stack((lower, upper)) + # if we want to stack at a new last axis, for lower.ndim > 1 + # np.concatenate((lower[..., None], upper[..., None]), axis=-1) + return ci + + def conf_int(self, *, alpha=0.05, **kwds): + """Confidence interval for the predicted value. + + Parameters + ---------- + alpha : float, optional + The significance level for the confidence interval. + ie., The default `alpha` = .05 returns a 95% confidence interval. + + kwds : extra keyword arguments + Ignored in base class, only for compatibility, consistent signature + with subclasses + + Returns + ------- + ci : ndarray, (k_constraints, 2) + The array has the lower and the upper limit of the confidence + interval in the columns. + """ + + ci = self._conf_int_generic(self.predicted, self.se, alpha, + dist_args=self.dist_args) + return ci + + def summary_frame(self, alpha=0.05): + """Summary frame + + Parameters + ---------- + alpha : float, optional + The significance level for the confidence interval. + ie., The default `alpha` = .05 returns a 95% confidence interval. + + Returns + ------- + pandas DataFrame with columns 'predicted', 'se', 'ci_lower', 'ci_upper' + """ + ci = self.conf_int(alpha=alpha) + to_include = {} + to_include['predicted'] = self.predicted + to_include['se'] = self.se + to_include['ci_lower'] = ci[:, 0] + to_include['ci_upper'] = ci[:, 1] + + self.table = to_include + # pandas dict does not handle 2d_array + # data = np.column_stack(list(to_include.values())) + # names = .... + res = pd.DataFrame(to_include, index=self.row_labels, + columns=to_include.keys()) + return res + + +class PredictionResultsMonotonic(PredictionResultsBase): + + def __init__(self, predicted, var_pred, linpred=None, linpred_se=None, + func=None, deriv=None, df=None, dist=None, row_labels=None): + # TODO: is var_resid used? drop from arguments? + self.predicted = predicted + self.var_pred = var_pred + self.linpred = linpred + self.linpred_se = linpred_se + self.func = func + self.deriv = deriv + self.df = df + self.row_labels = row_labels + + if dist is None or dist == 'norm': + self.dist = stats.norm + self.dist_args = () + elif dist == 't': + self.dist = stats.t + self.dist_args = (self.df,) + else: + self.dist = dist + self.dist_args = () + + def _conf_int_generic(self, center, se, alpha, dist_args=None): + """internal function to avoid code duplication + """ + if dist_args is None: + dist_args = () + + q = self.dist.ppf(1 - alpha / 2., *dist_args) + lower = center - q * se + upper = center + q * se + ci = np.column_stack((lower, upper)) + # if we want to stack at a new last axis, for lower.ndim > 1 + # np.concatenate((lower[..., None], upper[..., None]), axis=-1) + return ci + + def conf_int(self, method='endpoint', alpha=0.05, **kwds): + """Confidence interval for the predicted value. + + This is currently only available for t and z tests. + + Parameters + ---------- + method : {"endpoint", "delta"} + Method for confidence interval, "m + If method is "endpoint", then the confidence interval of the + linear predictor is transformed by the prediction function. + If method is "delta", then the delta-method is used. The confidence + interval in this case might reach outside the range of the + prediction, for example probabilities larger than one or smaller + than zero. + alpha : float, optional + The significance level for the confidence interval. + ie., The default `alpha` = .05 returns a 95% confidence interval. + kwds : extra keyword arguments + currently ignored, only for compatibility, consistent signature + + Returns + ------- + ci : ndarray, (k_constraints, 2) + The array has the lower and the upper limit of the confidence + interval in the columns. + """ + tmp = np.linspace(0, 1, 6) + # TODO: drop check? + is_linear = (self.func(tmp) == tmp).all() + if method == 'endpoint' and not is_linear: + ci_linear = self._conf_int_generic(self.linpred, self.linpred_se, + alpha, + dist_args=self.dist_args) + ci = self.func(ci_linear) + elif method == 'delta' or is_linear: + ci = self._conf_int_generic(self.predicted, self.se, alpha, + dist_args=self.dist_args) + + return ci + + +class PredictionResultsDelta(PredictionResultsBase): + """Prediction results based on delta method + """ + + def __init__(self, results_delta, **kwds): + + predicted = results_delta.predicted() + var_pred = results_delta.var() + + super().__init__(predicted, var_pred, **kwds) + + +class PredictionResultsMean(PredictionResultsBase): + """Prediction results for GLM. + + This results class is used for backwards compatibility for + `get_prediction` with GLM. The new PredictionResults classes dropped the + `_mean` post fix in the attribute names. + """ + + def __init__(self, predicted_mean, var_pred_mean, var_resid=None, + df=None, dist=None, row_labels=None, linpred=None, link=None): + # TODO: is var_resid used? drop from arguments? + self.predicted = predicted_mean + self.var_pred = var_pred_mean + self.df = df + self.var_resid = var_resid + self.row_labels = row_labels + self.linpred = linpred + self.link = link + + if dist is None or dist == 'norm': + self.dist = stats.norm + self.dist_args = () + elif dist == 't': + self.dist = stats.t + self.dist_args = (self.df,) + else: + self.dist = dist + self.dist_args = () + + @property + def predicted_mean(self): + # alias for backwards compatibility + return self.predicted + + @property + def var_pred_mean(self): + # alias for backwards compatibility + return self.var_pred + + @property + def se_mean(self): + # alias for backwards compatibility + return self.se + + def conf_int(self, method='endpoint', alpha=0.05, **kwds): + """Confidence interval for the predicted value. + + This is currently only available for t and z tests. + + Parameters + ---------- + method : {"endpoint", "delta"} + Method for confidence interval, "m + If method is "endpoint", then the confidence interval of the + linear predictor is transformed by the prediction function. + If method is "delta", then the delta-method is used. The confidence + interval in this case might reach outside the range of the + prediction, for example probabilities larger than one or smaller + than zero. + alpha : float, optional + The significance level for the confidence interval. + ie., The default `alpha` = .05 returns a 95% confidence interval. + kwds : extra keyword arguments + currently ignored, only for compatibility, consistent signature + + Returns + ------- + ci : ndarray, (k_constraints, 2) + The array has the lower and the upper limit of the confidence + interval in the columns. + """ + tmp = np.linspace(0, 1, 6) + is_linear = (self.link.inverse(tmp) == tmp).all() + if method == 'endpoint' and not is_linear: + ci_linear = self.linpred.conf_int(alpha=alpha, obs=False) + ci = self.link.inverse(ci_linear) + elif method == 'delta' or is_linear: + se = self.se_mean + q = self.dist.ppf(1 - alpha / 2., *self.dist_args) + lower = self.predicted_mean - q * se + upper = self.predicted_mean + q * se + ci = np.column_stack((lower, upper)) + # if we want to stack at a new last axis, for lower.ndim > 1 + # np.concatenate((lower[..., None], upper[..., None]), axis=-1) + + return ci + + def summary_frame(self, alpha=0.05): + """Summary frame + + Parameters + ---------- + alpha : float, optional + The significance level for the confidence interval. + ie., The default `alpha` = .05 returns a 95% confidence interval. + + Returns + ------- + pandas DataFrame with columns + 'mean', 'mean_se', 'mean_ci_lower', 'mean_ci_upper'. + """ + # TODO: finish and cleanup + ci_mean = self.conf_int(alpha=alpha) + to_include = {} + to_include['mean'] = self.predicted_mean + to_include['mean_se'] = self.se_mean + to_include['mean_ci_lower'] = ci_mean[:, 0] + to_include['mean_ci_upper'] = ci_mean[:, 1] + + self.table = to_include + # pandas dict does not handle 2d_array + # data = np.column_stack(list(to_include.values())) + # names = .... + res = pd.DataFrame(to_include, index=self.row_labels, + columns=to_include.keys()) + return res + + +def _get_exog_predict(self, exog=None, transform=True, row_labels=None): + """Prepare or transform exog for prediction + + Parameters + ---------- + exog : array_like, optional + The values for which you want to predict. + transform : bool, optional + If the model was fit via a formula, do you want to pass + exog through the formula. Default is True. E.g., if you fit + a model y ~ log(x1) + log(x2), and transform is True, then + you can pass a data structure that contains x1 and x2 in + their original form. Otherwise, you'd need to log the data + first. + row_labels : list of str or None + If row_lables are provided, then they will replace the generated + labels. + + Returns + ------- + exog : ndarray + Prediction exog + row_labels : list of str + Labels or pandas index for rows of prediction + """ + + # prepare exog and row_labels, based on base Results.predict + if transform and hasattr(self.model, 'formula') and exog is not None: + from patsy import dmatrix + if isinstance(exog, pd.Series): + exog = pd.DataFrame(exog) + exog = dmatrix(self.model.data.design_info, exog) + + if exog is not None: + if row_labels is None: + row_labels = getattr(exog, 'index', None) + if callable(row_labels): + row_labels = None + + exog = np.asarray(exog) + if exog.ndim == 1 and (self.model.exog.ndim == 1 or + self.model.exog.shape[1] == 1): + exog = exog[:, None] + exog = np.atleast_2d(exog) # needed in count model shape[1] + else: + exog = self.model.exog + + if row_labels is None: + row_labels = getattr(self.model.data, 'row_labels', None) + return exog, row_labels + + +def get_prediction_glm(self, exog=None, transform=True, + row_labels=None, linpred=None, link=None, + pred_kwds=None): + """ + Compute prediction results for GLM compatible models. + + Parameters + ---------- + exog : array_like, optional + The values for which you want to predict. + transform : bool, optional + If the model was fit via a formula, do you want to pass + exog through the formula. Default is True. E.g., if you fit + a model y ~ log(x1) + log(x2), and transform is True, then + you can pass a data structure that contains x1 and x2 in + their original form. Otherwise, you'd need to log the data + first. + row_labels : list of str or None + If row_lables are provided, then they will replace the generated + labels. + linpred : linear prediction instance + Instance of linear prediction results used for confidence intervals + based on endpoint transformation. + link : instance of link function + If no link function is provided, then the `model.family.link` is used. + pred_kwds : dict + Some models can take additional keyword arguments, such as offset or + additional exog in multi-part models. See the predict method of the + model for the details. + + Returns + ------- + prediction_results : generalized_linear_model.PredictionResults + The prediction results instance contains prediction and prediction + variance and can on demand calculate confidence intervals and summary + tables for the prediction of the mean and of new observations. + """ + + # prepare exog and row_labels, based on base Results.predict + exog, row_labels = _get_exog_predict( + self, + exog=exog, + transform=transform, + row_labels=row_labels, + ) + + if pred_kwds is None: + pred_kwds = {} + + predicted_mean = self.model.predict(self.params, exog, **pred_kwds) + + covb = self.cov_params() + + link_deriv = self.model.family.link.inverse_deriv(linpred.predicted_mean) + var_pred_mean = link_deriv**2 * (exog * np.dot(covb, exog.T).T).sum(1) + var_resid = self.scale # self.mse_resid / weights + + # TODO: check that we have correct scale, Refactor scale #??? + # special case for now: + if self.cov_type == 'fixed scale': + var_resid = self.cov_kwds['scale'] + + dist = ['norm', 't'][self.use_t] + return PredictionResultsMean( + predicted_mean, var_pred_mean, var_resid, + df=self.df_resid, dist=dist, + row_labels=row_labels, linpred=linpred, link=link) + + +def get_prediction_linear(self, exog=None, transform=True, + row_labels=None, pred_kwds=None, index=None): + """ + Compute prediction results for linear prediction. + + Parameters + ---------- + exog : array_like, optional + The values for which you want to predict. + transform : bool, optional + If the model was fit via a formula, do you want to pass + exog through the formula. Default is True. E.g., if you fit + a model y ~ log(x1) + log(x2), and transform is True, then + you can pass a data structure that contains x1 and x2 in + their original form. Otherwise, you'd need to log the data + first. + row_labels : list of str or None + If row_lables are provided, then they will replace the generated + labels. + pred_kwargs : + Some models can take additional keyword arguments, such as offset or + additional exog in multi-part models. + See the predict method of the model for the details. + index : slice or array-index + Is used to select rows and columns of cov_params, if the prediction + function only depends on a subset of parameters. + + Returns + ------- + prediction_results : PredictionResults + The prediction results instance contains prediction and prediction + variance and can on demand calculate confidence intervals and summary + tables for the prediction. + """ + + # prepare exog and row_labels, based on base Results.predict + exog, row_labels = _get_exog_predict( + self, + exog=exog, + transform=transform, + row_labels=row_labels, + ) + + if pred_kwds is None: + pred_kwds = {} + + k1 = exog.shape[1] + if len(self.params > k1): + # TODO: we allow endpoint transformation only for the first link + index = np.arange(k1) + else: + index = None + # get linear prediction and standard errors + covb = self.cov_params(column=index) + var_pred = (exog * np.dot(covb, exog.T).T).sum(1) + pred_kwds_linear = pred_kwds.copy() + pred_kwds_linear["which"] = "linear" + predicted = self.model.predict(self.params, exog, **pred_kwds_linear) + + dist = ['norm', 't'][self.use_t] + res = PredictionResultsBase(predicted, var_pred, + df=self.df_resid, dist=dist, + row_labels=row_labels + ) + return res + + +def get_prediction_monotonic(self, exog=None, transform=True, + row_labels=None, link=None, + pred_kwds=None, index=None): + """ + Compute prediction results when endpoint transformation is valid. + + Parameters + ---------- + exog : array_like, optional + The values for which you want to predict. + transform : bool, optional + If the model was fit via a formula, do you want to pass + exog through the formula. Default is True. E.g., if you fit + a model y ~ log(x1) + log(x2), and transform is True, then + you can pass a data structure that contains x1 and x2 in + their original form. Otherwise, you'd need to log the data + first. + row_labels : list of str or None + If row_lables are provided, then they will replace the generated + labels. + link : instance of link function + If no link function is provided, then the ``mmodel.family.link` is + used. + pred_kwargs : + Some models can take additional keyword arguments, such as offset or + additional exog in multi-part models. + See the predict method of the model for the details. + index : slice or array-index + Is used to select rows and columns of cov_params, if the prediction + function only depends on a subset of parameters. + + Returns + ------- + prediction_results : PredictionResults + The prediction results instance contains prediction and prediction + variance and can on demand calculate confidence intervals and summary + tables for the prediction. + """ + + # prepare exog and row_labels, based on base Results.predict + exog, row_labels = _get_exog_predict( + self, + exog=exog, + transform=transform, + row_labels=row_labels, + ) + + if pred_kwds is None: + pred_kwds = {} + + if link is None: + link = self.model.family.link + + func_deriv = link.inverse_deriv + + # get linear prediction and standard errors + covb = self.cov_params(column=index) + linpred_var = (exog * np.dot(covb, exog.T).T).sum(1) + pred_kwds_linear = pred_kwds.copy() + pred_kwds_linear["which"] = "linear" + linpred = self.model.predict(self.params, exog, **pred_kwds_linear) + + predicted = self.model.predict(self.params, exog, **pred_kwds) + link_deriv = func_deriv(linpred) + var_pred = link_deriv**2 * linpred_var + + dist = ['norm', 't'][self.use_t] + res = PredictionResultsMonotonic(predicted, var_pred, + df=self.df_resid, dist=dist, + row_labels=row_labels, linpred=linpred, + linpred_se=np.sqrt(linpred_var), + func=link.inverse, deriv=func_deriv) + return res + + +def get_prediction_delta( + self, + exog=None, + which="mean", + average=False, + agg_weights=None, + transform=True, + row_labels=None, + pred_kwds=None + ): + """ + compute prediction results + + Parameters + ---------- + exog : array_like, optional + The values for which you want to predict. + which : str + The statistic that is prediction. Which statistics are available + depends on the model.predict method. + average : bool + If average is True, then the mean prediction is computed, that is, + predictions are computed for individual exog and then them mean over + observation is used. + If average is False, then the results are the predictions for all + observations, i.e. same length as ``exog``. + agg_weights : ndarray, optional + Aggregation weights, only used if average is True. + The weights are not normalized. + transform : bool, optional + If the model was fit via a formula, do you want to pass + exog through the formula. Default is True. E.g., if you fit + a model y ~ log(x1) + log(x2), and transform is True, then + you can pass a data structure that contains x1 and x2 in + their original form. Otherwise, you'd need to log the data + first. + row_labels : list of str or None + If row_lables are provided, then they will replace the generated + labels. + pred_kwargs : + Some models can take additional keyword arguments, such as offset or + additional exog in multi-part models. + See the predict method of the model for the details. + + Returns + ------- + prediction_results : generalized_linear_model.PredictionResults + The prediction results instance contains prediction and prediction + variance and can on demand calculate confidence intervals and summary + tables for the prediction of the mean and of new observations. + """ + + # prepare exog and row_labels, based on base Results.predict + exog, row_labels = _get_exog_predict( + self, + exog=exog, + transform=transform, + row_labels=row_labels, + ) + if agg_weights is None: + agg_weights = np.array(1.) + + def f_pred(p): + """Prediction function as function of params + """ + pred = self.model.predict(p, exog, which=which, **pred_kwds) + if average: + # using `.T` which should work if aggweights is 1-dim + pred = (pred.T * agg_weights.T).mean(-1).T + return pred + + nlpm = self._get_wald_nonlinear(f_pred) + # TODO: currently returns NonlinearDeltaCov + res = PredictionResultsDelta(nlpm) + return res + + +def get_prediction(self, exog=None, transform=True, which="mean", + row_labels=None, average=False, agg_weights=None, + pred_kwds=None): + """ + Compute prediction results when endpoint transformation is valid. + + Parameters + ---------- + exog : array_like, optional + The values for which you want to predict. + transform : bool, optional + If the model was fit via a formula, do you want to pass + exog through the formula. Default is True. E.g., if you fit + a model y ~ log(x1) + log(x2), and transform is True, then + you can pass a data structure that contains x1 and x2 in + their original form. Otherwise, you'd need to log the data + first. + which : str + Which statistic is to be predicted. Default is "mean". + The available statistics and options depend on the model. + see the model.predict docstring + linear : bool + Linear has been replaced by the `which` keyword and will be + deprecated. + If linear is True, then `which` is ignored and the linear + prediction is returned. + row_labels : list of str or None + If row_lables are provided, then they will replace the generated + labels. + average : bool + If average is True, then the mean prediction is computed, that is, + predictions are computed for individual exog and then the average + over observation is used. + If average is False, then the results are the predictions for all + observations, i.e. same length as ``exog``. + agg_weights : ndarray, optional + Aggregation weights, only used if average is True. + The weights are not normalized. + **kwargs : + Some models can take additional keyword arguments, such as offset, + exposure or additional exog in multi-part models like zero inflated + models. + See the predict method of the model for the details. + + Returns + ------- + prediction_results : PredictionResults + The prediction results instance contains prediction and prediction + variance and can on demand calculate confidence intervals and + summary dataframe for the prediction. + + Notes + ----- + Status: new in 0.14, experimental + """ + use_endpoint = getattr(self.model, "_use_endpoint", True) + + if which == "linear": + res = get_prediction_linear( + self, + exog=exog, + transform=transform, + row_labels=row_labels, + pred_kwds=pred_kwds, + ) + + elif (which == "mean")and (use_endpoint is True) and (average is False): + # endpoint transformation + k1 = self.model.exog.shape[1] + if len(self.params > k1): + # TODO: we allow endpoint transformation only for the first link + index = np.arange(k1) + else: + index = None + + pred_kwds["which"] = which + # TODO: add link or ilink to all link based models (except zi + link = getattr(self.model, "link", None) + if link is None: + # GLM + if hasattr(self.model, "family"): + link = getattr(self.model.family, "link", None) + if link is None: + # defaulting to log link for count models + import warnings + warnings.warn("using default log-link in get_prediction") + from statsmodels.genmod.families import links + link = links.Log() + res = get_prediction_monotonic( + self, + exog=exog, + transform=transform, + row_labels=row_labels, + link=link, + pred_kwds=pred_kwds, + index=index, + ) + + else: + # which is not mean or linear, or we need averaging + res = get_prediction_delta( + self, + exog=exog, + which=which, + average=average, + agg_weights=agg_weights, + pred_kwds=pred_kwds, + ) + + return res + + +def params_transform_univariate(params, cov_params, link=None, transform=None, + row_labels=None): + """ + results for univariate, nonlinear, monotonicaly transformed parameters + + This provides transformed values, standard errors and confidence interval + for transformations of parameters, for example in calculating rates with + `exp(params)` in the case of Poisson or other models with exponential + mean function. + """ + + from statsmodels.genmod.families import links + if link is None and transform is None: + link = links.Log() + + if row_labels is None and hasattr(params, 'index'): + row_labels = params.index + + params = np.asarray(params) + + predicted_mean = link.inverse(params) + link_deriv = link.inverse_deriv(params) + var_pred_mean = link_deriv**2 * np.diag(cov_params) + # TODO: do we want covariance also, or just var/se + + dist = stats.norm + + # TODO: need ci for linear prediction, method of `lin_pred + linpred = PredictionResultsMean( + params, np.diag(cov_params), dist=dist, + row_labels=row_labels, link=links.Identity()) + + res = PredictionResultsMean( + predicted_mean, var_pred_mean, dist=dist, + row_labels=row_labels, linpred=linpred, link=link) + + return res diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/_screening.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/_screening.py new file mode 100644 index 0000000000000000000000000000000000000000..9460756f3c4316e0ac9bc9a474af4ad77e68dd80 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/_screening.py @@ -0,0 +1,431 @@ +""" +Created on Sat May 19 15:53:21 2018 + +Author: Josef Perktold +License: BSD-3 +""" + +from collections import defaultdict +import numpy as np + +from statsmodels.base._penalties import SCADSmoothed + + +class ScreeningResults: + """Results for Variable Screening + + Note: Indices except for exog_idx and in the iterated case also + idx_nonzero_batches are based on the combined [exog_keep, exog] array. + + Attributes + ---------- + results_final : instance + Results instance returned by the final fit of the penalized model, i.e. + after trimming exog with params below trimming threshold. + results_pen : results instance + Results instance of the penalized model before trimming. This includes + variables from the last forward selection + idx_nonzero + index of exog columns in the final selection including exog_keep + idx_exog + index of exog columns in the final selection for exog candidates, i.e. + without exog_keep + idx_excl + idx of excluded exog based on combined [exog_keep, exog] array. This is + the complement of idx_nonzero + converged : bool + True if the iteration has converged and stopped before maxiter has been + reached. False if maxiter has been reached. + iterations : int + number of iterations in the screening process. Each iteration consists + of a forward selection step and a trimming step. + history : dict of lists + results collected for each iteration during the screening process + 'idx_nonzero' 'params_keep'].append(start_params) + history['idx_added'].append(idx) + + The ScreeningResults returned by `screen_exog_iterator` has additional + attributes: + + idx_nonzero_batches : ndarray 2-D + Two-dimensional array with batch index in the first column and variable + index withing batch in the second column. They can be used jointly as + index for the data in the exog_iterator. + exog_final_names : list[str] + 'var_' where `bidx` is the batch index and `idx` is the + index of the selected column withing batch `bidx`. + history_batches : dict of lists + This provides information about the selected variables within each + batch during the first round screening + 'idx_nonzero' is based ond the array that includes exog_keep, while + 'idx_exog' is the index based on the exog of the batch. + """ + def __init__(self, screener, **kwds): + self.screener = screener + self.__dict__.update(**kwds) + + +class VariableScreening: + """Ultra-high, conditional sure independence screening + + This is an adjusted version of Fan's sure independence screening. + + Parameters + ---------- + model : instance of penalizing model + examples: GLMPenalized, PoissonPenalized and LogitPenalized. + The attributes of the model instance `pen_weight` and `penal` will be + ignored. + pen_weight : None or float + penalization weight use in SCAD penalized MLE + k_add : int + number of exog to add during expansion or forward selection + see Notes section for tie handling + k_max_add : int + maximum number of variables to include during variable addition, i.e. + forward selection. default is 30 + threshold_trim : float + threshold for trimming parameters to zero, default is 1e-4 + k_max_included : int + maximum total number of variables to include in model. + ranking_attr : str + This determines the result attribute or model method that is used for + the ranking of exog to include. The availability of attributes depends + on the model. + Default is 'resid_pearson', 'model.score_factor' can be used in GLM. + ranking_project : bool + If ranking_project is True, then the exog candidates for inclusion are + first projected on the already included exog before the computation + of the ranking measure. This brings the ranking measure closer to + the statistic of a score test for variable addition. + + Notes + ----- + Status: experimental, tested only on a limited set of models and + with a limited set of model options. + + Tie handling: If there are ties at the decision threshold, then all those + tied exog columns are treated in the same way. During forward selection + all exog columns with the same boundary value are included. During + elimination, the tied columns are not dropped. Consequently, if ties are + present, then the number of included exog can be larger than specified + by k_add, k_max_add and k_max_included. + + The screening algorithm works similar to step wise regression. Each + iteration of the screening algorithm includes a forward selection step + where variables are added to the model, and a backwards selection step + where variables are removed. In contrast to step wise regression, we add + a fixed number of variables at each forward selection step. The + backwards selection step is based on SCAD penalized estimation and + trimming of variables with estimated coefficients below a threshold. + The tuning parameters can be used to adjust the number of variables to add + and to include depending on the size of the dataset. + + There is currently no automatic tuning parameter selection. Candidate + explanatory variables should be standardized or should be on a similar + scale because penalization and trimming are based on the absolute values + of the parameters. + + + TODOs and current limitations: + + freq_weights are not supported in this. Candidate ranking uses + moment condition with resid_pearson or others without freq_weights. + pearson_resid: GLM resid_pearson does not include freq_weights. + + variable names: do we keep track of those? currently made-up names + + currently only supports numpy arrays, no exog type check or conversion + + currently only single columns are selected, no terms (multi column exog) + """ + + def __init__(self, model, pen_weight=None, use_weights=True, k_add=30, + k_max_add=30, threshold_trim=1e-4, k_max_included=20, + ranking_attr='resid_pearson', ranking_project=True): + + self.model = model + self.model_class = model.__class__ + self.init_kwds = model._get_init_kwds() + # pen_weight and penal are explicitly included + # TODO: check what we want to do here + self.init_kwds.pop('pen_weight', None) + self.init_kwds.pop('penal', None) + + self.endog = model.endog + self.exog_keep = model.exog + self.k_keep = model.exog.shape[1] + self.nobs = len(self.endog) + self.penal = self._get_penal() + + if pen_weight is not None: + self.pen_weight = pen_weight + else: + self.pen_weight = self.nobs * 10 + + # option for screening algorithm + self.use_weights = use_weights + self.k_add = k_add + self.k_max_add = k_max_add + self.threshold_trim = threshold_trim + self.k_max_included = k_max_included + self.ranking_attr = ranking_attr + self.ranking_project = ranking_project + + def _get_penal(self, weights=None): + """create new Penalty instance + """ + return SCADSmoothed(0.1, c0=0.0001, weights=weights) + + def ranking_measure(self, res_pen, exog, keep=None): + """compute measure for ranking exog candidates for inclusion + """ + endog = self.endog + + if self.ranking_project: + assert res_pen.model.exog.shape[1] == len(keep) + ex_incl = res_pen.model.exog[:, keep] + exog = exog - ex_incl.dot(np.linalg.pinv(ex_incl).dot(exog)) + + if self.ranking_attr == 'predicted_poisson': + # I keep this for more experiments + + # TODO: does it really help to change/trim params + # we are not reestimating with trimmed model + p = res_pen.params.copy() + if keep is not None: + p[~keep] = 0 + predicted = res_pen.model.predict(p) + # this is currently hardcoded for Poisson + resid_factor = (endog - predicted) / np.sqrt(predicted) + elif self.ranking_attr[:6] == 'model.': + # use model method, this is intended for score_factor + attr = self.ranking_attr.split('.')[1] + resid_factor = getattr(res_pen.model, attr)(res_pen.params) + if resid_factor.ndim == 2: + # for score_factor when extra params are in model + resid_factor = resid_factor[:, 0] + mom_cond = np.abs(resid_factor.dot(exog))**2 + else: + # use results attribute + resid_factor = getattr(res_pen, self.ranking_attr) + mom_cond = np.abs(resid_factor.dot(exog))**2 + return mom_cond + + def screen_exog(self, exog, endog=None, maxiter=100, method='bfgs', + disp=False, fit_kwds=None): + """screen and select variables (columns) in exog + + Parameters + ---------- + exog : ndarray + candidate explanatory variables that are screened for inclusion in + the model + endog : ndarray (optional) + use a new endog in the screening model. + This is not tested yet, and might not work correctly + maxiter : int + number of screening iterations + method : str + optimization method to use in fit, needs to be only of the gradient + optimizers + disp : bool + display option for fit during optimization + + Returns + ------- + res_screen : instance of ScreeningResults + The attribute `results_final` contains is the results instance + with the final model selection. + `idx_nonzero` contains the index of the selected exog in the full + exog, combined exog that are always kept plust exog_candidates. + see ScreeningResults for a full description + """ + model_class = self.model_class + if endog is None: + # allow a different endog than used in model + endog = self.endog + x0 = self.exog_keep + k_keep = self.k_keep + x1 = exog + k_current = x0.shape[1] + # TODO: remove the need for x, use x1 separately from x0 + # needs change to idx to be based on x1 (candidate variables) + x = np.column_stack((x0, x1)) + nobs, k_vars = x.shape + fkwds = fit_kwds if fit_kwds is not None else {} + fit_kwds = {'maxiter': 200, 'disp': False} + fit_kwds.update(fkwds) + + history = defaultdict(list) + idx_nonzero = np.arange(k_keep, dtype=int) + keep = np.ones(k_keep, np.bool_) + idx_excl = np.arange(k_keep, k_vars) + mod_pen = model_class(endog, x0, **self.init_kwds) + # do not penalize initial estimate + mod_pen.pen_weight = 0 + res_pen = mod_pen.fit(**fit_kwds) + start_params = res_pen.params + converged = False + idx_old = [] + for it in range(maxiter): + # candidates for inclusion in next iteration + x1 = x[:, idx_excl] + mom_cond = self.ranking_measure(res_pen, x1, keep=keep) + assert len(mom_cond) == len(idx_excl) + mcs = np.sort(mom_cond)[::-1] + idx_thr = min((self.k_max_add, k_current + self.k_add, len(mcs))) + threshold = mcs[idx_thr] + # indices of exog in current expansion model + idx = np.concatenate((idx_nonzero, idx_excl[mom_cond > threshold])) + start_params2 = np.zeros(len(idx)) + start_params2[:len(start_params)] = start_params + + if self.use_weights: + weights = np.ones(len(idx)) + weights[:k_keep] = 0 + # modify Penalty instance attached to self + # damgerous if res_pen is reused + self.penal.weights = weights + mod_pen = model_class(endog, x[:, idx], penal=self.penal, + pen_weight=self.pen_weight, + **self.init_kwds) + + res_pen = mod_pen.fit(method=method, + start_params=start_params2, + warn_convergence=False, skip_hessian=True, + **fit_kwds) + + keep = np.abs(res_pen.params) > self.threshold_trim + # use largest params to keep + if keep.sum() > self.k_max_included: + # TODO we can use now np.partition with partial sort + thresh_params = np.sort(np.abs(res_pen.params))[ + -self.k_max_included] + keep2 = np.abs(res_pen.params) > thresh_params + keep = np.logical_and(keep, keep2) + + # Note: idx and keep are for current expansion model + # idx_nonzero has indices of selected variables in full exog + keep[:k_keep] = True # always keep exog_keep + idx_nonzero = idx[keep] + + if disp: + print(keep) + print(idx_nonzero) + # x0 is exog of currently selected model, not used in iteration + # x0 = x[:, idx_nonzero] + k_current = len(idx_nonzero) + start_params = res_pen.params[keep] + + # use mask to get excluded indices + mask_excl = np.ones(k_vars, dtype=bool) + mask_excl[idx_nonzero] = False + idx_excl = np.nonzero(mask_excl)[0] + history['idx_nonzero'].append(idx_nonzero) + history['keep'].append(keep) + history['params_keep'].append(start_params) + history['idx_added'].append(idx) + + if (len(idx_nonzero) == len(idx_old) and + (idx_nonzero == idx_old).all()): + converged = True + break + idx_old = idx_nonzero + + # final esimate + # check that we still have exog_keep + assert np.all(idx_nonzero[:k_keep] == np.arange(k_keep)) + if self.use_weights: + weights = np.ones(len(idx_nonzero)) + weights[:k_keep] = 0 + # create new Penalty instance to avoide sharing attached penal + penal = self._get_penal(weights=weights) + else: + penal = self.penal + mod_final = model_class(endog, x[:, idx_nonzero], + penal=penal, + pen_weight=self.pen_weight, + **self.init_kwds) + + res_final = mod_final.fit(method=method, + start_params=start_params, + warn_convergence=False, + **fit_kwds) + # set exog_names for final model + xnames = ['var%4d' % ii for ii in idx_nonzero] + res_final.model.exog_names[k_keep:] = xnames[k_keep:] + + res = ScreeningResults(self, + results_pen = res_pen, + results_final = res_final, + idx_nonzero = idx_nonzero, + idx_exog = idx_nonzero[k_keep:] - k_keep, + idx_excl = idx_excl, + history = history, + converged = converged, + iterations = it + 1 # it is 0-based + ) + return res + + def screen_exog_iterator(self, exog_iterator): + """ + batched version of screen exog + + This screens variables in a two step process: + + In the first step screen_exog is used on each element of the + exog_iterator, and the batch winners are collected. + + In the second step all batch winners are combined into a new array + of exog candidates and `screen_exog` is used to select a final + model. + + Parameters + ---------- + exog_iterator : iterator over ndarrays + + Returns + ------- + res_screen_final : instance of ScreeningResults + This is the instance returned by the second round call to + `screen_exog`. Additional attributes are added to provide + more information about the batched selection process. + The index of final nonzero variables is + `idx_nonzero_batches` which is a 2-dimensional array with batch + index in the first column and variable index within batch in the + second column. They can be used jointly as index for the data + in the exog_iterator. + see ScreeningResults for a full description + """ + k_keep = self.k_keep + # res_batches = [] + res_idx = [] + exog_winner = [] + exog_idx = [] + for ex in exog_iterator: + res_screen = self.screen_exog(ex, maxiter=20) + # avoid storing res_screen, only for debugging + # res_batches.append(res_screen) + res_idx.append(res_screen.idx_nonzero) + exog_winner.append(ex[:, res_screen.idx_nonzero[k_keep:] - k_keep]) + exog_idx.append(res_screen.idx_nonzero[k_keep:] - k_keep) + + exog_winner = np.column_stack(exog_winner) + res_screen_final = self.screen_exog(exog_winner, maxiter=20) + + exog_winner_names = ['var%d_%d' % (bidx, idx) + for bidx, batch in enumerate(exog_idx) + for idx in batch] + + idx_full = [(bidx, idx) + for bidx, batch in enumerate(exog_idx) + for idx in batch] + ex_final_idx = res_screen_final.idx_nonzero[k_keep:] - k_keep + final_names = np.array(exog_winner_names)[ex_final_idx] + res_screen_final.idx_nonzero_batches = np.array(idx_full)[ex_final_idx] + res_screen_final.exog_final_names = final_names + history = {'idx_nonzero': res_idx, + 'idx_exog': exog_idx} + res_screen_final.history_batches = history + return res_screen_final diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/covtype.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/covtype.py new file mode 100644 index 0000000000000000000000000000000000000000..d0848499ca7aca5b5753a618b0c839c6a5d27879 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/covtype.py @@ -0,0 +1,368 @@ +""" +Created on Mon Aug 04 08:00:16 2014 + +Author: Josef Perktold +License: BSD-3 + +""" + +from statsmodels.compat.python import lzip + +import numpy as np + +descriptions = { + 'HC0': 'Standard Errors are heteroscedasticity robust (HC0)', + 'HC1': 'Standard Errors are heteroscedasticity robust (HC1)', + 'HC2': 'Standard Errors are heteroscedasticity robust (HC2)', + 'HC3': 'Standard Errors are heteroscedasticity robust (HC3)', + 'HAC': 'Standard Errors are heteroscedasticity and autocorrelation ' + 'robust (HAC) using {maxlags} lags and ' + '{correction} small sample correction', + 'fixed_scale': 'Standard Errors are based on fixed scale', + 'cluster': 'Standard Errors are robust to cluster correlation (cluster)', + 'HAC-Panel': 'Standard Errors are robust to ' + 'cluster correlation (HAC-Panel)', + 'HAC-Groupsum': 'Driscoll and Kraay Standard Errors are robust to ' + 'cluster correlation (HAC-Groupsum)', + 'none': 'Covariance matrix not calculated.', + 'approx': 'Covariance matrix calculated using numerical ({approx_type}) ' + 'differentiation.', + 'OPG': 'Covariance matrix calculated using the outer product of ' + 'gradients ({approx_type}).', + 'OIM': 'Covariance matrix calculated using the observed information ' + 'matrix ({approx_type}) described in Harvey (1989).', + 'robust': 'Quasi-maximum likelihood covariance matrix used for ' + 'robustness to some misspecifications; calculated using ' + 'numerical ({approx_type}) differentiation.', + 'robust-OIM': 'Quasi-maximum likelihood covariance matrix used for ' + 'robustness to some misspecifications; calculated using the ' + 'observed information matrix ({approx_type}) described in ' + 'Harvey (1989).', + 'robust-approx': 'Quasi-maximum likelihood covariance matrix used for ' + 'robustness to some misspecifications; calculated using ' + 'numerical ({approx_type}) differentiation.', +} + + +def normalize_cov_type(cov_type): + """ + Normalize the cov_type string to a canonical version + + Parameters + ---------- + cov_type : str + + Returns + ------- + normalized_cov_type : str + """ + if cov_type == 'nw-panel': + cov_type = 'hac-panel' + if cov_type == 'nw-groupsum': + cov_type = 'hac-groupsum' + return cov_type + + +def get_robustcov_results(self, cov_type='HC1', use_t=None, **kwds): + """create new results instance with robust covariance as default + + Parameters + ---------- + cov_type : str + the type of robust sandwich estimator to use. see Notes below + use_t : bool + If true, then the t distribution is used for inference. + If false, then the normal distribution is used. + kwds : depends on cov_type + Required or optional arguments for robust covariance calculation. + see Notes below + + Returns + ------- + results : results instance + This method creates a new results instance with the requested + robust covariance as the default covariance of the parameters. + Inferential statistics like p-values and hypothesis tests will be + based on this covariance matrix. + + Notes + ----- + Warning: Some of the options and defaults in cov_kwds may be changed in a + future version. + + The covariance keywords provide an option 'scaling_factor' to adjust the + scaling of the covariance matrix, that is the covariance is multiplied by + this factor if it is given and is not `None`. This allows the user to + adjust the scaling of the covariance matrix to match other statistical + packages. + For example, `scaling_factor=(nobs - 1.) / (nobs - k_params)` provides a + correction so that the robust covariance matrices match those of Stata in + some models like GLM and discrete Models. + + The following covariance types and required or optional arguments are + currently available: + + - 'HC0', 'HC1', 'HC2', 'HC3': heteroscedasticity robust covariance + + - no keyword arguments + + - 'HAC': heteroskedasticity-autocorrelation robust covariance + + ``maxlags`` : integer, required + number of lags to use + + ``kernel`` : {callable, str}, optional + kernels currently available kernels are ['bartlett', 'uniform'], + default is Bartlett + + ``use_correction``: bool, optional + If true, use small sample correction + + - 'cluster': clustered covariance estimator + + ``groups`` : array_like[int], required : + Integer-valued index of clusters or groups. + + ``use_correction``: bool, optional + If True the sandwich covariance is calculated with a small + sample correction. + If False the sandwich covariance is calculated without + small sample correction. + + ``df_correction``: bool, optional + If True (default), then the degrees of freedom for the + inferential statistics and hypothesis tests, such as + pvalues, f_pvalue, conf_int, and t_test and f_test, are + based on the number of groups minus one instead of the + total number of observations minus the number of explanatory + variables. `df_resid` of the results instance is also + adjusted. When `use_t` is also True, then pvalues are + computed using the Student's t distribution using the + corrected values. These may differ substantially from + p-values based on the normal is the number of groups is + small. + If False, then `df_resid` of the results instance is not + adjusted. + + + - 'hac-groupsum': Driscoll and Kraay, heteroscedasticity and + autocorrelation robust covariance for panel data + # TODO: more options needed here + + ``time`` : array_like, required + index of time periods + ``maxlags`` : integer, required + number of lags to use + ``kernel`` : {callable, str}, optional + The available kernels are ['bartlett', 'uniform']. The default is + Bartlett. + ``use_correction`` : {False, 'hac', 'cluster'}, optional + If False the the sandwich covariance is calculated without small + sample correction. If `use_correction = 'cluster'` (default), + then the same small sample correction as in the case of + `covtype='cluster'` is used. + ``df_correction`` : bool, optional + The adjustment to df_resid, see cov_type 'cluster' above + + - 'hac-panel': heteroscedasticity and autocorrelation robust standard + errors in panel data. The data needs to be sorted in this case, the + time series for each panel unit or cluster need to be stacked. The + membership to a time series of an individual or group can be either + specified by group indicators or by increasing time periods. One of + ``groups`` or ``time`` is required. # TODO: we need more options here + + ``groups`` : array_like[int] + indicator for groups + ``time`` : array_like[int] + index of time periods + ``maxlags`` : int, required + number of lags to use + ``kernel`` : {callable, str}, optional + Available kernels are ['bartlett', 'uniform'], default + is Bartlett + ``use_correction`` : {False, 'hac', 'cluster'}, optional + If False the sandwich covariance is calculated without + small sample correction. + ``df_correction`` : bool, optional + Adjustment to df_resid, see cov_type 'cluster' above + + **Reminder**: ``use_correction`` in "hac-groupsum" and "hac-panel" is + not bool, needs to be in {False, 'hac', 'cluster'}. + + .. todo:: Currently there is no check for extra or misspelled keywords, + except in the case of cov_type `HCx` + """ + + import statsmodels.stats.sandwich_covariance as sw + + cov_type = normalize_cov_type(cov_type) + + if 'kernel' in kwds: + kwds['weights_func'] = kwds.pop('kernel') + if 'weights_func' in kwds and not callable(kwds['weights_func']): + kwds['weights_func'] = sw.kernel_dict[kwds['weights_func']] + + # pop because HCx raises if any kwds + sc_factor = kwds.pop('scaling_factor', None) + + # TODO: make separate function that returns a robust cov plus info + use_self = kwds.pop('use_self', False) + if use_self: + res = self + else: + # this does not work for most models, use raw instance instead from fit + res = self.__class__(self.model, self.params, + normalized_cov_params=self.normalized_cov_params, + scale=self.scale) + + res.cov_type = cov_type + # use_t might already be defined by the class, and already set + if use_t is None: + use_t = self.use_t + res.cov_kwds = {'use_t':use_t} # store for information + res.use_t = use_t + + adjust_df = False + if cov_type in ['cluster', 'hac-panel', 'hac-groupsum']: + df_correction = kwds.get('df_correction', None) + # TODO: check also use_correction, do I need all combinations? + if df_correction is not False: # i.e. in [None, True]: + # user did not explicitely set it to False + adjust_df = True + + res.cov_kwds['adjust_df'] = adjust_df + + # verify and set kwds, and calculate cov + # TODO: this should be outsourced in a function so we can reuse it in + # other models + # TODO: make it DRYer repeated code for checking kwds + if cov_type.upper() in ('HC0', 'HC1', 'HC2', 'HC3'): + if kwds: + raise ValueError('heteroscedasticity robust covariance ' + 'does not use keywords') + res.cov_kwds['description'] = descriptions[cov_type.upper()] + + res.cov_params_default = getattr(self, 'cov_' + cov_type.upper(), None) + if res.cov_params_default is None: + # results classes that do not have cov_HCx attribute + res.cov_params_default = sw.cov_white_simple(self, + use_correction=False) + elif cov_type.lower() == 'hac': + maxlags = kwds['maxlags'] # required?, default in cov_hac_simple + res.cov_kwds['maxlags'] = maxlags + weights_func = kwds.get('weights_func', sw.weights_bartlett) + res.cov_kwds['weights_func'] = weights_func + use_correction = kwds.get('use_correction', False) + res.cov_kwds['use_correction'] = use_correction + res.cov_kwds['description'] = descriptions['HAC'].format( + maxlags=maxlags, correction=['without', 'with'][use_correction]) + + res.cov_params_default = sw.cov_hac_simple(self, nlags=maxlags, + weights_func=weights_func, + use_correction=use_correction) + elif cov_type.lower() == 'cluster': + #cluster robust standard errors, one- or two-way + groups = kwds['groups'] + if not hasattr(groups, 'shape'): + groups = np.asarray(groups).T + + if groups.ndim >= 2: + groups = groups.squeeze() + + res.cov_kwds['groups'] = groups + use_correction = kwds.get('use_correction', True) + res.cov_kwds['use_correction'] = use_correction + if groups.ndim == 1: + if adjust_df: + # need to find number of groups + # duplicate work + self.n_groups = n_groups = len(np.unique(groups)) + res.cov_params_default = sw.cov_cluster(self, groups, + use_correction=use_correction) + + elif groups.ndim == 2: + if hasattr(groups, 'values'): + groups = groups.values + + if adjust_df: + # need to find number of groups + # duplicate work + n_groups0 = len(np.unique(groups[:,0])) + n_groups1 = len(np.unique(groups[:, 1])) + self.n_groups = (n_groups0, n_groups1) + n_groups = min(n_groups0, n_groups1) # use for adjust_df + + # Note: sw.cov_cluster_2groups has 3 returns + res.cov_params_default = sw.cov_cluster_2groups(self, groups, + use_correction=use_correction)[0] + else: + raise ValueError('only two groups are supported') + res.cov_kwds['description'] = descriptions['cluster'] + + elif cov_type.lower() == 'hac-panel': + #cluster robust standard errors + res.cov_kwds['time'] = time = kwds.get('time', None) + res.cov_kwds['groups'] = groups = kwds.get('groups', None) + #TODO: nlags is currently required + #nlags = kwds.get('nlags', True) + #res.cov_kwds['nlags'] = nlags + #TODO: `nlags` or `maxlags` + res.cov_kwds['maxlags'] = maxlags = kwds['maxlags'] + use_correction = kwds.get('use_correction', 'hac') + res.cov_kwds['use_correction'] = use_correction + weights_func = kwds.get('weights_func', sw.weights_bartlett) + res.cov_kwds['weights_func'] = weights_func + # TODO: clumsy time index in cov_nw_panel + if groups is not None: + groups = np.asarray(groups) + tt = (np.nonzero(groups[:-1] != groups[1:])[0] + 1).tolist() + nobs_ = len(groups) + elif time is not None: + # TODO: clumsy time index in cov_nw_panel + time = np.asarray(time) + tt = (np.nonzero(time[1:] < time[:-1])[0] + 1).tolist() + nobs_ = len(time) + else: + raise ValueError('either time or groups needs to be given') + groupidx = lzip([0] + tt, tt + [nobs_]) + self.n_groups = n_groups = len(groupidx) + res.cov_params_default = sw.cov_nw_panel(self, maxlags, groupidx, + weights_func=weights_func, + use_correction=use_correction) + res.cov_kwds['description'] = descriptions['HAC-Panel'] + + elif cov_type.lower() == 'hac-groupsum': + # Driscoll-Kraay standard errors + res.cov_kwds['time'] = time = kwds['time'] + #TODO: nlags is currently required + #nlags = kwds.get('nlags', True) + #res.cov_kwds['nlags'] = nlags + #TODO: `nlags` or `maxlags` + res.cov_kwds['maxlags'] = maxlags = kwds['maxlags'] + use_correction = kwds.get('use_correction', 'cluster') + res.cov_kwds['use_correction'] = use_correction + weights_func = kwds.get('weights_func', sw.weights_bartlett) + res.cov_kwds['weights_func'] = weights_func + if adjust_df: + # need to find number of groups + tt = (np.nonzero(time[1:] < time[:-1])[0] + 1) + self.n_groups = n_groups = len(tt) + 1 + res.cov_params_default = sw.cov_nw_groupsum(self, maxlags, time, + weights_func=weights_func, + use_correction=use_correction) + res.cov_kwds['description'] = descriptions['HAC-Groupsum'] + else: + raise ValueError('cov_type not recognized. See docstring for ' + + 'available options and spelling') + + # generic optional factor to scale covariance + + res.cov_kwds['scaling_factor'] = sc_factor + if sc_factor is not None: + res.cov_params_default *= sc_factor + + if adjust_df: + # Note: df_resid is used for scale and others, add new attribute + res.df_resid_inference = n_groups - 1 + + return res diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/data.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/data.py new file mode 100644 index 0000000000000000000000000000000000000000..1edeec5663b7d128e055ef2163898ca4c08d7e17 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/data.py @@ -0,0 +1,694 @@ +""" +Base tools for handling various kinds of data structures, attaching metadata to +results, and doing data cleaning +""" + +from __future__ import annotations + +from statsmodels.compat.python import lmap + +from functools import reduce + +import numpy as np +from pandas import DataFrame, MultiIndex, Series, isnull + +import statsmodels.tools.data as data_util +from statsmodels.tools.decorators import cache_readonly, cache_writable +from statsmodels.tools.sm_exceptions import MissingDataError + + +def _asarray_2dcolumns(x): + if np.asarray(x).ndim > 1 and np.asarray(x).squeeze().ndim == 1: + return + + +def _asarray_2d_null_rows(x): + """ + Makes sure input is an array and is 2d. Makes sure output is 2d. True + indicates a null in the rows of 2d x. + """ + # Have to have the asarrays because isnull does not account for array_like + # input + x = np.asarray(x) + if x.ndim == 1: + x = x[:, None] + return np.any(isnull(x), axis=1)[:, None] + + +def _nan_rows(*arrs): + """ + Returns a boolean array which is True where any of the rows in any + of the _2d_ arrays in arrs are NaNs. Inputs can be any mixture of Series, + DataFrames or array_like. + """ + if len(arrs) == 1: + arrs += ([[False]],) + + def _nan_row_maybe_two_inputs(x, y): + # check for dtype bc dataframe has dtypes + x_is_boolean_array = hasattr(x, "dtype") and x.dtype == bool and x + return np.logical_or( + _asarray_2d_null_rows(x), (x_is_boolean_array | _asarray_2d_null_rows(y)) + ) + + return reduce(_nan_row_maybe_two_inputs, arrs).squeeze() + + +class ModelData: + """ + Class responsible for handling input data and extracting metadata into the + appropriate form + """ + + _param_names = None + _cov_names = None + + def __init__(self, endog, exog=None, missing="none", hasconst=None, **kwargs): + if data_util._is_recarray(endog) or data_util._is_recarray(exog): + from statsmodels.tools.sm_exceptions import recarray_exception + + raise NotImplementedError(recarray_exception) + if "design_info" in kwargs: + self.design_info = kwargs.pop("design_info") + if "formula" in kwargs: + self.formula = kwargs.pop("formula") + if missing != "none": + arrays, nan_idx = self.handle_missing(endog, exog, missing, **kwargs) + self.missing_row_idx = nan_idx + self.__dict__.update(arrays) # attach all the data arrays + self.orig_endog = self.endog + self.orig_exog = self.exog + self.endog, self.exog = self._convert_endog_exog(self.endog, self.exog) + else: + self.__dict__.update(kwargs) # attach the extra arrays anyway + self.orig_endog = endog + self.orig_exog = exog + self.endog, self.exog = self._convert_endog_exog(endog, exog) + + self.const_idx = None + self.k_constant = 0 + self._handle_constant(hasconst) + self._check_integrity() + self._cache = {} + + def __getstate__(self): + from copy import copy + + d = copy(self.__dict__) + if "design_info" in d: + del d["design_info"] + d["restore_design_info"] = True + return d + + def __setstate__(self, d): + if "restore_design_info" in d: + # NOTE: there may be a more performant way to do this + from patsy import PatsyError, dmatrices + + exc = [] + try: + data = d["frame"] + except KeyError: + data = d["orig_endog"].join(d["orig_exog"]) + + for depth in [2, 3, 1, 0, 4]: # sequence is a guess where to likely find it + try: + _, design = dmatrices( + d["formula"], data, eval_env=depth, return_type="dataframe" + ) + break + except (NameError, PatsyError) as e: + exc.append(e) # why do I need a reference from outside except block + pass + else: + raise exc[-1] + + self.design_info = design.design_info + del d["restore_design_info"] + self.__dict__.update(d) + + def _handle_constant(self, hasconst): + if hasconst is False or self.exog is None: + self.k_constant = 0 + self.const_idx = None + else: + # detect where the constant is + check_implicit = False + exog_max = np.max(self.exog, axis=0) + if not np.isfinite(exog_max).all(): + raise MissingDataError("exog contains inf or nans") + exog_min = np.min(self.exog, axis=0) + const_idx = np.where(exog_max == exog_min)[0].squeeze() + self.k_constant = const_idx.size + + if self.k_constant == 1: + if self.exog[:, const_idx].mean() != 0: + self.const_idx = int(const_idx) + else: + # we only have a zero column and no other constant + check_implicit = True + elif self.k_constant > 1: + # we have more than one constant column + # look for ones + values = [] # keep values if we need != 0 + for idx in const_idx: + value = self.exog[:, idx].mean() + if value == 1: + self.k_constant = 1 + self.const_idx = int(idx) + break + values.append(value) + else: + # we did not break, no column of ones + pos = np.array(values) != 0 + if pos.any(): + # take the first nonzero column + self.k_constant = 1 + self.const_idx = int(const_idx[pos.argmax()]) + else: + # only zero columns + check_implicit = True + elif self.k_constant == 0: + check_implicit = True + else: + # should not be here + pass + + if check_implicit and not hasconst: + # look for implicit constant + # Compute rank of augmented matrix + augmented_exog = np.column_stack( + (np.ones(self.exog.shape[0]), self.exog) + ) + rank_augm = np.linalg.matrix_rank(augmented_exog) + rank_orig = np.linalg.matrix_rank(self.exog) + self.k_constant = int(rank_orig == rank_augm) + self.const_idx = None + elif hasconst: + # Ensure k_constant is 1 any time hasconst is True + # even if one is not found + self.k_constant = 1 + + @classmethod + def _drop_nans(cls, x, nan_mask): + return x[nan_mask] + + @classmethod + def _drop_nans_2d(cls, x, nan_mask): + return x[nan_mask][:, nan_mask] + + @classmethod + def handle_missing(cls, endog, exog, missing, **kwargs): + """ + This returns a dictionary with keys endog, exog and the keys of + kwargs. It preserves Nones. + """ + none_array_names = [] + + # patsy's already dropped NaNs in y/X + missing_idx = kwargs.pop("missing_idx", None) + + if missing_idx is not None: + # y, X already handled by patsy. add back in later. + combined = () + combined_names = [] + if exog is None: + none_array_names += ["exog"] + elif exog is not None: + combined = (endog, exog) + combined_names = ["endog", "exog"] + else: + combined = (endog,) + combined_names = ["endog"] + none_array_names += ["exog"] + + # deal with other arrays + combined_2d = () + combined_2d_names = [] + if len(kwargs): + for key, value_array in kwargs.items(): + if value_array is None or np.ndim(value_array) == 0: + none_array_names += [key] + continue + # grab 1d arrays + if value_array.ndim == 1: + combined += (np.asarray(value_array),) + combined_names += [key] + elif value_array.squeeze().ndim == 1: + combined += (np.asarray(value_array),) + combined_names += [key] + + # grab 2d arrays that are _assumed_ to be symmetric + elif value_array.ndim == 2: + combined_2d += (np.asarray(value_array),) + combined_2d_names += [key] + else: + raise ValueError( + "Arrays with more than 2 dimensions " "are not yet handled" + ) + + if missing_idx is not None: + nan_mask = missing_idx + updated_row_mask = None + if combined: # there were extra arrays not handled by patsy + combined_nans = _nan_rows(*combined) + if combined_nans.shape[0] != nan_mask.shape[0]: + raise ValueError( + "Shape mismatch between endog/exog " + "and extra arrays given to model." + ) + # for going back and updated endog/exog + updated_row_mask = combined_nans[~nan_mask] + nan_mask |= combined_nans # for updating extra arrays only + if combined_2d: + combined_2d_nans = _nan_rows(combined_2d) + if combined_2d_nans.shape[0] != nan_mask.shape[0]: + raise ValueError( + "Shape mismatch between endog/exog " + "and extra 2d arrays given to model." + ) + if updated_row_mask is not None: + updated_row_mask |= combined_2d_nans[~nan_mask] + else: + updated_row_mask = combined_2d_nans[~nan_mask] + nan_mask |= combined_2d_nans + + else: + nan_mask = _nan_rows(*combined) + if combined_2d: + nan_mask = _nan_rows(*(nan_mask[:, None],) + combined_2d) + + if not np.any(nan_mask): # no missing do not do anything + combined = dict(zip(combined_names, combined)) + if combined_2d: + combined.update(dict(zip(combined_2d_names, combined_2d))) + if none_array_names: + combined.update({k: kwargs.get(k, None) for k in none_array_names}) + + if missing_idx is not None: + combined.update({"endog": endog}) + if exog is not None: + combined.update({"exog": exog}) + + return combined, [] + + elif missing == "raise": + raise MissingDataError("NaNs were encountered in the data") + + elif missing == "drop": + nan_mask = ~nan_mask + + def drop_nans(x): + return cls._drop_nans(x, nan_mask) + + def drop_nans_2d(x): + return cls._drop_nans_2d(x, nan_mask) + + combined = dict(zip(combined_names, lmap(drop_nans, combined))) + + if missing_idx is not None: + if updated_row_mask is not None: + updated_row_mask = ~updated_row_mask + # update endog/exog with this new information + endog = cls._drop_nans(endog, updated_row_mask) + if exog is not None: + exog = cls._drop_nans(exog, updated_row_mask) + + combined.update({"endog": endog}) + if exog is not None: + combined.update({"exog": exog}) + + if combined_2d: + combined.update( + dict(zip(combined_2d_names, lmap(drop_nans_2d, combined_2d))) + ) + if none_array_names: + combined.update({k: kwargs.get(k, None) for k in none_array_names}) + + return combined, np.where(~nan_mask)[0].tolist() + else: + raise ValueError("missing option %s not understood" % missing) + + def _convert_endog_exog(self, endog, exog): + + # for consistent outputs if endog is (n,1) + yarr = self._get_yarr(endog) + xarr = None + if exog is not None: + xarr = self._get_xarr(exog) + if xarr.ndim == 1: + xarr = xarr[:, None] + if xarr.ndim != 2: + raise ValueError("exog is not 1d or 2d") + + return yarr, xarr + + @cache_writable() + def ynames(self): + endog = self.orig_endog + ynames = self._get_names(endog) + if not ynames: + ynames = _make_endog_names(self.endog) + + if len(ynames) == 1: + return ynames[0] + else: + return list(ynames) + + @cache_writable() + def xnames(self) -> list[str] | None: + exog = self.orig_exog + if exog is not None: + xnames = self._get_names(exog) + if not xnames: + xnames = _make_exog_names(self.exog) + return list(xnames) + return None + + @property + def param_names(self): + # for handling names of 'extra' parameters in summary, etc. + return self._param_names or self.xnames + + @param_names.setter + def param_names(self, values): + self._param_names = values + + @property + def cov_names(self): + """ + Labels for covariance matrices + + In multidimensional models, each dimension of a covariance matrix + differs from the number of param_names. + + If not set, returns param_names + """ + # for handling names of covariance names in multidimensional models + if self._cov_names is not None: + return self._cov_names + return self.param_names + + @cov_names.setter + def cov_names(self, value): + # for handling names of covariance names in multidimensional models + self._cov_names = value + + @cache_readonly + def row_labels(self): + exog = self.orig_exog + if exog is not None: + row_labels = self._get_row_labels(exog) + else: + endog = self.orig_endog + row_labels = self._get_row_labels(endog) + return row_labels + + def _get_row_labels(self, arr): + return None + + def _get_names(self, arr): + if isinstance(arr, DataFrame): + if isinstance(arr.columns, MultiIndex): + # Flatten MultiIndexes into "simple" column names + return ["_".join(level for level in c if level) for c in arr.columns] + else: + return list(arr.columns) + elif isinstance(arr, Series): + if arr.name: + return [arr.name] + else: + return + else: + try: + return arr.dtype.names + except AttributeError: + pass + + return None + + def _get_yarr(self, endog): + if data_util._is_structured_ndarray(endog): + endog = data_util.struct_to_ndarray(endog) + endog = np.asarray(endog) + if len(endog) == 1: # never squeeze to a scalar + if endog.ndim == 1: + return endog + elif endog.ndim > 1: + return np.asarray([endog.squeeze()]) + + return endog.squeeze() + + def _get_xarr(self, exog): + if data_util._is_structured_ndarray(exog): + exog = data_util.struct_to_ndarray(exog) + return np.asarray(exog) + + def _check_integrity(self): + if self.exog is not None: + if len(self.exog) != len(self.endog): + raise ValueError("endog and exog matrices are different sizes") + + def wrap_output(self, obj, how="columns", names=None): + if how == "columns": + return self.attach_columns(obj) + elif how == "rows": + return self.attach_rows(obj) + elif how == "cov": + return self.attach_cov(obj) + elif how == "dates": + return self.attach_dates(obj) + elif how == "columns_eq": + return self.attach_columns_eq(obj) + elif how == "cov_eq": + return self.attach_cov_eq(obj) + elif how == "generic_columns": + return self.attach_generic_columns(obj, names) + elif how == "generic_columns_2d": + return self.attach_generic_columns_2d(obj, names) + elif how == "ynames": + return self.attach_ynames(obj) + elif how == "multivariate_confint": + return self.attach_mv_confint(obj) + else: + return obj + + def attach_columns(self, result): + return result + + def attach_columns_eq(self, result): + return result + + def attach_cov(self, result): + return result + + def attach_cov_eq(self, result): + return result + + def attach_rows(self, result): + return result + + def attach_dates(self, result): + return result + + def attach_mv_confint(self, result): + return result + + def attach_generic_columns(self, result, *args, **kwargs): + return result + + def attach_generic_columns_2d(self, result, *args, **kwargs): + return result + + def attach_ynames(self, result): + return result + + +class PatsyData(ModelData): + def _get_names(self, arr): + return arr.design_info.column_names + + +class PandasData(ModelData): + """ + Data handling class which knows how to reattach pandas metadata to model + results + """ + + def _convert_endog_exog(self, endog, exog=None): + # TODO: remove this when we handle dtype systematically + endog = np.asarray(endog) + exog = exog if exog is None else np.asarray(exog) + if endog.dtype == object or exog is not None and exog.dtype == object: + raise ValueError( + "Pandas data cast to numpy dtype of object. " + "Check input data with np.asarray(data)." + ) + return super()._convert_endog_exog(endog, exog) + + @classmethod + def _drop_nans(cls, x, nan_mask): + if isinstance(x, (Series, DataFrame)): + return x.loc[nan_mask] + else: # extra arguments could be plain ndarrays + return super()._drop_nans(x, nan_mask) + + @classmethod + def _drop_nans_2d(cls, x, nan_mask): + if isinstance(x, (Series, DataFrame)): + return x.loc[nan_mask].loc[:, nan_mask] + else: # extra arguments could be plain ndarrays + return super()._drop_nans_2d(x, nan_mask) + + def _check_integrity(self): + endog, exog = self.orig_endog, self.orig_exog + # exog can be None and we could be upcasting one or the other + if ( + exog is not None + and (hasattr(endog, "index") and hasattr(exog, "index")) + and not self.orig_endog.index.equals(self.orig_exog.index) + ): + raise ValueError("The indices for endog and exog are not aligned") + super()._check_integrity() + + def _get_row_labels(self, arr): + try: + return arr.index + except AttributeError: + # if we've gotten here it's because endog is pandas and + # exog is not, so just return the row labels from endog + return self.orig_endog.index + + def attach_generic_columns(self, result, names): + # get the attribute to use + column_names = getattr(self, names, None) + return Series(result, index=column_names) + + def attach_generic_columns_2d(self, result, rownames, colnames=None): + colnames = colnames or rownames + rownames = getattr(self, rownames, None) + colnames = getattr(self, colnames, None) + return DataFrame(result, index=rownames, columns=colnames) + + def attach_columns(self, result): + # this can either be a 1d array or a scalar + # do not squeeze because it might be a 2d row array + # if it needs a squeeze, the bug is elsewhere + if result.ndim <= 1: + return Series(result, index=self.param_names) + else: # for e.g., confidence intervals + return DataFrame(result, index=self.param_names) + + def attach_columns_eq(self, result): + return DataFrame(result, index=self.xnames, columns=self.ynames) + + def attach_cov(self, result): + return DataFrame(result, index=self.cov_names, columns=self.cov_names) + + def attach_cov_eq(self, result): + return DataFrame(result, index=self.ynames, columns=self.ynames) + + def attach_rows(self, result): + # assumes if len(row_labels) > len(result) it's bc it was truncated + # at the front, for AR lags, for example + squeezed = result.squeeze() + k_endog = np.array(self.ynames, ndmin=1).shape[0] + if k_endog > 1 and squeezed.shape == (k_endog,): + squeezed = squeezed[None, :] + # May be zero-dim, for example in the case of forecast one step in tsa + if squeezed.ndim < 2: + out = Series(squeezed) + else: + out = DataFrame(result) + out.columns = self.ynames + out.index = self.row_labels[-len(result) :] + return out + + def attach_dates(self, result): + squeezed = result.squeeze() + k_endog = np.array(self.ynames, ndmin=1).shape[0] + if k_endog > 1 and squeezed.shape == (k_endog,): + squeezed = np.asarray(squeezed)[None, :] + # May be zero-dim, for example in the case of forecast one step in tsa + if squeezed.ndim < 2: + return Series(squeezed, index=self.predict_dates) + else: + return DataFrame( + np.asarray(result), index=self.predict_dates, columns=self.ynames + ) + + def attach_mv_confint(self, result): + return DataFrame( + result.reshape((-1, 2)), index=self.cov_names, columns=["lower", "upper"] + ) + + def attach_ynames(self, result): + squeezed = result.squeeze() + # May be zero-dim, for example in the case of forecast one step in tsa + if squeezed.ndim < 2: + return Series(squeezed, name=self.ynames) + else: + return DataFrame(result, columns=self.ynames) + + +def _make_endog_names(endog): + if endog.ndim == 1 or endog.shape[1] == 1: + ynames = ["y"] + else: # for VAR + ynames = ["y%d" % (i + 1) for i in range(endog.shape[1])] + + return ynames + + +def _make_exog_names(exog): + exog_var = exog.var(0) + if (exog_var == 0).any(): + # assumes one constant in first or last position + # avoid exception if more than one constant + const_idx = exog_var.argmin() + exog_names = ["x%d" % i for i in range(1, exog.shape[1])] + exog_names.insert(const_idx, "const") + else: + exog_names = ["x%d" % i for i in range(1, exog.shape[1] + 1)] + + return exog_names + + +def handle_missing(endog, exog=None, missing="none", **kwargs): + klass = handle_data_class_factory(endog, exog) + if missing == "none": + ret_dict = dict(endog=endog, exog=exog) + ret_dict.update(kwargs) + return ret_dict, None + return klass.handle_missing(endog, exog, missing=missing, **kwargs) + + +def handle_data_class_factory(endog, exog): + """ + Given inputs + """ + if data_util._is_using_ndarray_type(endog, exog): + klass = ModelData + elif data_util._is_using_pandas(endog, exog): + klass = PandasData + elif data_util._is_using_patsy(endog, exog): + klass = PatsyData + # keep this check last + elif data_util._is_using_ndarray(endog, exog): + klass = ModelData + else: + raise ValueError( + "unrecognized data structures: %s / %s" % (type(endog), type(exog)) + ) + return klass + + +def handle_data(endog, exog, missing="none", hasconst=None, **kwargs): + # deal with lists and tuples up-front + if isinstance(endog, (list, tuple)): + endog = np.asarray(endog) + if isinstance(exog, (list, tuple)): + exog = np.asarray(exog) + + klass = handle_data_class_factory(endog, exog) + return klass(endog, exog=exog, missing=missing, hasconst=hasconst, **kwargs) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/distributed_estimation.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/distributed_estimation.py new file mode 100644 index 0000000000000000000000000000000000000000..4e9f93c9eac3466641921204a5aafed87dc97cf7 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/distributed_estimation.py @@ -0,0 +1,677 @@ +from statsmodels.base.elastic_net import RegularizedResults +from statsmodels.stats.regularized_covariance import _calc_nodewise_row, \ + _calc_nodewise_weight, _calc_approx_inv_cov +from statsmodels.base.model import LikelihoodModelResults +from statsmodels.regression.linear_model import OLS +import numpy as np + +""" +Distributed estimation routines. Currently, we support several +methods of distribution + +- sequential, has no extra dependencies +- parallel + - with joblib + A variety of backends are supported through joblib + This allows for different types of clusters besides + standard local clusters. Some examples of + backends supported by joblib are + - dask.distributed + - yarn + - ipyparallel + +The framework is very general and allows for a variety of +estimation methods. Currently, these include + +- debiased regularized estimation +- simple coefficient averaging (naive) + - regularized + - unregularized + +Currently, the default is regularized estimation with debiasing +which follows the methods outlined in + +Jason D. Lee, Qiang Liu, Yuekai Sun and Jonathan E. Taylor. +"Communication-Efficient Sparse Regression: A One-Shot Approach." +arXiv:1503.04337. 2015. https://arxiv.org/abs/1503.04337. + +There are several variables that are taken from the source paper +for which the interpretation may not be directly clear from the +code, these are mostly used to help form the estimate of the +approximate inverse covariance matrix as part of the +debiasing procedure. + + wexog + + A weighted design matrix used to perform the node-wise + regression procedure. + + nodewise_row + + nodewise_row is produced as part of the node-wise regression + procedure used to produce the approximate inverse covariance + matrix. One is produced for each variable using the + LASSO. + + nodewise_weight + + nodewise_weight is produced using the gamma_hat values for + each p to produce weights to reweight the gamma_hat values which + are ultimately used to form approx_inv_cov. + + approx_inv_cov + + This is the estimate of the approximate inverse covariance + matrix. This is used to debiase the coefficient average + along with the average gradient. For the OLS case, + approx_inv_cov is an approximation for + + n * (X^T X)^{-1} + + formed by node-wise regression. +""" + + +def _est_regularized_naive(mod, pnum, partitions, fit_kwds=None): + """estimates the regularized fitted parameters. + + Parameters + ---------- + mod : statsmodels model class instance + The model for the current partition. + pnum : scalar + Index of current partition + partitions : scalar + Total number of partitions + fit_kwds : dict-like or None + Keyword arguments to be given to fit_regularized + + Returns + ------- + An array of the parameters for the regularized fit + """ + + if fit_kwds is None: + raise ValueError("_est_regularized_naive currently " + + "requires that fit_kwds not be None.") + + return mod.fit_regularized(**fit_kwds).params + + +def _est_unregularized_naive(mod, pnum, partitions, fit_kwds=None): + """estimates the unregularized fitted parameters. + + Parameters + ---------- + mod : statsmodels model class instance + The model for the current partition. + pnum : scalar + Index of current partition + partitions : scalar + Total number of partitions + fit_kwds : dict-like or None + Keyword arguments to be given to fit + + Returns + ------- + An array of the parameters for the fit + """ + + if fit_kwds is None: + raise ValueError("_est_unregularized_naive currently " + + "requires that fit_kwds not be None.") + + return mod.fit(**fit_kwds).params + + +def _join_naive(params_l, threshold=0): + """joins the results from each run of _est__naive + and returns the mean estimate of the coefficients + + Parameters + ---------- + params_l : list + A list of arrays of coefficients. + threshold : scalar + The threshold at which the coefficients will be cut. + """ + + p = len(params_l[0]) + partitions = len(params_l) + + params_mn = np.zeros(p) + for params in params_l: + params_mn += params + params_mn /= partitions + + params_mn[np.abs(params_mn) < threshold] = 0 + + return params_mn + + +def _calc_grad(mod, params, alpha, L1_wt, score_kwds): + """calculates the log-likelihood gradient for the debiasing + + Parameters + ---------- + mod : statsmodels model class instance + The model for the current partition. + params : array_like + The estimated coefficients for the current partition. + alpha : scalar or array_like + The penalty weight. If a scalar, the same penalty weight + applies to all variables in the model. If a vector, it + must have the same length as `params`, and contains a + penalty weight for each coefficient. + L1_wt : scalar + The fraction of the penalty given to the L1 penalty term. + Must be between 0 and 1 (inclusive). If 0, the fit is + a ridge fit, if 1 it is a lasso fit. + score_kwds : dict-like or None + Keyword arguments for the score function. + + Returns + ------- + An array-like object of the same dimension as params + + Notes + ----- + In general: + + gradient l_k(params) + + where k corresponds to the index of the partition + + For OLS: + + X^T(y - X^T params) + """ + + grad = -mod.score(np.asarray(params), **score_kwds) + grad += alpha * (1 - L1_wt) + return grad + + +def _calc_wdesign_mat(mod, params, hess_kwds): + """calculates the weighted design matrix necessary to generate + the approximate inverse covariance matrix + + Parameters + ---------- + mod : statsmodels model class instance + The model for the current partition. + params : array_like + The estimated coefficients for the current partition. + hess_kwds : dict-like or None + Keyword arguments for the hessian function. + + Returns + ------- + An array-like object, updated design matrix, same dimension + as mod.exog + """ + + rhess = np.sqrt(mod.hessian_factor(np.asarray(params), **hess_kwds)) + return rhess[:, None] * mod.exog + + +def _est_regularized_debiased(mod, mnum, partitions, fit_kwds=None, + score_kwds=None, hess_kwds=None): + """estimates the regularized fitted parameters, is the default + estimation_method for class DistributedModel. + + Parameters + ---------- + mod : statsmodels model class instance + The model for the current partition. + mnum : scalar + Index of current partition. + partitions : scalar + Total number of partitions. + fit_kwds : dict-like or None + Keyword arguments to be given to fit_regularized + score_kwds : dict-like or None + Keyword arguments for the score function. + hess_kwds : dict-like or None + Keyword arguments for the Hessian function. + + Returns + ------- + A tuple of parameters for regularized fit + An array-like object of the fitted parameters, params + An array-like object for the gradient + A list of array like objects for nodewise_row + A list of array like objects for nodewise_weight + """ + + score_kwds = {} if score_kwds is None else score_kwds + hess_kwds = {} if hess_kwds is None else hess_kwds + + if fit_kwds is None: + raise ValueError("_est_regularized_debiased currently " + + "requires that fit_kwds not be None.") + else: + alpha = fit_kwds["alpha"] + + if "L1_wt" in fit_kwds: + L1_wt = fit_kwds["L1_wt"] + else: + L1_wt = 1 + + nobs, p = mod.exog.shape + p_part = int(np.ceil((1. * p) / partitions)) + + params = mod.fit_regularized(**fit_kwds).params + grad = _calc_grad(mod, params, alpha, L1_wt, score_kwds) / nobs + + wexog = _calc_wdesign_mat(mod, params, hess_kwds) + + nodewise_row_l = [] + nodewise_weight_l = [] + for idx in range(mnum * p_part, min((mnum + 1) * p_part, p)): + + nodewise_row = _calc_nodewise_row(wexog, idx, alpha) + nodewise_row_l.append(nodewise_row) + + nodewise_weight = _calc_nodewise_weight(wexog, nodewise_row, idx, + alpha) + nodewise_weight_l.append(nodewise_weight) + + return params, grad, nodewise_row_l, nodewise_weight_l + + +def _join_debiased(results_l, threshold=0): + """joins the results from each run of _est_regularized_debiased + and returns the debiased estimate of the coefficients + + Parameters + ---------- + results_l : list + A list of tuples each one containing the params, grad, + nodewise_row and nodewise_weight values for each partition. + threshold : scalar + The threshold at which the coefficients will be cut. + """ + + p = len(results_l[0][0]) + partitions = len(results_l) + + params_mn = np.zeros(p) + grad_mn = np.zeros(p) + + nodewise_row_l = [] + nodewise_weight_l = [] + + for r in results_l: + + params_mn += r[0] + grad_mn += r[1] + + nodewise_row_l.extend(r[2]) + nodewise_weight_l.extend(r[3]) + + nodewise_row_l = np.array(nodewise_row_l) + nodewise_weight_l = np.array(nodewise_weight_l) + + params_mn /= partitions + grad_mn *= -1. / partitions + + approx_inv_cov = _calc_approx_inv_cov(nodewise_row_l, nodewise_weight_l) + + debiased_params = params_mn + approx_inv_cov.dot(grad_mn) + + debiased_params[np.abs(debiased_params) < threshold] = 0 + + return debiased_params + + +def _helper_fit_partition(self, pnum, endog, exog, fit_kwds, + init_kwds_e={}): + """handles the model fitting for each machine. NOTE: this + is primarily handled outside of DistributedModel because + joblib cannot handle class methods. + + Parameters + ---------- + self : DistributedModel class instance + An instance of DistributedModel. + pnum : scalar + index of current partition. + endog : array_like + endogenous data for current partition. + exog : array_like + exogenous data for current partition. + fit_kwds : dict-like + Keywords needed for the model fitting. + init_kwds_e : dict-like + Additional init_kwds to add for each partition. + + Returns + ------- + estimation_method result. For the default, + _est_regularized_debiased, a tuple. + """ + + temp_init_kwds = self.init_kwds.copy() + temp_init_kwds.update(init_kwds_e) + + model = self.model_class(endog, exog, **temp_init_kwds) + results = self.estimation_method(model, pnum, self.partitions, + fit_kwds=fit_kwds, + **self.estimation_kwds) + return results + + +class DistributedModel: + __doc__ = """ + Distributed model class + + Parameters + ---------- + partitions : scalar + The number of partitions that the data will be split into. + model_class : statsmodels model class + The model class which will be used for estimation. If None + this defaults to OLS. + init_kwds : dict-like or None + Keywords needed for initializing the model, in addition to + endog and exog. + init_kwds_generator : generator or None + Additional keyword generator that produces model init_kwds + that may vary based on data partition. The current usecase + is for WLS and GLS + estimation_method : function or None + The method that performs the estimation for each partition. + If None this defaults to _est_regularized_debiased. + estimation_kwds : dict-like or None + Keywords to be passed to estimation_method. + join_method : function or None + The method used to recombine the results from each partition. + If None this defaults to _join_debiased. + join_kwds : dict-like or None + Keywords to be passed to join_method. + results_class : results class or None + The class of results that should be returned. If None this + defaults to RegularizedResults. + results_kwds : dict-like or None + Keywords to be passed to results class. + + Attributes + ---------- + partitions : scalar + See Parameters. + model_class : statsmodels model class + See Parameters. + init_kwds : dict-like + See Parameters. + init_kwds_generator : generator or None + See Parameters. + estimation_method : function + See Parameters. + estimation_kwds : dict-like + See Parameters. + join_method : function + See Parameters. + join_kwds : dict-like + See Parameters. + results_class : results class + See Parameters. + results_kwds : dict-like + See Parameters. + + Notes + ----- + + Examples + -------- + """ + + def __init__(self, partitions, model_class=None, + init_kwds=None, estimation_method=None, + estimation_kwds=None, join_method=None, join_kwds=None, + results_class=None, results_kwds=None): + + self.partitions = partitions + + if model_class is None: + self.model_class = OLS + else: + self.model_class = model_class + + if init_kwds is None: + self.init_kwds = {} + else: + self.init_kwds = init_kwds + + if estimation_method is None: + self.estimation_method = _est_regularized_debiased + else: + self.estimation_method = estimation_method + + if estimation_kwds is None: + self.estimation_kwds = {} + else: + self.estimation_kwds = estimation_kwds + + if join_method is None: + self.join_method = _join_debiased + else: + self.join_method = join_method + + if join_kwds is None: + self.join_kwds = {} + else: + self.join_kwds = join_kwds + + if results_class is None: + self.results_class = RegularizedResults + else: + self.results_class = results_class + + if results_kwds is None: + self.results_kwds = {} + else: + self.results_kwds = results_kwds + + def fit(self, data_generator, fit_kwds=None, parallel_method="sequential", + parallel_backend=None, init_kwds_generator=None): + """Performs the distributed estimation using the corresponding + DistributedModel + + Parameters + ---------- + data_generator : generator + A generator that produces a sequence of tuples where the first + element in the tuple corresponds to an endog array and the + element corresponds to an exog array. + fit_kwds : dict-like or None + Keywords needed for the model fitting. + parallel_method : str + type of distributed estimation to be used, currently + "sequential", "joblib" and "dask" are supported. + parallel_backend : None or joblib parallel_backend object + used to allow support for more complicated backends, + ex: dask.distributed + init_kwds_generator : generator or None + Additional keyword generator that produces model init_kwds + that may vary based on data partition. The current usecase + is for WLS and GLS + + Returns + ------- + join_method result. For the default, _join_debiased, it returns a + p length array. + """ + + if fit_kwds is None: + fit_kwds = {} + + if parallel_method == "sequential": + results_l = self.fit_sequential(data_generator, fit_kwds, + init_kwds_generator) + + elif parallel_method == "joblib": + results_l = self.fit_joblib(data_generator, fit_kwds, + parallel_backend, + init_kwds_generator) + + else: + raise ValueError("parallel_method: %s is currently not supported" + % parallel_method) + + params = self.join_method(results_l, **self.join_kwds) + + # NOTE that currently, the dummy result model that is initialized + # here does not use any init_kwds from the init_kwds_generator event + # if it is provided. It is possible to imagine an edge case where + # this might be a problem but given that the results model instance + # does not correspond to any data partition this seems reasonable. + res_mod = self.model_class([0], [0], **self.init_kwds) + + return self.results_class(res_mod, params, **self.results_kwds) + + def fit_sequential(self, data_generator, fit_kwds, + init_kwds_generator=None): + """Sequentially performs the distributed estimation using + the corresponding DistributedModel + + Parameters + ---------- + data_generator : generator + A generator that produces a sequence of tuples where the first + element in the tuple corresponds to an endog array and the + element corresponds to an exog array. + fit_kwds : dict-like + Keywords needed for the model fitting. + init_kwds_generator : generator or None + Additional keyword generator that produces model init_kwds + that may vary based on data partition. The current usecase + is for WLS and GLS + + Returns + ------- + join_method result. For the default, _join_debiased, it returns a + p length array. + """ + + results_l = [] + + if init_kwds_generator is None: + + for pnum, (endog, exog) in enumerate(data_generator): + + results = _helper_fit_partition(self, pnum, endog, exog, + fit_kwds) + results_l.append(results) + + else: + + tup_gen = enumerate(zip(data_generator, + init_kwds_generator)) + + for pnum, ((endog, exog), init_kwds_e) in tup_gen: + + results = _helper_fit_partition(self, pnum, endog, exog, + fit_kwds, init_kwds_e) + results_l.append(results) + + return results_l + + def fit_joblib(self, data_generator, fit_kwds, parallel_backend, + init_kwds_generator=None): + """Performs the distributed estimation in parallel using joblib + + Parameters + ---------- + data_generator : generator + A generator that produces a sequence of tuples where the first + element in the tuple corresponds to an endog array and the + element corresponds to an exog array. + fit_kwds : dict-like + Keywords needed for the model fitting. + parallel_backend : None or joblib parallel_backend object + used to allow support for more complicated backends, + ex: dask.distributed + init_kwds_generator : generator or None + Additional keyword generator that produces model init_kwds + that may vary based on data partition. The current usecase + is for WLS and GLS + + Returns + ------- + join_method result. For the default, _join_debiased, it returns a + p length array. + """ + + from statsmodels.tools.parallel import parallel_func + + par, f, n_jobs = parallel_func(_helper_fit_partition, self.partitions) + + if parallel_backend is None and init_kwds_generator is None: + results_l = par(f(self, pnum, endog, exog, fit_kwds) + for pnum, (endog, exog) + in enumerate(data_generator)) + + elif parallel_backend is not None and init_kwds_generator is None: + with parallel_backend: + results_l = par(f(self, pnum, endog, exog, fit_kwds) + for pnum, (endog, exog) + in enumerate(data_generator)) + + elif parallel_backend is None and init_kwds_generator is not None: + tup_gen = enumerate(zip(data_generator, init_kwds_generator)) + results_l = par(f(self, pnum, endog, exog, fit_kwds, init_kwds) + for pnum, ((endog, exog), init_kwds) + in tup_gen) + + elif parallel_backend is not None and init_kwds_generator is not None: + tup_gen = enumerate(zip(data_generator, init_kwds_generator)) + with parallel_backend: + results_l = par(f(self, pnum, endog, exog, fit_kwds, init_kwds) + for pnum, ((endog, exog), init_kwds) + in tup_gen) + + return results_l + + +class DistributedResults(LikelihoodModelResults): + """ + Class to contain model results + + Parameters + ---------- + model : class instance + Class instance for model used for distributed data, + this particular instance uses fake data and is really + only to allow use of methods like predict. + params : ndarray + Parameter estimates from the fit model. + """ + + def __init__(self, model, params): + super().__init__(model, params) + + def predict(self, exog, *args, **kwargs): + """Calls self.model.predict for the provided exog. See + Results.predict. + + Parameters + ---------- + exog : array_like NOT optional + The values for which we want to predict, unlike standard + predict this is NOT optional since the data in self.model + is fake. + *args : + Some models can take additional arguments. See the + predict method of the model for the details. + **kwargs : + Some models can take additional keywords arguments. See the + predict method of the model for the details. + + Returns + ------- + prediction : ndarray, pandas.Series or pandas.DataFrame + See self.model.predict + """ + + return self.model.predict(self.params, exog, *args, **kwargs) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/elastic_net.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/elastic_net.py new file mode 100644 index 0000000000000000000000000000000000000000..8327d8b5292549b26cae3ddf6b3edde7ff7e9f27 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/elastic_net.py @@ -0,0 +1,388 @@ +import numpy as np +from statsmodels.base.model import Results +import statsmodels.base.wrapper as wrap +from statsmodels.tools.decorators import cache_readonly + +""" +Elastic net regularization. + +Routines for fitting regression models using elastic net +regularization. The elastic net minimizes the objective function + +-llf / nobs + alpha((1 - L1_wt) * sum(params**2) / 2 + + L1_wt * sum(abs(params))) + +The algorithm implemented here closely follows the implementation in +the R glmnet package, documented here: + +http://cran.r-project.org/web/packages/glmnet/index.html + +and here: + +http://www.jstatsoft.org/v33/i01/paper + +This routine should work for any regression model that implements +loglike, score, and hess. +""" + + +def _gen_npfuncs(k, L1_wt, alpha, loglike_kwds, score_kwds, hess_kwds): + """ + Negative penalized log-likelihood functions. + + Returns the negative penalized log-likelihood, its derivative, and + its Hessian. The penalty only includes the smooth (L2) term. + + All three functions have argument signature (x, model), where + ``x`` is a point in the parameter space and ``model`` is an + arbitrary statsmodels regression model. + """ + + def nploglike(params, model): + nobs = model.nobs + pen_llf = alpha[k] * (1 - L1_wt) * np.sum(params**2) / 2 + llf = model.loglike(np.r_[params], **loglike_kwds) + return - llf / nobs + pen_llf + + def npscore(params, model): + nobs = model.nobs + pen_grad = alpha[k] * (1 - L1_wt) * params + gr = -model.score(np.r_[params], **score_kwds)[0] / nobs + return gr + pen_grad + + def nphess(params, model): + nobs = model.nobs + pen_hess = alpha[k] * (1 - L1_wt) + h = -model.hessian(np.r_[params], **hess_kwds)[0, 0] / nobs + pen_hess + return h + + return nploglike, npscore, nphess + + +def fit_elasticnet(model, method="coord_descent", maxiter=100, + alpha=0., L1_wt=1., start_params=None, cnvrg_tol=1e-7, + zero_tol=1e-8, refit=False, check_step=True, + loglike_kwds=None, score_kwds=None, hess_kwds=None): + """ + Return an elastic net regularized fit to a regression model. + + Parameters + ---------- + model : model object + A statsmodels object implementing ``loglike``, ``score``, and + ``hessian``. + method : {'coord_descent'} + Only the coordinate descent algorithm is implemented. + maxiter : int + The maximum number of iteration cycles (an iteration cycle + involves running coordinate descent on all variables). + alpha : scalar or array_like + The penalty weight. If a scalar, the same penalty weight + applies to all variables in the model. If a vector, it + must have the same length as `params`, and contains a + penalty weight for each coefficient. + L1_wt : scalar + The fraction of the penalty given to the L1 penalty term. + Must be between 0 and 1 (inclusive). If 0, the fit is + a ridge fit, if 1 it is a lasso fit. + start_params : array_like + Starting values for `params`. + cnvrg_tol : scalar + If `params` changes by less than this amount (in sup-norm) + in one iteration cycle, the algorithm terminates with + convergence. + zero_tol : scalar + Any estimated coefficient smaller than this value is + replaced with zero. + refit : bool + If True, the model is refit using only the variables that have + non-zero coefficients in the regularized fit. The refitted + model is not regularized. + check_step : bool + If True, confirm that the first step is an improvement and search + further if it is not. + loglike_kwds : dict-like or None + Keyword arguments for the log-likelihood function. + score_kwds : dict-like or None + Keyword arguments for the score function. + hess_kwds : dict-like or None + Keyword arguments for the Hessian function. + + Returns + ------- + Results + A results object. + + Notes + ----- + The ``elastic net`` penalty is a combination of L1 and L2 + penalties. + + The function that is minimized is: + + -loglike/n + alpha*((1-L1_wt)*|params|_2^2/2 + L1_wt*|params|_1) + + where |*|_1 and |*|_2 are the L1 and L2 norms. + + The computational approach used here is to obtain a quadratic + approximation to the smooth part of the target function: + + -loglike/n + alpha*(1-L1_wt)*|params|_2^2/2 + + then repeatedly optimize the L1 penalized version of this function + along coordinate axes. + """ + + k_exog = model.exog.shape[1] + + loglike_kwds = {} if loglike_kwds is None else loglike_kwds + score_kwds = {} if score_kwds is None else score_kwds + hess_kwds = {} if hess_kwds is None else hess_kwds + + if np.isscalar(alpha): + alpha = alpha * np.ones(k_exog) + + # Define starting params + if start_params is None: + params = np.zeros(k_exog) + else: + params = start_params.copy() + + btol = 1e-4 + params_zero = np.zeros(len(params), dtype=bool) + + init_args = model._get_init_kwds() + # we do not need a copy of init_args b/c get_init_kwds provides new dict + init_args['hasconst'] = False + model_offset = init_args.pop('offset', None) + if 'exposure' in init_args and init_args['exposure'] is not None: + if model_offset is None: + model_offset = np.log(init_args.pop('exposure')) + else: + model_offset += np.log(init_args.pop('exposure')) + + fgh_list = [ + _gen_npfuncs(k, L1_wt, alpha, loglike_kwds, score_kwds, hess_kwds) + for k in range(k_exog)] + + converged = False + + for itr in range(maxiter): + + # Sweep through the parameters + params_save = params.copy() + for k in range(k_exog): + + # Under the active set method, if a parameter becomes + # zero we do not try to change it again. + # TODO : give the user the option to switch this off + if params_zero[k]: + continue + + # Set the offset to account for the variables that are + # being held fixed in the current coordinate + # optimization. + params0 = params.copy() + params0[k] = 0 + offset = np.dot(model.exog, params0) + if model_offset is not None: + offset += model_offset + + # Create a one-variable model for optimization. + model_1var = model.__class__( + model.endog, model.exog[:, k], offset=offset, **init_args) + + # Do the one-dimensional optimization. + func, grad, hess = fgh_list[k] + params[k] = _opt_1d( + func, grad, hess, model_1var, params[k], alpha[k]*L1_wt, + tol=btol, check_step=check_step) + + # Update the active set + if itr > 0 and np.abs(params[k]) < zero_tol: + params_zero[k] = True + params[k] = 0. + + # Check for convergence + pchange = np.max(np.abs(params - params_save)) + if pchange < cnvrg_tol: + converged = True + break + + # Set approximate zero coefficients to be exactly zero + params[np.abs(params) < zero_tol] = 0 + + if not refit: + results = RegularizedResults(model, params) + results.converged = converged + return RegularizedResultsWrapper(results) + + # Fit the reduced model to get standard errors and other + # post-estimation results. + ii = np.flatnonzero(params) + cov = np.zeros((k_exog, k_exog)) + init_args = {k: getattr(model, k, None) for k in model._init_keys} + if len(ii) > 0: + model1 = model.__class__( + model.endog, model.exog[:, ii], **init_args) + rslt = model1.fit() + params[ii] = rslt.params + cov[np.ix_(ii, ii)] = rslt.normalized_cov_params + else: + # Hack: no variables were selected but we need to run fit in + # order to get the correct results class. So just fit a model + # with one variable. + model1 = model.__class__(model.endog, model.exog[:, 0], **init_args) + rslt = model1.fit(maxiter=0) + + # fit may return a results or a results wrapper + if issubclass(rslt.__class__, wrap.ResultsWrapper): + klass = rslt._results.__class__ + else: + klass = rslt.__class__ + + # Not all models have a scale + if hasattr(rslt, 'scale'): + scale = rslt.scale + else: + scale = 1. + + # The degrees of freedom should reflect the number of parameters + # in the refit model, not including the zeros that are displayed + # to indicate which variables were dropped. See issue #1723 for + # discussion about setting df parameters in model and results + # classes. + p, q = model.df_model, model.df_resid + model.df_model = len(ii) + model.df_resid = model.nobs - model.df_model + + # Assuming a standard signature for creating results classes. + refit = klass(model, params, cov, scale=scale) + refit.regularized = True + refit.converged = converged + refit.method = method + refit.fit_history = {'iteration': itr + 1} + + # Restore df in model class, see issue #1723 for discussion. + model.df_model, model.df_resid = p, q + + return refit + + +def _opt_1d(func, grad, hess, model, start, L1_wt, tol, + check_step=True): + """ + One-dimensional helper for elastic net. + + Parameters + ---------- + func : function + A smooth function of a single variable to be optimized + with L1 penaty. + grad : function + The gradient of `func`. + hess : function + The Hessian of `func`. + model : statsmodels model + The model being fit. + start : real + A starting value for the function argument + L1_wt : non-negative real + The weight for the L1 penalty function. + tol : non-negative real + A convergence threshold. + check_step : bool + If True, check that the first step is an improvement and + use bisection if it is not. If False, return after the + first step regardless. + + Notes + ----- + ``func``, ``grad``, and ``hess`` have argument signature (x, + model), where ``x`` is a point in the parameter space and + ``model`` is the model being fit. + + If the log-likelihood for the model is exactly quadratic, the + global minimum is returned in one step. Otherwise numerical + bisection is used. + + Returns + ------- + The argmin of the objective function. + """ + + # Overview: + # We want to minimize L(x) + L1_wt*abs(x), where L() is a smooth + # loss function that includes the log-likelihood and L2 penalty. + # This is a 1-dimensional optimization. If L(x) is exactly + # quadratic we can solve for the argmin exactly. Otherwise we + # approximate L(x) with a quadratic function Q(x) and try to use + # the minimizer of Q(x) + L1_wt*abs(x). But if this yields an + # uphill step for the actual target function L(x) + L1_wt*abs(x), + # then we fall back to a expensive line search. The line search + # is never needed for OLS. + + x = start + f = func(x, model) + b = grad(x, model) + c = hess(x, model) + d = b - c*x + + # The optimum is achieved by hard thresholding to zero + if L1_wt > np.abs(d): + return 0. + + # x + h is the minimizer of the Q(x) + L1_wt*abs(x) + if d >= 0: + h = (L1_wt - b) / c + elif d < 0: + h = -(L1_wt + b) / c + else: + return np.nan + + # If the new point is not uphill for the target function, take it + # and return. This check is a bit expensive and un-necessary for + # OLS + if not check_step: + return x + h + f1 = func(x + h, model) + L1_wt*np.abs(x + h) + if f1 <= f + L1_wt*np.abs(x) + 1e-10: + return x + h + + # Fallback for models where the loss is not quadratic + from scipy.optimize import brent + x_opt = brent(func, args=(model,), brack=(x-1, x+1), tol=tol) + return x_opt + + +class RegularizedResults(Results): + """ + Results for models estimated using regularization + + Parameters + ---------- + model : Model + The model instance used to estimate the parameters. + params : ndarray + The estimated (regularized) parameters. + """ + def __init__(self, model, params): + super().__init__(model, params) + + @cache_readonly + def fittedvalues(self): + """ + The predicted values from the model at the estimated parameters. + """ + return self.model.predict(self.params) + + +class RegularizedResultsWrapper(wrap.ResultsWrapper): + _attrs = { + 'params': 'columns', + 'resid': 'rows', + 'fittedvalues': 'rows', + } + _wrap_attrs = _attrs +wrap.populate_wrapper(RegularizedResultsWrapper, # noqa:E305 + RegularizedResults) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/l1_cvxopt.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/l1_cvxopt.py new file mode 100644 index 0000000000000000000000000000000000000000..11ea2a3abcae4c9f4308ecc1824b203443a2f875 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/l1_cvxopt.py @@ -0,0 +1,203 @@ +""" +Holds files for l1 regularization of LikelihoodModel, using cvxopt. +""" +import numpy as np +import statsmodels.base.l1_solvers_common as l1_solvers_common + + +def fit_l1_cvxopt_cp( + f, score, start_params, args, kwargs, disp=False, maxiter=100, + callback=None, retall=False, full_output=False, hess=None): + """ + Solve the l1 regularized problem using cvxopt.solvers.cp + + Specifically: We convert the convex but non-smooth problem + + .. math:: \\min_\\beta f(\\beta) + \\sum_k\\alpha_k |\\beta_k| + + via the transformation to the smooth, convex, constrained problem in twice + as many variables (adding the "added variables" :math:`u_k`) + + .. math:: \\min_{\\beta,u} f(\\beta) + \\sum_k\\alpha_k u_k, + + subject to + + .. math:: -u_k \\leq \\beta_k \\leq u_k. + + Parameters + ---------- + All the usual parameters from LikelhoodModel.fit + alpha : non-negative scalar or numpy array (same size as parameters) + The weight multiplying the l1 penalty term + trim_mode : 'auto, 'size', or 'off' + If not 'off', trim (set to zero) parameters that would have been zero + if the solver reached the theoretical minimum. + If 'auto', trim params using the Theory above. + If 'size', trim params if they have very small absolute value + size_trim_tol : float or 'auto' (default = 'auto') + For use when trim_mode === 'size' + auto_trim_tol : float + For sue when trim_mode == 'auto'. Use + qc_tol : float + Print warning and do not allow auto trim when (ii) in "Theory" (above) + is violated by this much. + qc_verbose : bool + If true, print out a full QC report upon failure + abstol : float + absolute accuracy (default: 1e-7). + reltol : float + relative accuracy (default: 1e-6). + feastol : float + tolerance for feasibility conditions (default: 1e-7). + refinement : int + number of iterative refinement steps when solving KKT equations + (default: 1). + """ + from cvxopt import solvers, matrix + + start_params = np.array(start_params).ravel('F') + + ## Extract arguments + # k_params is total number of covariates, possibly including a leading constant. + k_params = len(start_params) + # The start point + x0 = np.append(start_params, np.fabs(start_params)) + x0 = matrix(x0, (2 * k_params, 1)) + # The regularization parameter + alpha = np.array(kwargs['alpha_rescaled']).ravel('F') + # Make sure it's a vector + alpha = alpha * np.ones(k_params) + assert alpha.min() >= 0 + + ## Wrap up functions for cvxopt + f_0 = lambda x: _objective_func(f, x, k_params, alpha, *args) + Df = lambda x: _fprime(score, x, k_params, alpha) + G = _get_G(k_params) # Inequality constraint matrix, Gx \leq h + h = matrix(0.0, (2 * k_params, 1)) # RHS in inequality constraint + H = lambda x, z: _hessian_wrapper(hess, x, z, k_params) + + ## Define the optimization function + def F(x=None, z=None): + if x is None: + return 0, x0 + elif z is None: + return f_0(x), Df(x) + else: + return f_0(x), Df(x), H(x, z) + + ## Convert optimization settings to cvxopt form + solvers.options['show_progress'] = disp + solvers.options['maxiters'] = maxiter + if 'abstol' in kwargs: + solvers.options['abstol'] = kwargs['abstol'] + if 'reltol' in kwargs: + solvers.options['reltol'] = kwargs['reltol'] + if 'feastol' in kwargs: + solvers.options['feastol'] = kwargs['feastol'] + if 'refinement' in kwargs: + solvers.options['refinement'] = kwargs['refinement'] + + ### Call the optimizer + results = solvers.cp(F, G, h) + x = np.asarray(results['x']).ravel() + params = x[:k_params] + + ### Post-process + # QC + qc_tol = kwargs['qc_tol'] + qc_verbose = kwargs['qc_verbose'] + passed = l1_solvers_common.qc_results( + params, alpha, score, qc_tol, qc_verbose) + # Possibly trim + trim_mode = kwargs['trim_mode'] + size_trim_tol = kwargs['size_trim_tol'] + auto_trim_tol = kwargs['auto_trim_tol'] + params, trimmed = l1_solvers_common.do_trim_params( + params, k_params, alpha, score, passed, trim_mode, size_trim_tol, + auto_trim_tol) + + ### Pack up return values for statsmodels + # TODO These retvals are returned as mle_retvals...but the fit was not ML + if full_output: + fopt = f_0(x) + gopt = float('nan') # Objective is non-differentiable + hopt = float('nan') + iterations = float('nan') + converged = (results['status'] == 'optimal') + warnflag = results['status'] + retvals = { + 'fopt': fopt, 'converged': converged, 'iterations': iterations, + 'gopt': gopt, 'hopt': hopt, 'trimmed': trimmed, + 'warnflag': warnflag} + else: + x = np.array(results['x']).ravel() + params = x[:k_params] + + ### Return results + if full_output: + return params, retvals + else: + return params + + +def _objective_func(f, x, k_params, alpha, *args): + """ + The regularized objective function. + """ + from cvxopt import matrix + + x_arr = np.asarray(x) + params = x_arr[:k_params].ravel() + u = x_arr[k_params:] + # Call the numpy version + objective_func_arr = f(params, *args) + (alpha * u).sum() + # Return + return matrix(objective_func_arr) + + +def _fprime(score, x, k_params, alpha): + """ + The regularized derivative. + """ + from cvxopt import matrix + + x_arr = np.asarray(x) + params = x_arr[:k_params].ravel() + # Call the numpy version + # The derivative just appends a vector of constants + fprime_arr = np.append(score(params), alpha) + # Return + return matrix(fprime_arr, (1, 2 * k_params)) + + +def _get_G(k_params): + """ + The linear inequality constraint matrix. + """ + from cvxopt import matrix + + I = np.eye(k_params) # noqa:E741 + A = np.concatenate((-I, -I), axis=1) + B = np.concatenate((I, -I), axis=1) + C = np.concatenate((A, B), axis=0) + # Return + return matrix(C) + + +def _hessian_wrapper(hess, x, z, k_params): + """ + Wraps the hessian up in the form for cvxopt. + + cvxopt wants the hessian of the objective function and the constraints. + Since our constraints are linear, this part is all zeros. + """ + from cvxopt import matrix + + x_arr = np.asarray(x) + params = x_arr[:k_params].ravel() + zh_x = np.asarray(z[0]) * hess(params) + zero_mat = np.zeros(zh_x.shape) + A = np.concatenate((zh_x, zero_mat), axis=1) + B = np.concatenate((zero_mat, zero_mat), axis=1) + zh_x_ext = np.concatenate((A, B), axis=0) + return matrix(zh_x_ext, (2 * k_params, 2 * k_params)) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/l1_slsqp.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/l1_slsqp.py new file mode 100644 index 0000000000000000000000000000000000000000..18e1954d515dd483f87627a4122971a1526e8c5b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/l1_slsqp.py @@ -0,0 +1,168 @@ +""" +Holds files for l1 regularization of LikelihoodModel, using +scipy.optimize.slsqp +""" +import numpy as np +from scipy.optimize import fmin_slsqp +import statsmodels.base.l1_solvers_common as l1_solvers_common + + +def fit_l1_slsqp( + f, score, start_params, args, kwargs, disp=False, maxiter=1000, + callback=None, retall=False, full_output=False, hess=None): + """ + Solve the l1 regularized problem using scipy.optimize.fmin_slsqp(). + + Specifically: We convert the convex but non-smooth problem + + .. math:: \\min_\\beta f(\\beta) + \\sum_k\\alpha_k |\\beta_k| + + via the transformation to the smooth, convex, constrained problem in twice + as many variables (adding the "added variables" :math:`u_k`) + + .. math:: \\min_{\\beta,u} f(\\beta) + \\sum_k\\alpha_k u_k, + + subject to + + .. math:: -u_k \\leq \\beta_k \\leq u_k. + + Parameters + ---------- + All the usual parameters from LikelhoodModel.fit + alpha : non-negative scalar or numpy array (same size as parameters) + The weight multiplying the l1 penalty term + trim_mode : 'auto, 'size', or 'off' + If not 'off', trim (set to zero) parameters that would have been zero + if the solver reached the theoretical minimum. + If 'auto', trim params using the Theory above. + If 'size', trim params if they have very small absolute value + size_trim_tol : float or 'auto' (default = 'auto') + For use when trim_mode === 'size' + auto_trim_tol : float + For sue when trim_mode == 'auto'. Use + qc_tol : float + Print warning and do not allow auto trim when (ii) in "Theory" (above) + is violated by this much. + qc_verbose : bool + If true, print out a full QC report upon failure + acc : float (default 1e-6) + Requested accuracy as used by slsqp + """ + start_params = np.array(start_params).ravel('F') + + ### Extract values + # k_params is total number of covariates, + # possibly including a leading constant. + k_params = len(start_params) + # The start point + x0 = np.append(start_params, np.fabs(start_params)) + # alpha is the regularization parameter + alpha = np.array(kwargs['alpha_rescaled']).ravel('F') + # Make sure it's a vector + alpha = alpha * np.ones(k_params) + assert alpha.min() >= 0 + # Convert display parameters to scipy.optimize form + disp_slsqp = _get_disp_slsqp(disp, retall) + # Set/retrieve the desired accuracy + acc = kwargs.setdefault('acc', 1e-12) + + ### Wrap up for use in fmin_slsqp + func = lambda x_full: _objective_func(f, x_full, k_params, alpha, *args) + f_ieqcons_wrap = lambda x_full: _f_ieqcons(x_full, k_params) + fprime_wrap = lambda x_full: _fprime(score, x_full, k_params, alpha) + fprime_ieqcons_wrap = lambda x_full: _fprime_ieqcons(x_full, k_params) + + ### Call the solver + results = fmin_slsqp( + func, x0, f_ieqcons=f_ieqcons_wrap, fprime=fprime_wrap, acc=acc, + iter=maxiter, disp=disp_slsqp, full_output=full_output, + fprime_ieqcons=fprime_ieqcons_wrap) + params = np.asarray(results[0][:k_params]) + + ### Post-process + # QC + qc_tol = kwargs['qc_tol'] + qc_verbose = kwargs['qc_verbose'] + passed = l1_solvers_common.qc_results( + params, alpha, score, qc_tol, qc_verbose) + # Possibly trim + trim_mode = kwargs['trim_mode'] + size_trim_tol = kwargs['size_trim_tol'] + auto_trim_tol = kwargs['auto_trim_tol'] + params, trimmed = l1_solvers_common.do_trim_params( + params, k_params, alpha, score, passed, trim_mode, size_trim_tol, + auto_trim_tol) + + ### Pack up return values for statsmodels optimizers + # TODO These retvals are returned as mle_retvals...but the fit was not ML. + # This could be confusing someday. + if full_output: + x_full, fx, its, imode, smode = results + fopt = func(np.asarray(x_full)) + converged = (imode == 0) + warnflag = str(imode) + ' ' + smode + iterations = its + gopt = float('nan') # Objective is non-differentiable + hopt = float('nan') + retvals = { + 'fopt': fopt, 'converged': converged, 'iterations': iterations, + 'gopt': gopt, 'hopt': hopt, 'trimmed': trimmed, + 'warnflag': warnflag} + + ### Return + if full_output: + return params, retvals + else: + return params + + +def _get_disp_slsqp(disp, retall): + if disp or retall: + if disp: + disp_slsqp = 1 + if retall: + disp_slsqp = 2 + else: + disp_slsqp = 0 + return disp_slsqp + + +def _objective_func(f, x_full, k_params, alpha, *args): + """ + The regularized objective function + """ + x_params = x_full[:k_params] + x_added = x_full[k_params:] + ## Return + return f(x_params, *args) + (alpha * x_added).sum() + + +def _fprime(score, x_full, k_params, alpha): + """ + The regularized derivative + """ + x_params = x_full[:k_params] + # The derivative just appends a vector of constants + return np.append(score(x_params), alpha) + + +def _f_ieqcons(x_full, k_params): + """ + The inequality constraints. + """ + x_params = x_full[:k_params] + x_added = x_full[k_params:] + # All entries in this vector must be \geq 0 in a feasible solution + return np.append(x_params + x_added, x_added - x_params) + + +def _fprime_ieqcons(x_full, k_params): + """ + Derivative of the inequality constraints + """ + I = np.eye(k_params) # noqa:E741 + A = np.concatenate((I, I), axis=1) + B = np.concatenate((-I, I), axis=1) + C = np.concatenate((A, B), axis=0) + ## Return + return C diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/l1_solvers_common.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/l1_solvers_common.py new file mode 100644 index 0000000000000000000000000000000000000000..ecdd68eff57aa27aae7bab90568e89d63499820d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/l1_solvers_common.py @@ -0,0 +1,163 @@ +""" +Holds common functions for l1 solvers. +""" + +import numpy as np + +from statsmodels.tools.sm_exceptions import ConvergenceWarning + + +def qc_results(params, alpha, score, qc_tol, qc_verbose=False): + """ + Theory dictates that one of two conditions holds: + i) abs(score[i]) == alpha[i] and params[i] != 0 + ii) abs(score[i]) <= alpha[i] and params[i] == 0 + qc_results checks to see that (ii) holds, within qc_tol + + qc_results also checks for nan or results of the wrong shape. + + Parameters + ---------- + params : ndarray + model parameters. Not including the added variables x_added. + alpha : ndarray + regularization coefficients + score : function + Gradient of unregularized objective function + qc_tol : float + Tolerance to hold conditions (i) and (ii) to for QC check. + qc_verbose : bool + If true, print out a full QC report upon failure + + Returns + ------- + passed : bool + True if QC check passed + qc_dict : Dictionary + Keys are fprime, alpha, params, passed_array + + Prints + ------ + Warning message if QC check fails. + """ + ## Check for fatal errors + assert not np.isnan(params).max() + assert (params == params.ravel('F')).min(), \ + "params should have already been 1-d" + + ## Start the theory compliance check + fprime = score(params) + k_params = len(params) + + passed_array = np.array([True] * k_params) + for i in range(k_params): + if alpha[i] > 0: + # If |fprime| is too big, then something went wrong + if (abs(fprime[i]) - alpha[i]) / alpha[i] > qc_tol: + passed_array[i] = False + qc_dict = dict( + fprime=fprime, alpha=alpha, params=params, passed_array=passed_array) + passed = passed_array.min() + if not passed: + num_failed = (~passed_array).sum() + message = 'QC check did not pass for %d out of %d parameters' % ( + num_failed, k_params) + message += '\nTry increasing solver accuracy or number of iterations'\ + ', decreasing alpha, or switch solvers' + if qc_verbose: + message += _get_verbose_addon(qc_dict) + + import warnings + warnings.warn(message, ConvergenceWarning) + + return passed + + +def _get_verbose_addon(qc_dict): + alpha = qc_dict['alpha'] + params = qc_dict['params'] + fprime = qc_dict['fprime'] + passed_array = qc_dict['passed_array'] + + addon = '\n------ verbose QC printout -----------------' + addon = '\n------ Recall the problem was rescaled by 1 / nobs ---' + addon += '\n|%-10s|%-10s|%-10s|%-10s|' % ( + 'passed', 'alpha', 'fprime', 'param') + addon += '\n--------------------------------------------' + for i in range(len(alpha)): + addon += '\n|%-10s|%-10.3e|%-10.3e|%-10.3e|' % ( + passed_array[i], alpha[i], fprime[i], params[i]) + return addon + + +def do_trim_params(params, k_params, alpha, score, passed, trim_mode, + size_trim_tol, auto_trim_tol): + """ + Trims (set to zero) params that are zero at the theoretical minimum. + Uses heuristics to account for the solver not actually finding the minimum. + + In all cases, if alpha[i] == 0, then do not trim the ith param. + In all cases, do nothing with the added variables. + + Parameters + ---------- + params : ndarray + model parameters. Not including added variables. + k_params : Int + Number of parameters + alpha : ndarray + regularization coefficients + score : Function. + score(params) should return a 1-d vector of derivatives of the + unpenalized objective function. + passed : bool + True if the QC check passed + trim_mode : 'auto, 'size', or 'off' + If not 'off', trim (set to zero) parameters that would have been zero + if the solver reached the theoretical minimum. + If 'auto', trim params using the Theory above. + If 'size', trim params if they have very small absolute value + size_trim_tol : float or 'auto' (default = 'auto') + For use when trim_mode === 'size' + auto_trim_tol : float + For sue when trim_mode == 'auto'. Use + qc_tol : float + Print warning and do not allow auto trim when (ii) in "Theory" (above) + is violated by this much. + + Returns + ------- + params : ndarray + Trimmed model parameters + trimmed : ndarray of booleans + trimmed[i] == True if the ith parameter was trimmed. + """ + ## Trim the small params + trimmed = [False] * k_params + + if trim_mode == 'off': + trimmed = np.array([False] * k_params) + elif trim_mode == 'auto' and not passed: + import warnings + msg = "Could not trim params automatically due to failed QC check. " \ + "Trimming using trim_mode == 'size' will still work." + warnings.warn(msg, ConvergenceWarning) + trimmed = np.array([False] * k_params) + elif trim_mode == 'auto' and passed: + fprime = score(params) + for i in range(k_params): + if alpha[i] != 0: + if (alpha[i] - abs(fprime[i])) / alpha[i] > auto_trim_tol: + params[i] = 0.0 + trimmed[i] = True + elif trim_mode == 'size': + for i in range(k_params): + if alpha[i] != 0: + if abs(params[i]) < size_trim_tol: + params[i] = 0.0 + trimmed[i] = True + else: + raise ValueError( + "trim_mode == %s, which is not recognized" % (trim_mode)) + + return params, np.asarray(trimmed) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/model.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/model.py new file mode 100644 index 0000000000000000000000000000000000000000..82f98635d5a054e570bb2cc7c12836bb54d72854 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/model.py @@ -0,0 +1,2880 @@ +from __future__ import annotations + +from statsmodels.compat.python import lzip + +from functools import reduce +import warnings + +import numpy as np +import pandas as pd +from scipy import stats + +from statsmodels.base.data import handle_data +from statsmodels.base.optimizer import Optimizer +import statsmodels.base.wrapper as wrap +from statsmodels.formula import handle_formula_data +from statsmodels.stats.contrast import ( + ContrastResults, + WaldTestResults, + t_test_pairwise, +) +from statsmodels.tools.data import _is_using_pandas +from statsmodels.tools.decorators import ( + cache_readonly, + cached_data, + cached_value, +) +from statsmodels.tools.numdiff import approx_fprime +from statsmodels.tools.sm_exceptions import ( + HessianInversionWarning, + ValueWarning, +) +from statsmodels.tools.tools import nan_dot, recipr +from statsmodels.tools.validation import bool_like + +ERROR_INIT_KWARGS = False + +_model_params_doc = """Parameters + ---------- + endog : array_like + A 1-d endogenous response variable. The dependent variable. + exog : array_like + A nobs x k array where `nobs` is the number of observations and `k` + is the number of regressors. An intercept is not included by default + and should be added by the user. See + :func:`statsmodels.tools.add_constant`.""" + +_missing_param_doc = """\ +missing : str + Available options are 'none', 'drop', and 'raise'. If 'none', no nan + checking is done. If 'drop', any observations with nans are dropped. + If 'raise', an error is raised. Default is 'none'.""" +_extra_param_doc = """ + hasconst : None or bool + Indicates whether the RHS includes a user-supplied constant. If True, + a constant is not checked for and k_constant is set to 1 and all + result statistics are calculated as if a constant is present. If + False, a constant is not checked for and k_constant is set to 0. + **kwargs + Extra arguments that are used to set model properties when using the + formula interface.""" + + +class Model: + __doc__ = """ + A (predictive) statistical model. Intended to be subclassed not used. + + {params_doc} + {extra_params_doc} + + Attributes + ---------- + exog_names + endog_names + + Notes + ----- + `endog` and `exog` are references to any data provided. So if the data is + already stored in numpy arrays and it is changed then `endog` and `exog` + will change as well. + """.format(params_doc=_model_params_doc, + extra_params_doc=_missing_param_doc + _extra_param_doc) + + # Maximum number of endogenous variables when using a formula + # Default is 1, which is more common. Override in models when needed + # Set to None to skip check + _formula_max_endog = 1 + # kwargs that are generically allowed, maybe not supported in all models + _kwargs_allowed = [ + "missing", 'missing_idx', 'formula', 'design_info', "hasconst", + ] + + def __init__(self, endog, exog=None, **kwargs): + missing = kwargs.pop('missing', 'none') + hasconst = kwargs.pop('hasconst', None) + self.data = self._handle_data(endog, exog, missing, hasconst, + **kwargs) + self.k_constant = self.data.k_constant + self.exog = self.data.exog + self.endog = self.data.endog + self._data_attr = [] + self._data_attr.extend(['exog', 'endog', 'data.exog', 'data.endog']) + if 'formula' not in kwargs: # will not be able to unpickle without these + self._data_attr.extend(['data.orig_endog', 'data.orig_exog']) + # store keys for extras if we need to recreate model instance + # we do not need 'missing', maybe we need 'hasconst' + self._init_keys = list(kwargs.keys()) + if hasconst is not None: + self._init_keys.append('hasconst') + + def _get_init_kwds(self): + """return dictionary with extra keys used in model.__init__ + """ + kwds = {key: getattr(self, key, None) + for key in self._init_keys} + + return kwds + + def _check_kwargs(self, kwargs, keys_extra=None, error=ERROR_INIT_KWARGS): + + kwargs_allowed = [ + "missing", 'missing_idx', 'formula', 'design_info', "hasconst", + ] + if keys_extra: + kwargs_allowed.extend(keys_extra) + + kwargs_invalid = [i for i in kwargs if i not in kwargs_allowed] + if kwargs_invalid: + msg = "unknown kwargs " + repr(kwargs_invalid) + if error is False: + warnings.warn(msg, ValueWarning) + else: + raise ValueError(msg) + + def _handle_data(self, endog, exog, missing, hasconst, **kwargs): + data = handle_data(endog, exog, missing, hasconst, **kwargs) + # kwargs arrays could have changed, easier to just attach here + for key in kwargs: + if key in ['design_info', 'formula']: # leave attached to data + continue + # pop so we do not start keeping all these twice or references + try: + setattr(self, key, data.__dict__.pop(key)) + except KeyError: # panel already pops keys in data handling + pass + return data + + @classmethod + def from_formula(cls, formula, data, subset=None, drop_cols=None, + *args, **kwargs): + """ + Create a Model from a formula and dataframe. + + Parameters + ---------- + formula : str or generic Formula object + The formula specifying the model. + data : array_like + The data for the model. See Notes. + subset : array_like + An array-like object of booleans, integers, or index values that + indicate the subset of df to use in the model. Assumes df is a + `pandas.DataFrame`. + drop_cols : array_like + Columns to drop from the design matrix. Cannot be used to + drop terms involving categoricals. + *args + Additional positional argument that are passed to the model. + **kwargs + These are passed to the model with one exception. The + ``eval_env`` keyword is passed to patsy. It can be either a + :class:`patsy:patsy.EvalEnvironment` object or an integer + indicating the depth of the namespace to use. For example, the + default ``eval_env=0`` uses the calling namespace. If you wish + to use a "clean" environment set ``eval_env=-1``. + + Returns + ------- + model + The model instance. + + Notes + ----- + data must define __getitem__ with the keys in the formula terms + args and kwargs are passed on to the model instantiation. E.g., + a numpy structured or rec array, a dictionary, or a pandas DataFrame. + """ + # TODO: provide a docs template for args/kwargs from child models + # TODO: subset could use syntax. issue #469. + if subset is not None: + data = data.loc[subset] + eval_env = kwargs.pop('eval_env', None) + if eval_env is None: + eval_env = 2 + elif eval_env == -1: + from patsy import EvalEnvironment + eval_env = EvalEnvironment({}) + elif isinstance(eval_env, int): + eval_env += 1 # we're going down the stack again + missing = kwargs.get('missing', 'drop') + if missing == 'none': # with patsy it's drop or raise. let's raise. + missing = 'raise' + + tmp = handle_formula_data(data, None, formula, depth=eval_env, + missing=missing) + ((endog, exog), missing_idx, design_info) = tmp + max_endog = cls._formula_max_endog + if (max_endog is not None and + endog.ndim > 1 and endog.shape[1] > max_endog): + raise ValueError('endog has evaluated to an array with multiple ' + 'columns that has shape {}. This occurs when ' + 'the variable converted to endog is non-numeric' + ' (e.g., bool or str).'.format(endog.shape)) + if drop_cols is not None and len(drop_cols) > 0: + cols = [x for x in exog.columns if x not in drop_cols] + if len(cols) < len(exog.columns): + exog = exog[cols] + cols = list(design_info.term_names) + for col in drop_cols: + try: + cols.remove(col) + except ValueError: + pass # OK if not present + design_info = design_info.subset(cols) + + kwargs.update({'missing_idx': missing_idx, + 'missing': missing, + 'formula': formula, # attach formula for unpckling + 'design_info': design_info}) + mod = cls(endog, exog, *args, **kwargs) + mod.formula = formula + # since we got a dataframe, attach the original + mod.data.frame = data + return mod + + @property + def endog_names(self): + """ + Names of endogenous variables. + """ + return self.data.ynames + + @property + def exog_names(self) -> list[str] | None: + """ + Names of exogenous variables. + """ + return self.data.xnames + + def fit(self): + """ + Fit a model to data. + """ + raise NotImplementedError + + def predict(self, params, exog=None, *args, **kwargs): + """ + After a model has been fit predict returns the fitted values. + + This is a placeholder intended to be overwritten by individual models. + """ + raise NotImplementedError + + +class LikelihoodModel(Model): + """ + Likelihood model is a subclass of Model. + """ + + def __init__(self, endog, exog=None, **kwargs): + super().__init__(endog, exog, **kwargs) + self.initialize() + + def initialize(self): + """ + Initialize (possibly re-initialize) a Model instance. + + For example, if the the design matrix of a linear model changes then + initialized can be used to recompute values using the modified design + matrix. + """ + pass + + # TODO: if the intent is to re-initialize the model with new data then this + # method needs to take inputs... + + def loglike(self, params): + """ + Log-likelihood of model. + + Parameters + ---------- + params : ndarray + The model parameters used to compute the log-likelihood. + + Notes + ----- + Must be overridden by subclasses. + """ + raise NotImplementedError + + def score(self, params): + """ + Score vector of model. + + The gradient of logL with respect to each parameter. + + Parameters + ---------- + params : ndarray + The parameters to use when evaluating the Hessian. + + Returns + ------- + ndarray + The score vector evaluated at the parameters. + """ + raise NotImplementedError + + def information(self, params): + """ + Fisher information matrix of model. + + Returns -1 * Hessian of the log-likelihood evaluated at params. + + Parameters + ---------- + params : ndarray + The model parameters. + """ + raise NotImplementedError + + def hessian(self, params): + """ + The Hessian matrix of the model. + + Parameters + ---------- + params : ndarray + The parameters to use when evaluating the Hessian. + + Returns + ------- + ndarray + The hessian evaluated at the parameters. + """ + raise NotImplementedError + + def fit(self, start_params=None, method='newton', maxiter=100, + full_output=True, disp=True, fargs=(), callback=None, retall=False, + skip_hessian=False, **kwargs): + """ + Fit method for likelihood based models + + Parameters + ---------- + start_params : array_like, optional + Initial guess of the solution for the loglikelihood maximization. + The default is an array of zeros. + method : str, optional + The `method` determines which solver from `scipy.optimize` + is used, and it can be chosen from among the following strings: + + - 'newton' for Newton-Raphson, 'nm' for Nelder-Mead + - 'bfgs' for Broyden-Fletcher-Goldfarb-Shanno (BFGS) + - 'lbfgs' for limited-memory BFGS with optional box constraints + - 'powell' for modified Powell's method + - 'cg' for conjugate gradient + - 'ncg' for Newton-conjugate gradient + - 'basinhopping' for global basin-hopping solver + - 'minimize' for generic wrapper of scipy minimize (BFGS by default) + + The explicit arguments in `fit` are passed to the solver, + with the exception of the basin-hopping solver. Each + solver has several optional arguments that are not the same across + solvers. See the notes section below (or scipy.optimize) for the + available arguments and for the list of explicit arguments that the + basin-hopping solver supports. + maxiter : int, optional + The maximum number of iterations to perform. + full_output : bool, optional + Set to True to have all available output in the Results object's + mle_retvals attribute. The output is dependent on the solver. + See LikelihoodModelResults notes section for more information. + disp : bool, optional + Set to True to print convergence messages. + fargs : tuple, optional + Extra arguments passed to the likelihood function, i.e., + loglike(x,*args) + callback : callable callback(xk), optional + Called after each iteration, as callback(xk), where xk is the + current parameter vector. + retall : bool, optional + Set to True to return list of solutions at each iteration. + Available in Results object's mle_retvals attribute. + skip_hessian : bool, optional + If False (default), then the negative inverse hessian is calculated + after the optimization. If True, then the hessian will not be + calculated. However, it will be available in methods that use the + hessian in the optimization (currently only with `"newton"`). + kwargs : keywords + All kwargs are passed to the chosen solver with one exception. The + following keyword controls what happens after the fit:: + + warn_convergence : bool, optional + If True, checks the model for the converged flag. If the + converged flag is False, a ConvergenceWarning is issued. + + Notes + ----- + The 'basinhopping' solver ignores `maxiter`, `retall`, `full_output` + explicit arguments. + + Optional arguments for solvers (see returned Results.mle_settings):: + + 'newton' + tol : float + Relative error in params acceptable for convergence. + 'nm' -- Nelder Mead + xtol : float + Relative error in params acceptable for convergence + ftol : float + Relative error in loglike(params) acceptable for + convergence + maxfun : int + Maximum number of function evaluations to make. + 'bfgs' + gtol : float + Stop when norm of gradient is less than gtol. + norm : float + Order of norm (np.inf is max, -np.inf is min) + epsilon + If fprime is approximated, use this value for the step + size. Only relevant if LikelihoodModel.score is None. + 'lbfgs' + m : int + This many terms are used for the Hessian approximation. + factr : float + A stop condition that is a variant of relative error. + pgtol : float + A stop condition that uses the projected gradient. + epsilon + If fprime is approximated, use this value for the step + size. Only relevant if LikelihoodModel.score is None. + maxfun : int + Maximum number of function evaluations to make. + bounds : sequence + (min, max) pairs for each element in x, + defining the bounds on that parameter. + Use None for one of min or max when there is no bound + in that direction. + 'cg' + gtol : float + Stop when norm of gradient is less than gtol. + norm : float + Order of norm (np.inf is max, -np.inf is min) + epsilon : float + If fprime is approximated, use this value for the step + size. Can be scalar or vector. Only relevant if + Likelihoodmodel.score is None. + 'ncg' + fhess_p : callable f'(x,*args) + Function which computes the Hessian of f times an arbitrary + vector, p. Should only be supplied if + LikelihoodModel.hessian is None. + avextol : float + Stop when the average relative error in the minimizer + falls below this amount. + epsilon : float or ndarray + If fhess is approximated, use this value for the step size. + Only relevant if Likelihoodmodel.hessian is None. + 'powell' + xtol : float + Line-search error tolerance + ftol : float + Relative error in loglike(params) for acceptable for + convergence. + maxfun : int + Maximum number of function evaluations to make. + start_direc : ndarray + Initial direction set. + 'basinhopping' + niter : int + The number of basin hopping iterations. + niter_success : int + Stop the run if the global minimum candidate remains the + same for this number of iterations. + T : float + The "temperature" parameter for the accept or reject + criterion. Higher "temperatures" mean that larger jumps + in function value will be accepted. For best results + `T` should be comparable to the separation (in function + value) between local minima. + stepsize : float + Initial step size for use in the random displacement. + interval : int + The interval for how often to update the `stepsize`. + minimizer : dict + Extra keyword arguments to be passed to the minimizer + `scipy.optimize.minimize()`, for example 'method' - the + minimization method (e.g. 'L-BFGS-B'), or 'tol' - the + tolerance for termination. Other arguments are mapped from + explicit argument of `fit`: + - `args` <- `fargs` + - `jac` <- `score` + - `hess` <- `hess` + 'minimize' + min_method : str, optional + Name of minimization method to use. + Any method specific arguments can be passed directly. + For a list of methods and their arguments, see + documentation of `scipy.optimize.minimize`. + If no method is specified, then BFGS is used. + """ + Hinv = None # JP error if full_output=0, Hinv not defined + + if start_params is None: + if hasattr(self, 'start_params'): + start_params = self.start_params + elif self.exog is not None: + # fails for shape (K,)? + start_params = [0.0] * self.exog.shape[1] + else: + raise ValueError("If exog is None, then start_params should " + "be specified") + + # TODO: separate args from nonarg taking score and hessian, ie., + # user-supplied and numerically evaluated estimate frprime does not take + # args in most (any?) of the optimize function + + nobs = self.endog.shape[0] + # f = lambda params, *args: -self.loglike(params, *args) / nobs + + def f(params, *args): + return -self.loglike(params, *args) / nobs + + if method == 'newton': + # TODO: why are score and hess positive? + def score(params, *args): + return self.score(params, *args) / nobs + + def hess(params, *args): + return self.hessian(params, *args) / nobs + else: + def score(params, *args): + return -self.score(params, *args) / nobs + + def hess(params, *args): + return -self.hessian(params, *args) / nobs + + warn_convergence = kwargs.pop('warn_convergence', True) + + # Remove covariance args before calling fir to allow strict checking + if 'cov_type' in kwargs: + cov_kwds = kwargs.get('cov_kwds', {}) + kwds = {'cov_type': kwargs['cov_type'], 'cov_kwds': cov_kwds} + if cov_kwds: + del kwargs["cov_kwds"] + del kwargs["cov_type"] + else: + kwds = {} + if 'use_t' in kwargs: + kwds['use_t'] = kwargs['use_t'] + del kwargs["use_t"] + + optimizer = Optimizer() + xopt, retvals, optim_settings = optimizer._fit(f, score, start_params, + fargs, kwargs, + hessian=hess, + method=method, + disp=disp, + maxiter=maxiter, + callback=callback, + retall=retall, + full_output=full_output) + # Restore cov_type, cov_kwds and use_t + optim_settings.update(kwds) + # NOTE: this is for fit_regularized and should be generalized + cov_params_func = kwargs.setdefault('cov_params_func', None) + if cov_params_func: + Hinv = cov_params_func(self, xopt, retvals) + elif method == 'newton' and full_output: + Hinv = np.linalg.inv(-retvals['Hessian']) / nobs + elif not skip_hessian: + H = -1 * self.hessian(xopt) + invertible = False + if np.all(np.isfinite(H)): + eigvals, eigvecs = np.linalg.eigh(H) + if np.min(eigvals) > 0: + invertible = True + + if invertible: + Hinv = eigvecs.dot(np.diag(1.0 / eigvals)).dot(eigvecs.T) + Hinv = np.asfortranarray((Hinv + Hinv.T) / 2.0) + else: + warnings.warn('Inverting hessian failed, no bse or cov_params ' + 'available', HessianInversionWarning) + Hinv = None + + # TODO: add Hessian approximation and change the above if needed + mlefit = LikelihoodModelResults(self, xopt, Hinv, scale=1., **kwds) + + # TODO: hardcode scale? + mlefit.mle_retvals = retvals + if isinstance(retvals, dict): + if warn_convergence and not retvals['converged']: + from statsmodels.tools.sm_exceptions import ConvergenceWarning + warnings.warn("Maximum Likelihood optimization failed to " + "converge. Check mle_retvals", + ConvergenceWarning) + + mlefit.mle_settings = optim_settings + return mlefit + + def _fit_zeros(self, keep_index=None, start_params=None, + return_auxiliary=False, k_params=None, **fit_kwds): + """experimental, fit the model subject to zero constraints + + Intended for internal use cases until we know what we need. + API will need to change to handle models with two exog. + This is not yet supported by all model subclasses. + + This is essentially a simplified version of `fit_constrained`, and + does not need to use `offset`. + + The estimation creates a new model with transformed design matrix, + exog, and converts the results back to the original parameterization. + + Some subclasses could use a more efficient calculation than using a + new model. + + Parameters + ---------- + keep_index : array_like (int or bool) or slice + variables that should be dropped. + start_params : None or array_like + starting values for the optimization. `start_params` needs to be + given in the original parameter space and are internally + transformed. + k_params : int or None + If None, then we try to infer from start_params or model. + **fit_kwds : keyword arguments + fit_kwds are used in the optimization of the transformed model. + + Returns + ------- + results : Results instance + """ + # we need to append index of extra params to keep_index as in + # NegativeBinomial + if hasattr(self, 'k_extra') and self.k_extra > 0: + # we cannot change the original, TODO: should we add keep_index_params? + keep_index = np.array(keep_index, copy=True) + k = self.exog.shape[1] + extra_index = np.arange(k, k + self.k_extra) + keep_index_p = np.concatenate((keep_index, extra_index)) + else: + keep_index_p = keep_index + + # not all models support start_params, drop if None, hide them in fit_kwds + if start_params is not None: + fit_kwds['start_params'] = start_params[keep_index_p] + k_params = len(start_params) + # ignore k_params in this case, or verify consisteny? + + # build auxiliary model and fit + init_kwds = self._get_init_kwds() + mod_constr = self.__class__(self.endog, self.exog[:, keep_index], + **init_kwds) + res_constr = mod_constr.fit(**fit_kwds) + # switch name, only need keep_index for params below + keep_index = keep_index_p + + if k_params is None: + k_params = self.exog.shape[1] + k_params += getattr(self, 'k_extra', 0) + + params_full = np.zeros(k_params) + params_full[keep_index] = res_constr.params + + # create dummy results Instance, TODO: wire up properly + # TODO: this could be moved into separate private method if needed + # discrete L1 fit_regularized doens't reestimate AFAICS + # RLM does not have method, disp nor warn_convergence keywords + # OLS, WLS swallows extra kwds with **kwargs, but does not have method='nm' + try: + # Note: addding full_output=False causes exceptions + res = self.fit(maxiter=0, disp=0, method='nm', skip_hessian=True, + warn_convergence=False, start_params=params_full) + # we get a wrapper back + except (TypeError, ValueError): + res = self.fit() + + # Warning: make sure we are not just changing the wrapper instead of + # results #2400 + # TODO: do we need to change res._results.scale in some models? + if hasattr(res_constr.model, 'scale'): + # Note: res.model is self + # GLM problem, see #2399, + # TODO: remove from model if not needed anymore + res.model.scale = res._results.scale = res_constr.model.scale + + if hasattr(res_constr, 'mle_retvals'): + res._results.mle_retvals = res_constr.mle_retvals + # not available for not scipy optimization, e.g. glm irls + # TODO: what retvals should be required? + # res.mle_retvals['fcall'] = res_constr.mle_retvals.get('fcall', np.nan) + # res.mle_retvals['iterations'] = res_constr.mle_retvals.get( + # 'iterations', np.nan) + # res.mle_retvals['converged'] = res_constr.mle_retvals['converged'] + # overwrite all mle_settings + if hasattr(res_constr, 'mle_settings'): + res._results.mle_settings = res_constr.mle_settings + + res._results.params = params_full + if (not hasattr(res._results, 'normalized_cov_params') or + res._results.normalized_cov_params is None): + res._results.normalized_cov_params = np.zeros((k_params, k_params)) + else: + res._results.normalized_cov_params[...] = 0 + + # fancy indexing requires integer array + keep_index = np.array(keep_index) + res._results.normalized_cov_params[keep_index[:, None], keep_index] = \ + res_constr.normalized_cov_params + k_constr = res_constr.df_resid - res._results.df_resid + if hasattr(res_constr, 'cov_params_default'): + res._results.cov_params_default = np.zeros((k_params, k_params)) + res._results.cov_params_default[keep_index[:, None], keep_index] = \ + res_constr.cov_params_default + if hasattr(res_constr, 'cov_type'): + res._results.cov_type = res_constr.cov_type + res._results.cov_kwds = res_constr.cov_kwds + + res._results.keep_index = keep_index + res._results.df_resid = res_constr.df_resid + res._results.df_model = res_constr.df_model + + res._results.k_constr = k_constr + res._results.results_constrained = res_constr + + # special temporary workaround for RLM + # need to be able to override robust covariances + if hasattr(res.model, 'M'): + del res._results._cache['resid'] + del res._results._cache['fittedvalues'] + del res._results._cache['sresid'] + cov = res._results._cache['bcov_scaled'] + # inplace adjustment + cov[...] = 0 + cov[keep_index[:, None], keep_index] = res_constr.bcov_scaled + res._results.cov_params_default = cov + + return res + + def _fit_collinear(self, atol=1e-14, rtol=1e-13, **kwds): + """experimental, fit of the model without collinear variables + + This currently uses QR to drop variables based on the given + sequence. + Options will be added in future, when the supporting functions + to identify collinear variables become available. + """ + + # ------ copied from PR #2380 remove when merged + x = self.exog + tol = atol + rtol * x.var(0) + r = np.linalg.qr(x, mode='r') + mask = np.abs(r.diagonal()) < np.sqrt(tol) + # TODO add to results instance + # idx_collinear = np.where(mask)[0] + idx_keep = np.where(~mask)[0] + return self._fit_zeros(keep_index=idx_keep, **kwds) + + +# TODO: the below is unfinished +class GenericLikelihoodModel(LikelihoodModel): + """ + Allows the fitting of any likelihood function via maximum likelihood. + + A subclass needs to specify at least the log-likelihood + If the log-likelihood is specified for each observation, then results that + require the Jacobian will be available. (The other case is not tested yet.) + + Notes + ----- + Optimization methods that require only a likelihood function are 'nm' and + 'powell' + + Optimization methods that require a likelihood function and a + score/gradient are 'bfgs', 'cg', and 'ncg'. A function to compute the + Hessian is optional for 'ncg'. + + Optimization method that require a likelihood function, a score/gradient, + and a Hessian is 'newton' + + If they are not overwritten by a subclass, then numerical gradient, + Jacobian and Hessian of the log-likelihood are calculated by numerical + forward differentiation. This might results in some cases in precision + problems, and the Hessian might not be positive definite. Even if the + Hessian is not positive definite the covariance matrix of the parameter + estimates based on the outer product of the Jacobian might still be valid. + + + Examples + -------- + see also subclasses in directory miscmodels + + import statsmodels.api as sm + data = sm.datasets.spector.load() + data.exog = sm.add_constant(data.exog) + # in this dir + from model import GenericLikelihoodModel + probit_mod = sm.Probit(data.endog, data.exog) + probit_res = probit_mod.fit() + loglike = probit_mod.loglike + score = probit_mod.score + mod = GenericLikelihoodModel(data.endog, data.exog, loglike, score) + res = mod.fit(method="nm", maxiter = 500) + import numpy as np + np.allclose(res.params, probit_res.params) + """ + def __init__(self, endog, exog=None, loglike=None, score=None, + hessian=None, missing='none', extra_params_names=None, + **kwds): + # let them be none in case user wants to use inheritance + if loglike is not None: + self.loglike = loglike + if score is not None: + self.score = score + if hessian is not None: + self.hessian = hessian + + hasconst = kwds.pop("hasconst", None) + self.__dict__.update(kwds) + + # TODO: data structures? + + # TODO temporary solution, force approx normal + # self.df_model = 9999 + # somewhere: CacheWriteWarning: 'df_model' cannot be overwritten + super().__init__( + endog, exog, missing=missing, hasconst=hasconst, **kwds + ) + + # this will not work for ru2nmnl, maybe np.ndim of a dict? + if exog is not None: + self.nparams = (exog.shape[1] if np.ndim(exog) == 2 else 1) + + if extra_params_names is not None: + self._set_extra_params_names(extra_params_names) + + def _set_extra_params_names(self, extra_params_names): + # check param_names + if extra_params_names is not None: + if self.exog is not None: + self.exog_names.extend(extra_params_names) + else: + self.data.xnames = extra_params_names + + self.k_extra = len(extra_params_names) + if hasattr(self, "df_resid"): + self.df_resid -= self.k_extra + + self.nparams = len(self.exog_names) + + # this is redundant and not used when subclassing + def initialize(self): + """ + Initialize (possibly re-initialize) a Model instance. For + instance, the design matrix of a linear model may change + and some things must be recomputed. + """ + if not self.score: # right now score is not optional + self.score = lambda x: approx_fprime(x, self.loglike) + if not self.hessian: + pass + else: # can use approx_hess_p if we have a gradient + if not self.hessian: + pass + # Initialize is called by + # statsmodels.model.LikelihoodModel.__init__ + # and should contain any preprocessing that needs to be done for a model + if self.exog is not None: + # assume constant + er = np.linalg.matrix_rank(self.exog) + self.df_model = float(er - 1) + self.df_resid = float(self.exog.shape[0] - er) + else: + self.df_model = np.nan + self.df_resid = np.nan + super().initialize() + + def expandparams(self, params): + """ + expand to full parameter array when some parameters are fixed + + Parameters + ---------- + params : ndarray + reduced parameter array + + Returns + ------- + paramsfull : ndarray + expanded parameter array where fixed parameters are included + + Notes + ----- + Calling this requires that self.fixed_params and self.fixed_paramsmask + are defined. + + *developer notes:* + + This can be used in the log-likelihood to ... + + this could also be replaced by a more general parameter + transformation. + """ + paramsfull = self.fixed_params.copy() + paramsfull[self.fixed_paramsmask] = params + return paramsfull + + def reduceparams(self, params): + """Reduce parameters""" + return params[self.fixed_paramsmask] + + def loglike(self, params): + """Log-likelihood of model at params""" + return self.loglikeobs(params).sum(0) + + def nloglike(self, params): + """Negative log-likelihood of model at params""" + return -self.loglikeobs(params).sum(0) + + def loglikeobs(self, params): + """ + Log-likelihood of the model for all observations at params. + + Parameters + ---------- + params : array_like + The parameters of the model. + + Returns + ------- + loglike : array_like + The log likelihood of the model evaluated at `params`. + """ + return -self.nloglikeobs(params) + + def score(self, params): + """ + Gradient of log-likelihood evaluated at params + """ + kwds = {} + kwds.setdefault('centered', True) + return approx_fprime(params, self.loglike, **kwds).ravel() + + def score_obs(self, params, **kwds): + """ + Jacobian/Gradient of log-likelihood evaluated at params for each + observation. + """ + # kwds.setdefault('epsilon', 1e-4) + kwds.setdefault('centered', True) + return approx_fprime(params, self.loglikeobs, **kwds) + + def hessian(self, params): + """ + Hessian of log-likelihood evaluated at params + """ + from statsmodels.tools.numdiff import approx_hess + + # need options for hess (epsilon) + return approx_hess(params, self.loglike) + + def hessian_factor(self, params, scale=None, observed=True): + """Weights for calculating Hessian + + Parameters + ---------- + params : ndarray + parameter at which Hessian is evaluated + scale : None or float + If scale is None, then the default scale will be calculated. + Default scale is defined by `self.scaletype` and set in fit. + If scale is not None, then it is used as a fixed scale. + observed : bool + If True, then the observed Hessian is returned. If false then the + expected information matrix is returned. + + Returns + ------- + hessian_factor : ndarray, 1d + A 1d weight vector used in the calculation of the Hessian. + The hessian is obtained by `(exog.T * hessian_factor).dot(exog)` + """ + + raise NotImplementedError + + def fit(self, start_params=None, method='nm', maxiter=500, full_output=1, + disp=1, callback=None, retall=0, **kwargs): + + if start_params is None: + if hasattr(self, 'start_params'): + start_params = self.start_params + else: + start_params = 0.1 * np.ones(self.nparams) + + if "cov_type" not in kwargs: + # this will add default cov_type name and description + kwargs["cov_type"] = 'nonrobust' + + fit_method = super().fit + mlefit = fit_method(start_params=start_params, + method=method, maxiter=maxiter, + full_output=full_output, + disp=disp, callback=callback, **kwargs) + + results_class = getattr(self, 'results_class', + GenericLikelihoodModelResults) + genericmlefit = results_class(self, mlefit) + + # amend param names + exog_names = [] if (self.exog_names is None) else self.exog_names + k_miss = len(exog_names) - len(mlefit.params) + if not k_miss == 0: + if k_miss < 0: + self._set_extra_params_names(['par%d' % i + for i in range(-k_miss)]) + else: + # I do not want to raise after we have already fit() + warnings.warn('more exog_names than parameters', ValueWarning) + + return genericmlefit + + +class Results: + """ + Class to contain model results + + Parameters + ---------- + model : class instance + the previously specified model instance + params : ndarray + parameter estimates from the fit model + """ + def __init__(self, model, params, **kwd): + self.__dict__.update(kwd) + self.initialize(model, params, **kwd) + self._data_attr = [] + # Variables to clear from cache + self._data_in_cache = ['fittedvalues', 'resid', 'wresid'] + + def initialize(self, model, params, **kwargs): + """ + Initialize (possibly re-initialize) a Results instance. + + Parameters + ---------- + model : Model + The model instance. + params : ndarray + The model parameters. + **kwargs + Any additional keyword arguments required to initialize the model. + """ + self.params = params + self.model = model + if hasattr(model, 'k_constant'): + self.k_constant = model.k_constant + + def _transform_predict_exog(self, exog, transform=True): + + is_pandas = _is_using_pandas(exog, None) + exog_index = None + if is_pandas: + if exog.ndim == 2 or self.params.size == 1: + exog_index = exog.index + else: + exog_index = [exog.index.name] + + if transform and hasattr(self.model, 'formula') and (exog is not None): + # allow both location of design_info, see #7043 + design_info = (getattr(self.model, "design_info", None) or + self.model.data.design_info) + from patsy import dmatrix + if isinstance(exog, pd.Series): + # we are guessing whether it should be column or row + if (hasattr(exog, 'name') and isinstance(exog.name, str) and + exog.name in design_info.describe()): + # assume we need one column + exog = pd.DataFrame(exog) + else: + # assume we need a row + exog = pd.DataFrame(exog).T + exog_index = exog.index + orig_exog_len = len(exog) + is_dict = isinstance(exog, dict) + try: + exog = dmatrix(design_info, exog, return_type="dataframe") + except Exception as exc: + msg = ('predict requires that you use a DataFrame when ' + 'predicting from a model\nthat was created using the ' + 'formula api.' + '\n\nThe original error message returned by patsy is:\n' + '{}'.format(str(str(exc)))) + raise exc.__class__(msg) + if orig_exog_len > len(exog) and not is_dict: + if exog_index is None: + warnings.warn('nan values have been dropped', ValueWarning) + else: + exog = exog.reindex(exog_index) + exog_index = exog.index + + if exog is not None: + exog = np.asarray(exog) + if exog.ndim == 1 and (self.model.exog.ndim == 1 or + self.model.exog.shape[1] == 1): + exog = exog[:, None] + exog = np.atleast_2d(exog) # needed in count model shape[1] + + return exog, exog_index + + def predict(self, exog=None, transform=True, *args, **kwargs): + """ + Call self.model.predict with self.params as the first argument. + + Parameters + ---------- + exog : array_like, optional + The values for which you want to predict. see Notes below. + transform : bool, optional + If the model was fit via a formula, do you want to pass + exog through the formula. Default is True. E.g., if you fit + a model y ~ log(x1) + log(x2), and transform is True, then + you can pass a data structure that contains x1 and x2 in + their original form. Otherwise, you'd need to log the data + first. + *args + Additional arguments to pass to the model, see the + predict method of the model for the details. + **kwargs + Additional keywords arguments to pass to the model, see the + predict method of the model for the details. + + Returns + ------- + array_like + See self.model.predict. + + Notes + ----- + The types of exog that are supported depends on whether a formula + was used in the specification of the model. + + If a formula was used, then exog is processed in the same way as + the original data. This transformation needs to have key access to the + same variable names, and can be a pandas DataFrame or a dict like + object that contains numpy arrays. + + If no formula was used, then the provided exog needs to have the + same number of columns as the original exog in the model. No + transformation of the data is performed except converting it to + a numpy array. + + Row indices as in pandas data frames are supported, and added to the + returned prediction. + """ + exog, exog_index = self._transform_predict_exog(exog, + transform=transform) + + predict_results = self.model.predict(self.params, exog, *args, + **kwargs) + + if exog_index is not None and not hasattr(predict_results, + 'predicted_values'): + if predict_results.ndim == 1: + return pd.Series(predict_results, index=exog_index) + else: + return pd.DataFrame(predict_results, index=exog_index) + else: + return predict_results + + def summary(self): + """ + Summary + + Not implemented + """ + raise NotImplementedError + + +# TODO: public method? +class LikelihoodModelResults(Results): + """ + Class to contain results from likelihood models + + Parameters + ---------- + model : LikelihoodModel instance or subclass instance + LikelihoodModelResults holds a reference to the model that is fit. + params : 1d array_like + parameter estimates from estimated model + normalized_cov_params : 2d array + Normalized (before scaling) covariance of params. (dot(X.T,X))**-1 + scale : float + For (some subset of models) scale will typically be the + mean square error from the estimated model (sigma^2) + + Attributes + ---------- + mle_retvals : dict + Contains the values returned from the chosen optimization method if + full_output is True during the fit. Available only if the model + is fit by maximum likelihood. See notes below for the output from + the different methods. + mle_settings : dict + Contains the arguments passed to the chosen optimization method. + Available if the model is fit by maximum likelihood. See + LikelihoodModel.fit for more information. + model : model instance + LikelihoodResults contains a reference to the model that is fit. + params : ndarray + The parameters estimated for the model. + scale : float + The scaling factor of the model given during instantiation. + tvalues : ndarray + The t-values of the standard errors. + + + Notes + ----- + The covariance of params is given by scale times normalized_cov_params. + + Return values by solver if full_output is True during fit: + + 'newton' + fopt : float + The value of the (negative) loglikelihood at its + minimum. + iterations : int + Number of iterations performed. + score : ndarray + The score vector at the optimum. + Hessian : ndarray + The Hessian at the optimum. + warnflag : int + 1 if maxiter is exceeded. 0 if successful convergence. + converged : bool + True: converged. False: did not converge. + allvecs : list + List of solutions at each iteration. + 'nm' + fopt : float + The value of the (negative) loglikelihood at its + minimum. + iterations : int + Number of iterations performed. + warnflag : int + 1: Maximum number of function evaluations made. + 2: Maximum number of iterations reached. + converged : bool + True: converged. False: did not converge. + allvecs : list + List of solutions at each iteration. + 'bfgs' + fopt : float + Value of the (negative) loglikelihood at its minimum. + gopt : float + Value of gradient at minimum, which should be near 0. + Hinv : ndarray + value of the inverse Hessian matrix at minimum. Note + that this is just an approximation and will often be + different from the value of the analytic Hessian. + fcalls : int + Number of calls to loglike. + gcalls : int + Number of calls to gradient/score. + warnflag : int + 1: Maximum number of iterations exceeded. 2: Gradient + and/or function calls are not changing. + converged : bool + True: converged. False: did not converge. + allvecs : list + Results at each iteration. + 'lbfgs' + fopt : float + Value of the (negative) loglikelihood at its minimum. + gopt : float + Value of gradient at minimum, which should be near 0. + fcalls : int + Number of calls to loglike. + warnflag : int + Warning flag: + + - 0 if converged + - 1 if too many function evaluations or too many iterations + - 2 if stopped for another reason + + converged : bool + True: converged. False: did not converge. + 'powell' + fopt : float + Value of the (negative) loglikelihood at its minimum. + direc : ndarray + Current direction set. + iterations : int + Number of iterations performed. + fcalls : int + Number of calls to loglike. + warnflag : int + 1: Maximum number of function evaluations. 2: Maximum number + of iterations. + converged : bool + True : converged. False: did not converge. + allvecs : list + Results at each iteration. + 'cg' + fopt : float + Value of the (negative) loglikelihood at its minimum. + fcalls : int + Number of calls to loglike. + gcalls : int + Number of calls to gradient/score. + warnflag : int + 1: Maximum number of iterations exceeded. 2: Gradient and/ + or function calls not changing. + converged : bool + True: converged. False: did not converge. + allvecs : list + Results at each iteration. + 'ncg' + fopt : float + Value of the (negative) loglikelihood at its minimum. + fcalls : int + Number of calls to loglike. + gcalls : int + Number of calls to gradient/score. + hcalls : int + Number of calls to hessian. + warnflag : int + 1: Maximum number of iterations exceeded. + converged : bool + True: converged. False: did not converge. + allvecs : list + Results at each iteration. + """ + + # by default we use normal distribution + # can be overwritten by instances or subclasses + + def __init__(self, model, params, normalized_cov_params=None, scale=1., + **kwargs): + super().__init__(model, params) + self.normalized_cov_params = normalized_cov_params + self.scale = scale + self._use_t = False + # robust covariance + # We put cov_type in kwargs so subclasses can decide in fit whether to + # use this generic implementation + if 'use_t' in kwargs: + use_t = kwargs['use_t'] + self.use_t = use_t if use_t is not None else False + if 'cov_type' in kwargs: + cov_type = kwargs.get('cov_type', 'nonrobust') + cov_kwds = kwargs.get('cov_kwds', {}) + + if cov_type == 'nonrobust': + self.cov_type = 'nonrobust' + self.cov_kwds = {'description': 'Standard Errors assume that the ' + + 'covariance matrix of the errors is correctly ' + + 'specified.'} + else: + from statsmodels.base.covtype import get_robustcov_results + if cov_kwds is None: + cov_kwds = {} + use_t = self.use_t + # TODO: we should not need use_t in get_robustcov_results + get_robustcov_results(self, cov_type=cov_type, use_self=True, + use_t=use_t, **cov_kwds) + + def normalized_cov_params(self): + """See specific model class docstring""" + raise NotImplementedError + + def _get_robustcov_results(self, cov_type='nonrobust', use_self=True, + use_t=None, **cov_kwds): + if use_self is False: + raise ValueError("use_self should have been removed long ago. " + "See GH#4401") + from statsmodels.base.covtype import get_robustcov_results + if cov_kwds is None: + cov_kwds = {} + + if cov_type == 'nonrobust': + self.cov_type = 'nonrobust' + self.cov_kwds = {'description': 'Standard Errors assume that the ' + + 'covariance matrix of the errors is correctly ' + + 'specified.'} + else: + # TODO: we should not need use_t in get_robustcov_results + get_robustcov_results(self, cov_type=cov_type, use_self=True, + use_t=use_t, **cov_kwds) + @property + def use_t(self): + """Flag indicating to use the Student's distribution in inference.""" + return self._use_t + + @use_t.setter + def use_t(self, value): + self._use_t = bool(value) + + @cached_value + def llf(self): + """Log-likelihood of model""" + return self.model.loglike(self.params) + + @cached_value + def bse(self): + """The standard errors of the parameter estimates.""" + # Issue 3299 + if ((not hasattr(self, 'cov_params_default')) and + (self.normalized_cov_params is None)): + bse_ = np.empty(len(self.params)) + bse_[:] = np.nan + else: + with warnings.catch_warnings(): + warnings.simplefilter("ignore", RuntimeWarning) + bse_ = np.sqrt(np.diag(self.cov_params())) + return bse_ + + @cached_value + def tvalues(self): + """ + Return the t-statistic for a given parameter estimate. + """ + with warnings.catch_warnings(): + warnings.simplefilter("ignore", RuntimeWarning) + return self.params / self.bse + + @cached_value + def pvalues(self): + """The two-tailed p values for the t-stats of the params.""" + with warnings.catch_warnings(): + warnings.simplefilter("ignore", RuntimeWarning) + if self.use_t: + df_resid = getattr(self, 'df_resid_inference', self.df_resid) + return stats.t.sf(np.abs(self.tvalues), df_resid) * 2 + else: + return stats.norm.sf(np.abs(self.tvalues)) * 2 + + def cov_params(self, r_matrix=None, column=None, scale=None, cov_p=None, + other=None): + """ + Compute the variance/covariance matrix. + + The variance/covariance matrix can be of a linear contrast of the + estimated parameters or all params multiplied by scale which will + usually be an estimate of sigma^2. Scale is assumed to be a scalar. + + Parameters + ---------- + r_matrix : array_like + Can be 1d, or 2d. Can be used alone or with other. + column : array_like, optional + Must be used on its own. Can be 0d or 1d see below. + scale : float, optional + Can be specified or not. Default is None, which means that + the scale argument is taken from the model. + cov_p : ndarray, optional + The covariance of the parameters. If not provided, this value is + read from `self.normalized_cov_params` or + `self.cov_params_default`. + other : array_like, optional + Can be used when r_matrix is specified. + + Returns + ------- + ndarray + The covariance matrix of the parameter estimates or of linear + combination of parameter estimates. See Notes. + + Notes + ----- + (The below are assumed to be in matrix notation.) + + If no argument is specified returns the covariance matrix of a model + ``(scale)*(X.T X)^(-1)`` + + If contrast is specified it pre and post-multiplies as follows + ``(scale) * r_matrix (X.T X)^(-1) r_matrix.T`` + + If contrast and other are specified returns + ``(scale) * r_matrix (X.T X)^(-1) other.T`` + + If column is specified returns + ``(scale) * (X.T X)^(-1)[column,column]`` if column is 0d + + OR + + ``(scale) * (X.T X)^(-1)[column][:,column]`` if column is 1d + """ + if (hasattr(self, 'mle_settings') and + self.mle_settings['optimizer'] in ['l1', 'l1_cvxopt_cp']): + dot_fun = nan_dot + else: + dot_fun = np.dot + + if (cov_p is None and self.normalized_cov_params is None and + not hasattr(self, 'cov_params_default')): + raise ValueError('need covariance of parameters for computing ' + '(unnormalized) covariances') + if column is not None and (r_matrix is not None or other is not None): + raise ValueError('Column should be specified without other ' + 'arguments.') + if other is not None and r_matrix is None: + raise ValueError('other can only be specified with r_matrix') + + if cov_p is None: + if hasattr(self, 'cov_params_default'): + cov_p = self.cov_params_default + else: + if scale is None: + scale = self.scale + cov_p = self.normalized_cov_params * scale + + if column is not None: + column = np.asarray(column) + if column.shape == (): + return cov_p[column, column] + else: + return cov_p[column[:, None], column] + elif r_matrix is not None: + r_matrix = np.asarray(r_matrix) + if r_matrix.shape == (): + raise ValueError("r_matrix should be 1d or 2d") + if other is None: + other = r_matrix + else: + other = np.asarray(other) + tmp = dot_fun(r_matrix, dot_fun(cov_p, np.transpose(other))) + return tmp + else: # if r_matrix is None and column is None: + return cov_p + + # TODO: make sure this works as needed for GLMs + def t_test(self, r_matrix, cov_p=None, use_t=None): + """ + Compute a t-test for a each linear hypothesis of the form Rb = q. + + Parameters + ---------- + r_matrix : {array_like, str, tuple} + One of: + + - array : If an array is given, a p x k 2d array or length k 1d + array specifying the linear restrictions. It is assumed + that the linear combination is equal to zero. + - str : The full hypotheses to test can be given as a string. + See the examples. + - tuple : A tuple of arrays in the form (R, q). If q is given, + can be either a scalar or a length p row vector. + + cov_p : array_like, optional + An alternative estimate for the parameter covariance matrix. + If None is given, self.normalized_cov_params is used. + use_t : bool, optional + If use_t is None, then the default of the model is used. If use_t + is True, then the p-values are based on the t distribution. If + use_t is False, then the p-values are based on the normal + distribution. + + Returns + ------- + ContrastResults + The results for the test are attributes of this results instance. + The available results have the same elements as the parameter table + in `summary()`. + + See Also + -------- + tvalues : Individual t statistics for the estimated parameters. + f_test : Perform an F tests on model parameters. + patsy.DesignInfo.linear_constraint : Specify a linear constraint. + + Examples + -------- + >>> import numpy as np + >>> import statsmodels.api as sm + >>> data = sm.datasets.longley.load() + >>> data.exog = sm.add_constant(data.exog) + >>> results = sm.OLS(data.endog, data.exog).fit() + >>> r = np.zeros_like(results.params) + >>> r[5:] = [1,-1] + >>> print(r) + [ 0. 0. 0. 0. 0. 1. -1.] + + r tests that the coefficients on the 5th and 6th independent + variable are the same. + + >>> T_test = results.t_test(r) + >>> print(T_test) + Test for Constraints + ============================================================================== + coef std err t P>|t| [0.025 0.975] + ------------------------------------------------------------------------------ + c0 -1829.2026 455.391 -4.017 0.003 -2859.368 -799.037 + ============================================================================== + >>> T_test.effect + -1829.2025687192481 + >>> T_test.sd + 455.39079425193762 + >>> T_test.tvalue + -4.0167754636411717 + >>> T_test.pvalue + 0.0015163772380899498 + + Alternatively, you can specify the hypothesis tests using a string + + >>> from statsmodels.formula.api import ols + >>> dta = sm.datasets.longley.load_pandas().data + >>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR' + >>> results = ols(formula, dta).fit() + >>> hypotheses = 'GNPDEFL = GNP, UNEMP = 2, YEAR/1829 = 1' + >>> t_test = results.t_test(hypotheses) + >>> print(t_test) + Test for Constraints + ============================================================================== + coef std err t P>|t| [0.025 0.975] + ------------------------------------------------------------------------------ + c0 15.0977 84.937 0.178 0.863 -177.042 207.238 + c1 -2.0202 0.488 -8.231 0.000 -3.125 -0.915 + c2 1.0001 0.249 0.000 1.000 0.437 1.563 + ============================================================================== + """ + from patsy import DesignInfo + use_t = bool_like(use_t, "use_t", strict=True, optional=True) + if self.params.ndim == 2: + names = [f'y{i[0]}_{i[1]}' + for i in self.model.data.cov_names] + else: + names = self.model.data.cov_names + LC = DesignInfo(names).linear_constraint(r_matrix) + r_matrix, q_matrix = LC.coefs, LC.constants + num_ttests = r_matrix.shape[0] + num_params = r_matrix.shape[1] + + if (cov_p is None and self.normalized_cov_params is None and + not hasattr(self, 'cov_params_default')): + raise ValueError('Need covariance of parameters for computing ' + 'T statistics') + params = self.params.ravel(order="F") + if num_params != params.shape[0]: + raise ValueError('r_matrix and params are not aligned') + if q_matrix is None: + q_matrix = np.zeros(num_ttests) + else: + q_matrix = np.asarray(q_matrix) + q_matrix = q_matrix.squeeze() + if q_matrix.size > 1: + if q_matrix.shape[0] != num_ttests: + raise ValueError("r_matrix and q_matrix must have the same " + "number of rows") + + if use_t is None: + # switch to use_t false if undefined + use_t = (hasattr(self, 'use_t') and self.use_t) + + _effect = np.dot(r_matrix, params) + + # Perform the test + if num_ttests > 1: + _sd = np.sqrt(np.diag(self.cov_params( + r_matrix=r_matrix, cov_p=cov_p))) + else: + _sd = np.sqrt(self.cov_params(r_matrix=r_matrix, cov_p=cov_p)) + _t = (_effect - q_matrix) * recipr(_sd) + + df_resid = getattr(self, 'df_resid_inference', self.df_resid) + + if use_t: + return ContrastResults(effect=_effect, t=_t, sd=_sd, + df_denom=df_resid) + else: + return ContrastResults(effect=_effect, statistic=_t, sd=_sd, + df_denom=df_resid, + distribution='norm') + + def f_test(self, r_matrix, cov_p=None, invcov=None): + """ + Compute the F-test for a joint linear hypothesis. + + This is a special case of `wald_test` that always uses the F + distribution. + + Parameters + ---------- + r_matrix : {array_like, str, tuple} + One of: + + - array : An r x k array where r is the number of restrictions to + test and k is the number of regressors. It is assumed + that the linear combination is equal to zero. + - str : The full hypotheses to test can be given as a string. + See the examples. + - tuple : A tuple of arrays in the form (R, q), ``q`` can be + either a scalar or a length k row vector. + + cov_p : array_like, optional + An alternative estimate for the parameter covariance matrix. + If None is given, self.normalized_cov_params is used. + invcov : array_like, optional + A q x q array to specify an inverse covariance matrix based on a + restrictions matrix. + + Returns + ------- + ContrastResults + The results for the test are attributes of this results instance. + + See Also + -------- + t_test : Perform a single hypothesis test. + wald_test : Perform a Wald-test using a quadratic form. + statsmodels.stats.contrast.ContrastResults : Test results. + patsy.DesignInfo.linear_constraint : Specify a linear constraint. + + Notes + ----- + The matrix `r_matrix` is assumed to be non-singular. More precisely, + + r_matrix (pX pX.T) r_matrix.T + + is assumed invertible. Here, pX is the generalized inverse of the + design matrix of the model. There can be problems in non-OLS models + where the rank of the covariance of the noise is not full. + + Examples + -------- + >>> import numpy as np + >>> import statsmodels.api as sm + >>> data = sm.datasets.longley.load() + >>> data.exog = sm.add_constant(data.exog) + >>> results = sm.OLS(data.endog, data.exog).fit() + >>> A = np.identity(len(results.params)) + >>> A = A[1:,:] + + This tests that each coefficient is jointly statistically + significantly different from zero. + + >>> print(results.f_test(A)) + + + Compare this to + + >>> results.fvalue + 330.2853392346658 + >>> results.f_pvalue + 4.98403096572e-10 + + >>> B = np.array(([0,0,1,-1,0,0,0],[0,0,0,0,0,1,-1])) + + This tests that the coefficient on the 2nd and 3rd regressors are + equal and jointly that the coefficient on the 5th and 6th regressors + are equal. + + >>> print(results.f_test(B)) + + + Alternatively, you can specify the hypothesis tests using a string + + >>> from statsmodels.datasets import longley + >>> from statsmodels.formula.api import ols + >>> dta = longley.load_pandas().data + >>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR' + >>> results = ols(formula, dta).fit() + >>> hypotheses = '(GNPDEFL = GNP), (UNEMP = 2), (YEAR/1829 = 1)' + >>> f_test = results.f_test(hypotheses) + >>> print(f_test) + + """ + res = self.wald_test(r_matrix, cov_p=cov_p, invcov=invcov, use_f=True, scalar=True) + return res + + # TODO: untested for GLMs? + def wald_test(self, r_matrix, cov_p=None, invcov=None, + use_f=None, df_constraints=None, scalar=None): + """ + Compute a Wald-test for a joint linear hypothesis. + + Parameters + ---------- + r_matrix : {array_like, str, tuple} + One of: + + - array : An r x k array where r is the number of restrictions to + test and k is the number of regressors. It is assumed that the + linear combination is equal to zero. + - str : The full hypotheses to test can be given as a string. + See the examples. + - tuple : A tuple of arrays in the form (R, q), ``q`` can be + either a scalar or a length p row vector. + + cov_p : array_like, optional + An alternative estimate for the parameter covariance matrix. + If None is given, self.normalized_cov_params is used. + invcov : array_like, optional + A q x q array to specify an inverse covariance matrix based on a + restrictions matrix. + use_f : bool + If True, then the F-distribution is used. If False, then the + asymptotic distribution, chisquare is used. If use_f is None, then + the F distribution is used if the model specifies that use_t is True. + The test statistic is proportionally adjusted for the distribution + by the number of constraints in the hypothesis. + df_constraints : int, optional + The number of constraints. If not provided the number of + constraints is determined from r_matrix. + scalar : bool, optional + Flag indicating whether the Wald test statistic should be returned + as a sclar float. The current behavior is to return an array. + This will switch to a scalar float after 0.14 is released. To + get the future behavior now, set scalar to True. To silence + the warning and retain the legacy behavior, set scalar to + False. + + Returns + ------- + ContrastResults + The results for the test are attributes of this results instance. + + See Also + -------- + f_test : Perform an F tests on model parameters. + t_test : Perform a single hypothesis test. + statsmodels.stats.contrast.ContrastResults : Test results. + patsy.DesignInfo.linear_constraint : Specify a linear constraint. + + Notes + ----- + The matrix `r_matrix` is assumed to be non-singular. More precisely, + + r_matrix (pX pX.T) r_matrix.T + + is assumed invertible. Here, pX is the generalized inverse of the + design matrix of the model. There can be problems in non-OLS models + where the rank of the covariance of the noise is not full. + """ + use_f = bool_like(use_f, "use_f", strict=True, optional=True) + scalar = bool_like(scalar, "scalar", strict=True, optional=True) + if use_f is None: + # switch to use_t false if undefined + use_f = (hasattr(self, 'use_t') and self.use_t) + + from patsy import DesignInfo + if self.params.ndim == 2: + names = [f'y{i[0]}_{i[1]}' + for i in self.model.data.cov_names] + else: + names = self.model.data.cov_names + params = self.params.ravel(order="F") + LC = DesignInfo(names).linear_constraint(r_matrix) + r_matrix, q_matrix = LC.coefs, LC.constants + + if (self.normalized_cov_params is None and cov_p is None and + invcov is None and not hasattr(self, 'cov_params_default')): + raise ValueError('need covariance of parameters for computing ' + 'F statistics') + + cparams = np.dot(r_matrix, params[:, None]) + J = float(r_matrix.shape[0]) # number of restrictions + + if q_matrix is None: + q_matrix = np.zeros(J) + else: + q_matrix = np.asarray(q_matrix) + if q_matrix.ndim == 1: + q_matrix = q_matrix[:, None] + if q_matrix.shape[0] != J: + raise ValueError("r_matrix and q_matrix must have the same " + "number of rows") + Rbq = cparams - q_matrix + if invcov is None: + cov_p = self.cov_params(r_matrix=r_matrix, cov_p=cov_p) + if np.isnan(cov_p).max(): + raise ValueError("r_matrix performs f_test for using " + "dimensions that are asymptotically " + "non-normal") + invcov = np.linalg.pinv(cov_p) + J_ = np.linalg.matrix_rank(cov_p) + if J_ < J: + warnings.warn('covariance of constraints does not have full ' + 'rank. The number of constraints is %d, but ' + 'rank is %d' % (J, J_), ValueWarning) + J = J_ + + # TODO streamline computation, we do not need to compute J if given + if df_constraints is not None: + # let caller override J by df_constraint + J = df_constraints + + if (hasattr(self, 'mle_settings') and + self.mle_settings['optimizer'] in ['l1', 'l1_cvxopt_cp']): + F = nan_dot(nan_dot(Rbq.T, invcov), Rbq) + else: + F = np.dot(np.dot(Rbq.T, invcov), Rbq) + + df_resid = getattr(self, 'df_resid_inference', self.df_resid) + if scalar is None: + warnings.warn( + "The behavior of wald_test will change after 0.14 to returning " + "scalar test statistic values. To get the future behavior now, " + "set scalar to True. To silence this message while retaining " + "the legacy behavior, set scalar to False.", + FutureWarning + ) + scalar = False + if scalar and F.size == 1: + F = float(np.squeeze(F)) + if use_f: + F /= J + return ContrastResults(F=F, df_denom=df_resid, + df_num=J) #invcov.shape[0]) + else: + return ContrastResults(chi2=F, df_denom=J, statistic=F, + distribution='chi2', distargs=(J,)) + + def wald_test_terms(self, skip_single=False, extra_constraints=None, + combine_terms=None, scalar=None): + """ + Compute a sequence of Wald tests for terms over multiple columns. + + This computes joined Wald tests for the hypothesis that all + coefficients corresponding to a `term` are zero. + `Terms` are defined by the underlying formula or by string matching. + + Parameters + ---------- + skip_single : bool + If true, then terms that consist only of a single column and, + therefore, refers only to a single parameter is skipped. + If false, then all terms are included. + extra_constraints : ndarray + Additional constraints to test. Note that this input has not been + tested. + combine_terms : {list[str], None} + Each string in this list is matched to the name of the terms or + the name of the exogenous variables. All columns whose name + includes that string are combined in one joint test. + scalar : bool, optional + Flag indicating whether the Wald test statistic should be returned + as a sclar float. The current behavior is to return an array. + This will switch to a scalar float after 0.14 is released. To + get the future behavior now, set scalar to True. To silence + the warning and retain the legacy behavior, set scalar to + False. + + Returns + ------- + WaldTestResults + The result instance contains `table` which is a pandas DataFrame + with the test results: test statistic, degrees of freedom and + pvalues. + + Examples + -------- + >>> res_ols = ols("np.log(Days+1) ~ C(Duration, Sum)*C(Weight, Sum)", data).fit() + >>> res_ols.wald_test_terms() + + F P>F df constraint df denom + Intercept 279.754525 2.37985521351e-22 1 51 + C(Duration, Sum) 5.367071 0.0245738436636 1 51 + C(Weight, Sum) 12.432445 3.99943118767e-05 2 51 + C(Duration, Sum):C(Weight, Sum) 0.176002 0.83912310946 2 51 + + >>> res_poi = Poisson.from_formula("Days ~ C(Weight) * C(Duration)", \ + data).fit(cov_type='HC0') + >>> wt = res_poi.wald_test_terms(skip_single=False, \ + combine_terms=['Duration', 'Weight']) + >>> print(wt) + chi2 P>chi2 df constraint + Intercept 15.695625 7.43960374424e-05 1 + C(Weight) 16.132616 0.000313940174705 2 + C(Duration) 1.009147 0.315107378931 1 + C(Weight):C(Duration) 0.216694 0.897315972824 2 + Duration 11.187849 0.010752286833 3 + Weight 30.263368 4.32586407145e-06 4 + """ + # lazy import + from collections import defaultdict + + result = self + if extra_constraints is None: + extra_constraints = [] + if combine_terms is None: + combine_terms = [] + design_info = getattr(result.model.data, 'design_info', None) + + if design_info is None and extra_constraints is None: + raise ValueError('no constraints, nothing to do') + + identity = np.eye(len(result.params)) + constraints = [] + combined = defaultdict(list) + if design_info is not None: + for term in design_info.terms: + cols = design_info.slice(term) + name = term.name() + constraint_matrix = identity[cols] + + # check if in combined + for cname in combine_terms: + if cname in name: + combined[cname].append(constraint_matrix) + + k_constraint = constraint_matrix.shape[0] + if skip_single: + if k_constraint == 1: + continue + + constraints.append((name, constraint_matrix)) + + combined_constraints = [] + for cname in combine_terms: + combined_constraints.append((cname, np.vstack(combined[cname]))) + else: + # check by exog/params names if there is no formula info + for col, name in enumerate(result.model.exog_names): + constraint_matrix = np.atleast_2d(identity[col]) + + # check if in combined + for cname in combine_terms: + if cname in name: + combined[cname].append(constraint_matrix) + + if skip_single: + continue + + constraints.append((name, constraint_matrix)) + + combined_constraints = [] + for cname in combine_terms: + combined_constraints.append((cname, np.vstack(combined[cname]))) + + use_t = result.use_t + distribution = ['chi2', 'F'][use_t] + + res_wald = [] + index = [] + for name, constraint in constraints + combined_constraints + extra_constraints: + wt = result.wald_test(constraint, scalar=scalar) + row = [wt.statistic, wt.pvalue, constraint.shape[0]] + if use_t: + row.append(wt.df_denom) + res_wald.append(row) + index.append(name) + + # distribution nerutral names + col_names = ['statistic', 'pvalue', 'df_constraint'] + if use_t: + col_names.append('df_denom') + # TODO: maybe move DataFrame creation to results class + from pandas import DataFrame + table = DataFrame(res_wald, index=index, columns=col_names) + res = WaldTestResults(None, distribution, None, table=table) + # TODO: remove temp again, added for testing + res.temp = constraints + combined_constraints + extra_constraints + return res + + def t_test_pairwise(self, term_name, method='hs', alpha=0.05, + factor_labels=None): + """ + Perform pairwise t_test with multiple testing corrected p-values. + + This uses the formula design_info encoding contrast matrix and should + work for all encodings of a main effect. + + Parameters + ---------- + term_name : str + The name of the term for which pairwise comparisons are computed. + Term names for categorical effects are created by patsy and + correspond to the main part of the exog names. + method : {str, list[str]} + The multiple testing p-value correction to apply. The default is + 'hs'. See stats.multipletesting. + alpha : float + The significance level for multiple testing reject decision. + factor_labels : {list[str], None} + Labels for the factor levels used for pairwise labels. If not + provided, then the labels from the formula design_info are used. + + Returns + ------- + MultiCompResult + The results are stored as attributes, the main attributes are the + following two. Other attributes are added for debugging purposes + or as background information. + + - result_frame : pandas DataFrame with t_test results and multiple + testing corrected p-values. + - contrasts : matrix of constraints of the null hypothesis in the + t_test. + + Notes + ----- + Status: experimental. Currently only checked for treatment coding with + and without specified reference level. + + Currently there are no multiple testing corrected confidence intervals + available. + + Examples + -------- + >>> res = ols("np.log(Days+1) ~ C(Weight) + C(Duration)", data).fit() + >>> pw = res.t_test_pairwise("C(Weight)") + >>> pw.result_frame + coef std err t P>|t| Conf. Int. Low + 2-1 0.632315 0.230003 2.749157 8.028083e-03 0.171563 + 3-1 1.302555 0.230003 5.663201 5.331513e-07 0.841803 + 3-2 0.670240 0.230003 2.914044 5.119126e-03 0.209488 + Conf. Int. Upp. pvalue-hs reject-hs + 2-1 1.093067 0.010212 True + 3-1 1.763307 0.000002 True + 3-2 1.130992 0.010212 True + """ + res = t_test_pairwise(self, term_name, method=method, alpha=alpha, + factor_labels=factor_labels) + return res + + def _get_wald_nonlinear(self, func, deriv=None): + """Experimental method for nonlinear prediction and tests + + Parameters + ---------- + func : callable, f(params) + nonlinear function of the estimation parameters. The return of + the function can be vector valued, i.e. a 1-D array + deriv : function or None + first derivative or Jacobian of func. If deriv is None, then a + numerical derivative will be used. If func returns a 1-D array, + then the `deriv` should have rows corresponding to the elements + of the return of func. + + Returns + ------- + nl : instance of `NonlinearDeltaCov` with attributes and methods to + calculate the results for the prediction or tests + + """ + from statsmodels.stats._delta_method import NonlinearDeltaCov + func_args = None # TODO: not yet implemented, maybe skip - use partial + nl = NonlinearDeltaCov(func, self.params, self.cov_params(), + deriv=deriv, func_args=func_args) + + return nl + + def conf_int(self, alpha=.05, cols=None): + """ + Construct confidence interval for the fitted parameters. + + Parameters + ---------- + alpha : float, optional + The significance level for the confidence interval. The default + `alpha` = .05 returns a 95% confidence interval. + cols : array_like, optional + Specifies which confidence intervals to return. + + .. deprecated: 0.13 + + cols is deprecated and will be removed after 0.14 is released. + cols only works when inputs are NumPy arrays and will fail + when using pandas Series or DataFrames as input. You can + subset the confidence intervals using slices. + + Returns + ------- + array_like + Each row contains [lower, upper] limits of the confidence interval + for the corresponding parameter. The first column contains all + lower, the second column contains all upper limits. + + Notes + ----- + The confidence interval is based on the standard normal distribution + if self.use_t is False. If self.use_t is True, then uses a Student's t + with self.df_resid_inference (or self.df_resid if df_resid_inference is + not defined) degrees of freedom. + + Examples + -------- + >>> import statsmodels.api as sm + >>> data = sm.datasets.longley.load() + >>> data.exog = sm.add_constant(data.exog) + >>> results = sm.OLS(data.endog, data.exog).fit() + >>> results.conf_int() + array([[-5496529.48322745, -1467987.78596704], + [ -177.02903529, 207.15277984], + [ -0.1115811 , 0.03994274], + [ -3.12506664, -0.91539297], + [ -1.5179487 , -0.54850503], + [ -0.56251721, 0.460309 ], + [ 798.7875153 , 2859.51541392]]) + + >>> results.conf_int(cols=(2,3)) + array([[-0.1115811 , 0.03994274], + [-3.12506664, -0.91539297]]) + """ + bse = self.bse + + if self.use_t: + dist = stats.t + df_resid = getattr(self, 'df_resid_inference', self.df_resid) + q = dist.ppf(1 - alpha / 2, df_resid) + else: + dist = stats.norm + q = dist.ppf(1 - alpha / 2) + + params = self.params + lower = params - q * bse + upper = params + q * bse + if cols is not None: + warnings.warn( + "cols is deprecated and will be removed after 0.14 is " + "released. cols only works when inputs are NumPy arrays and " + "will fail when using pandas Series or DataFrames as input. " + "Subsets of confidence intervals can be selected using slices " + "of the full confidence interval array.", + FutureWarning + ) + cols = np.asarray(cols) + lower = lower[cols] + upper = upper[cols] + return np.asarray(lzip(lower, upper)) + + def save(self, fname, remove_data=False): + """ + Save a pickle of this instance. + + Parameters + ---------- + fname : {str, handle} + A string filename or a file handle. + remove_data : bool + If False (default), then the instance is pickled without changes. + If True, then all arrays with length nobs are set to None before + pickling. See the remove_data method. + In some cases not all arrays will be set to None. + + Notes + ----- + If remove_data is true and the model result does not implement a + remove_data method then this will raise an exception. + """ + + from statsmodels.iolib.smpickle import save_pickle + + if remove_data: + self.remove_data() + + save_pickle(self, fname) + + @classmethod + def load(cls, fname): + """ + Load a pickled results instance + + .. warning:: + + Loading pickled models is not secure against erroneous or + maliciously constructed data. Never unpickle data received from + an untrusted or unauthenticated source. + + Parameters + ---------- + fname : {str, handle, pathlib.Path} + A string filename or a file handle. + + Returns + ------- + Results + The unpickled results instance. + """ + + from statsmodels.iolib.smpickle import load_pickle + return load_pickle(fname) + + def remove_data(self): + """ + Remove data arrays, all nobs arrays from result and model. + + This reduces the size of the instance, so it can be pickled with less + memory. Currently tested for use with predict from an unpickled + results and model instance. + + .. warning:: + + Since data and some intermediate results have been removed + calculating new statistics that require them will raise exceptions. + The exception will occur the first time an attribute is accessed + that has been set to None. + + Not fully tested for time series models, tsa, and might delete too much + for prediction or not all that would be possible. + + The lists of arrays to delete are maintained as attributes of + the result and model instance, except for cached values. These + lists could be changed before calling remove_data. + + The attributes to remove are named in: + + model._data_attr : arrays attached to both the model instance + and the results instance with the same attribute name. + + result._data_in_cache : arrays that may exist as values in + result._cache + + result._data_attr_model : arrays attached to the model + instance but not to the results instance + """ + cls = self.__class__ + # Note: we cannot just use `getattr(cls, x)` or `getattr(self, x)` + # because of redirection involved with property-like accessors + cls_attrs = {} + for name in dir(cls): + try: + attr = object.__getattribute__(cls, name) + except AttributeError: + pass + else: + cls_attrs[name] = attr + data_attrs = [x for x in cls_attrs + if isinstance(cls_attrs[x], cached_data)] + for name in data_attrs: + self._cache[name] = None + + def wipe(obj, att): + # get to last element in attribute path + p = att.split('.') + att_ = p.pop(-1) + try: + obj_ = reduce(getattr, [obj] + p) + if hasattr(obj_, att_): + setattr(obj_, att_, None) + except AttributeError: + pass + + model_only = ['model.' + i for i in getattr(self, "_data_attr_model", [])] + model_attr = ['model.' + i for i in self.model._data_attr] + for att in self._data_attr + model_attr + model_only: + if att in data_attrs: + # these have been handled above, and trying to call wipe + # would raise an Exception anyway, so skip these + continue + wipe(self, att) + + for key in self._data_in_cache: + try: + self._cache[key] = None + except (AttributeError, KeyError): + pass + + +class LikelihoodResultsWrapper(wrap.ResultsWrapper): + _attrs = { + 'params': 'columns', + 'bse': 'columns', + 'pvalues': 'columns', + 'tvalues': 'columns', + 'resid': 'rows', + 'fittedvalues': 'rows', + 'normalized_cov_params': 'cov', + } + + _wrap_attrs = _attrs + _wrap_methods = { + 'cov_params': 'cov', + 'conf_int': 'columns' + } + +wrap.populate_wrapper(LikelihoodResultsWrapper, # noqa:E305 + LikelihoodModelResults) + + +class ResultMixin: + + @cache_readonly + def df_modelwc(self): + """Model WC""" + # collect different ways of defining the number of parameters, used for + # aic, bic + k_extra = getattr(self.model, "k_extra", 0) + if hasattr(self, 'df_model'): + if hasattr(self, 'k_constant'): + hasconst = self.k_constant + elif hasattr(self, 'hasconst'): + hasconst = self.hasconst + else: + # default assumption + hasconst = 1 + return self.df_model + hasconst + k_extra + else: + return self.params.size + + @cache_readonly + def aic(self): + """Akaike information criterion""" + return -2 * self.llf + 2 * (self.df_modelwc) + + @cache_readonly + def bic(self): + """Bayesian information criterion""" + return -2 * self.llf + np.log(self.nobs) * (self.df_modelwc) + + @cache_readonly + def score_obsv(self): + """cached Jacobian of log-likelihood + """ + return self.model.score_obs(self.params) + + @cache_readonly + def hessv(self): + """cached Hessian of log-likelihood + """ + return self.model.hessian(self.params) + + @cache_readonly + def covjac(self): + """ + covariance of parameters based on outer product of jacobian of + log-likelihood + """ + # if not hasattr(self, '_results'): + # raise ValueError('need to call fit first') + # #self.fit() + # self.jacv = jacv = self.jac(self._results.params) + jacv = self.score_obsv + return np.linalg.inv(np.dot(jacv.T, jacv)) + + @cache_readonly + def covjhj(self): + """covariance of parameters based on HJJH + + dot product of Hessian, Jacobian, Jacobian, Hessian of likelihood + + name should be covhjh + """ + jacv = self.score_obsv + hessv = self.hessv + hessinv = np.linalg.inv(hessv) + # self.hessinv = hessin = self.cov_params() + return np.dot(hessinv, np.dot(np.dot(jacv.T, jacv), hessinv)) + + @cache_readonly + def bsejhj(self): + """standard deviation of parameter estimates based on covHJH + """ + return np.sqrt(np.diag(self.covjhj)) + + @cache_readonly + def bsejac(self): + """standard deviation of parameter estimates based on covjac + """ + return np.sqrt(np.diag(self.covjac)) + + def bootstrap(self, nrep=100, method='nm', disp=0, store=1): + """simple bootstrap to get mean and variance of estimator + + see notes + + Parameters + ---------- + nrep : int + number of bootstrap replications + method : str + optimization method to use + disp : bool + If true, then optimization prints results + store : bool + If true, then parameter estimates for all bootstrap iterations + are attached in self.bootstrap_results + + Returns + ------- + mean : ndarray + mean of parameter estimates over bootstrap replications + std : ndarray + standard deviation of parameter estimates over bootstrap + replications + + Notes + ----- + This was mainly written to compare estimators of the standard errors of + the parameter estimates. It uses independent random sampling from the + original endog and exog, and therefore is only correct if observations + are independently distributed. + + This will be moved to apply only to models with independently + distributed observations. + """ + results = [] + hascloneattr = True if hasattr(self.model, 'cloneattr') else False + for i in range(nrep): + rvsind = np.random.randint(self.nobs, size=self.nobs) + # this needs to set startparam and get other defining attributes + # need a clone method on model + if self.exog is not None: + exog_resamp = self.exog[rvsind, :] + else: + exog_resamp = None + # build auxiliary model and fit + init_kwds = self.model._get_init_kwds() + fitmod = self.model.__class__(self.endog[rvsind], + exog=exog_resamp, **init_kwds) + if hascloneattr: + for attr in self.model.cloneattr: + setattr(fitmod, attr, getattr(self.model, attr)) + + fitres = fitmod.fit(method=method, disp=disp) + results.append(fitres.params) + results = np.array(results) + if store: + self.bootstrap_results = results + return results.mean(0), results.std(0), results + + def get_nlfun(self, fun): + """ + get_nlfun + + This is not Implemented + """ + # I think this is supposed to get the delta method that is currently + # in miscmodels count (as part of Poisson example) + raise NotImplementedError + + +class _LLRMixin(): + """Mixin class for Null model and likelihood ratio + """ + # methods copied from DiscreteResults, adjusted pseudo R2 + + def pseudo_rsquared(self, kind="mcf"): + """ + McFadden's pseudo-R-squared. `1 - (llf / llnull)` + """ + kind = kind.lower() + if kind.startswith("mcf"): + prsq = 1 - self.llf / self.llnull + elif kind.startswith("cox") or kind in ["cs", "lr"]: + prsq = 1 - np.exp((self.llnull - self.llf) * (2 / self.nobs)) + else: + raise ValueError("only McFadden and Cox-Snell are available") + return prsq + + @cache_readonly + def llr(self): + """ + Likelihood ratio chi-squared statistic; `-2*(llnull - llf)` + """ + return -2*(self.llnull - self.llf) + + @cache_readonly + def llr_pvalue(self): + """ + The chi-squared probability of getting a log-likelihood ratio + statistic greater than llr. llr has a chi-squared distribution + with degrees of freedom `df_model`. + """ + # see also RegressionModel compare_lr_test + llr = self.llr + df_full = self.df_resid + df_restr = self.df_resid_null + lrdf = (df_restr - df_full) + self.df_lr_null = lrdf + return stats.distributions.chi2.sf(llr, lrdf) + + def set_null_options(self, llnull=None, attach_results=True, **kwargs): + """ + Set the fit options for the Null (constant-only) model. + + This resets the cache for related attributes which is potentially + fragile. This only sets the option, the null model is estimated + when llnull is accessed, if llnull is not yet in cache. + + Parameters + ---------- + llnull : {None, float} + If llnull is not None, then the value will be directly assigned to + the cached attribute "llnull". + attach_results : bool + Sets an internal flag whether the results instance of the null + model should be attached. By default without calling this method, + thenull model results are not attached and only the loglikelihood + value llnull is stored. + **kwargs + Additional keyword arguments used as fit keyword arguments for the + null model. The override and model default values. + + Notes + ----- + Modifies attributes of this instance, and so has no return. + """ + # reset cache, note we need to add here anything that depends on + # llnullor the null model. If something is missing, then the attribute + # might be incorrect. + self._cache.pop('llnull', None) + self._cache.pop('llr', None) + self._cache.pop('llr_pvalue', None) + self._cache.pop('prsquared', None) + if hasattr(self, 'res_null'): + del self.res_null + + if llnull is not None: + self._cache['llnull'] = llnull + self._attach_nullmodel = attach_results + self._optim_kwds_null = kwargs + + @cache_readonly + def llnull(self): + """ + Value of the constant-only loglikelihood + """ + model = self.model + kwds = model._get_init_kwds().copy() + for key in getattr(model, '_null_drop_keys', []): + del kwds[key] + # TODO: what parameters to pass to fit? + mod_null = model.__class__(model.endog, np.ones(self.nobs), **kwds) + # TODO: consider catching and warning on convergence failure? + # in the meantime, try hard to converge. see + # TestPoissonConstrained1a.test_smoke + + optim_kwds = getattr(self, '_optim_kwds_null', {}).copy() + + if 'start_params' in optim_kwds: + # user provided + sp_null = optim_kwds.pop('start_params') + elif hasattr(model, '_get_start_params_null'): + # get moment estimates if available + sp_null = model._get_start_params_null() + else: + sp_null = None + + opt_kwds = dict(method='bfgs', warn_convergence=False, maxiter=10000, + disp=0) + opt_kwds.update(optim_kwds) + + if optim_kwds: + res_null = mod_null.fit(start_params=sp_null, **opt_kwds) + else: + # this should be a reasonably method case across versions + res_null = mod_null.fit(start_params=sp_null, method='nm', + warn_convergence=False, + maxiter=10000, disp=0) + res_null = mod_null.fit(start_params=res_null.params, method='bfgs', + warn_convergence=False, + maxiter=10000, disp=0) + + if getattr(self, '_attach_nullmodel', False) is not False: + self.res_null = res_null + + self.k_null = len(res_null.params) + self.df_resid_null = res_null.df_resid + return res_null.llf + + +class GenericLikelihoodModelResults(LikelihoodModelResults, ResultMixin): + """ + A results class for the discrete dependent variable models. + + ..Warning : + + The following description has not been updated to this version/class. + Where are AIC, BIC, ....? docstring looks like copy from discretemod + + Parameters + ---------- + model : A DiscreteModel instance + mlefit : instance of LikelihoodResults + This contains the numerical optimization results as returned by + LikelihoodModel.fit(), in a superclass of GnericLikelihoodModels + + + Attributes + ---------- + aic : float + Akaike information criterion. -2*(`llf` - p) where p is the number + of regressors including the intercept. + bic : float + Bayesian information criterion. -2*`llf` + ln(`nobs`)*p where p is the + number of regressors including the intercept. + bse : ndarray + The standard errors of the coefficients. + df_resid : float + See model definition. + df_model : float + See model definition. + fitted_values : ndarray + Linear predictor XB. + llf : float + Value of the loglikelihood + llnull : float + Value of the constant-only loglikelihood + llr : float + Likelihood ratio chi-squared statistic; -2*(`llnull` - `llf`) + llr_pvalue : float + The chi-squared probability of getting a log-likelihood ratio + statistic greater than llr. llr has a chi-squared distribution + with degrees of freedom `df_model`. + prsquared : float + McFadden's pseudo-R-squared. 1 - (`llf`/`llnull`) + """ + + def __init__(self, model, mlefit): + self.model = model + self.endog = model.endog + self.exog = model.exog + self.nobs = model.endog.shape[0] + + # TODO: possibly move to model.fit() + # and outsource together with patching names + k_extra = getattr(self.model, "k_extra", 0) + if hasattr(model, 'df_model') and not np.isnan(model.df_model): + self.df_model = model.df_model + else: + df_model = len(mlefit.params) - self.model.k_constant - k_extra + self.df_model = df_model + # retrofitting the model, used in t_test TODO: check design + self.model.df_model = df_model + + if hasattr(model, 'df_resid') and not np.isnan(model.df_resid): + self.df_resid = model.df_resid + else: + self.df_resid = self.endog.shape[0] - self.df_model - k_extra + # retrofitting the model, used in t_test TODO: check design + self.model.df_resid = self.df_resid + + self._cache = {} + self.__dict__.update(mlefit.__dict__) + + k_params = len(mlefit.params) + # checks mainly for adding new models or subclassing + + if self.df_model + self.model.k_constant + k_extra != k_params: + warnings.warn("df_model + k_constant + k_extra " + "differs from k_params", UserWarning) + + if self.df_resid != self.nobs - k_params: + warnings.warn("df_resid differs from nobs - k_params") + + def get_prediction( + self, + exog=None, + which="mean", + transform=True, + row_labels=None, + average=False, + agg_weights=None, + **kwargs + ): + """ + Compute prediction results when endpoint transformation is valid. + + Parameters + ---------- + exog : array_like, optional + The values for which you want to predict. + transform : bool, optional + If the model was fit via a formula, do you want to pass + exog through the formula. Default is True. E.g., if you fit + a model y ~ log(x1) + log(x2), and transform is True, then + you can pass a data structure that contains x1 and x2 in + their original form. Otherwise, you'd need to log the data + first. + which : str + Which statistic is to be predicted. Default is "mean". + The available statistics and options depend on the model. + see the model.predict docstring + row_labels : list of str or None + If row_lables are provided, then they will replace the generated + labels. + average : bool + If average is True, then the mean prediction is computed, that is, + predictions are computed for individual exog and then the average + over observation is used. + If average is False, then the results are the predictions for all + observations, i.e. same length as ``exog``. + agg_weights : ndarray, optional + Aggregation weights, only used if average is True. + The weights are not normalized. + **kwargs : + Some models can take additional keyword arguments, such as offset, + exposure or additional exog in multi-part models like zero inflated + models. + See the predict method of the model for the details. + + Returns + ------- + prediction_results : PredictionResults + The prediction results instance contains prediction and prediction + variance and can on demand calculate confidence intervals and + summary dataframe for the prediction. + + Notes + ----- + Status: new in 0.14, experimental + """ + from statsmodels.base._prediction_inference import get_prediction + + pred_kwds = kwargs + + res = get_prediction( + self, + exog=exog, + which=which, + transform=transform, + row_labels=row_labels, + average=average, + agg_weights=agg_weights, + pred_kwds=pred_kwds + ) + return res + + def summary(self, yname=None, xname=None, title=None, alpha=.05): + """Summarize the Regression Results + + Parameters + ---------- + yname : str, optional + Default is `y` + xname : list[str], optional + Names for the exogenous variables, default is "var_xx". + Must match the number of parameters in the model + title : str, optional + Title for the top table. If not None, then this replaces the + default title + alpha : float + significance level for the confidence intervals + + Returns + ------- + smry : Summary instance + this holds the summary tables and text, which can be printed or + converted to various output formats. + + See Also + -------- + statsmodels.iolib.summary.Summary : class to hold summary results + """ + + top_left = [('Dep. Variable:', None), + ('Model:', None), + ('Method:', ['Maximum Likelihood']), + ('Date:', None), + ('Time:', None), + ('No. Observations:', None), + ('Df Residuals:', None), + ('Df Model:', None), + ] + + top_right = [('Log-Likelihood:', None), + ('AIC:', ["%#8.4g" % self.aic]), + ('BIC:', ["%#8.4g" % self.bic]) + ] + + if title is None: + title = self.model.__class__.__name__ + ' ' + "Results" + + # create summary table instance + from statsmodels.iolib.summary import Summary + smry = Summary() + smry.add_table_2cols(self, gleft=top_left, gright=top_right, + yname=yname, xname=xname, title=title) + smry.add_table_params(self, yname=yname, xname=xname, alpha=alpha, + use_t=self.use_t) + + return smry diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/optimizer.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..f735a5b780954848aca8bda01f3d28302033c939 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/optimizer.py @@ -0,0 +1,1077 @@ +""" +Functions that are general enough to use for any model fitting. The idea is +to untie these from LikelihoodModel so that they may be re-used generally. +""" +from __future__ import annotations + +from statsmodels.compat.scipy import SP_LT_15, SP_LT_17, SP_LT_116 + +from collections.abc import Sequence +from typing import Any + +import numpy as np +from scipy import optimize + + +def check_kwargs(kwargs: dict[str, Any], allowed: Sequence[str], method: str): + extra = set(list(kwargs.keys())).difference(list(allowed)) + if extra: + import warnings + + warnings.warn( + "Keyword arguments have been passed to the optimizer that have " + "no effect. The list of allowed keyword arguments for method " + f"{method} is: {', '.join(allowed)}. The list of unsupported " + f"keyword arguments passed include: {', '.join(extra)}. After " + "release 0.14, this will raise.", + FutureWarning + ) + + +def _check_method(method, methods): + if method not in methods: + message = "Unknown fit method %s" % method + raise ValueError(message) + + +class Optimizer: + def _fit(self, objective, gradient, start_params, fargs, kwargs, + hessian=None, method='newton', maxiter=100, full_output=True, + disp=True, callback=None, retall=False): + """ + Fit function for any model with an objective function. + + Parameters + ---------- + objective : function + Objective function to be minimized. + gradient : function + The gradient of the objective function. + start_params : array_like, optional + Initial guess of the solution for the loglikelihood maximization. + The default is an array of zeros. + fargs : tuple + Extra arguments passed to the objective function, i.e. + objective(x,*args) + kwargs : dict[str, Any] + Extra keyword arguments passed to the objective function, i.e. + objective(x,**kwargs) + hessian : str, optional + Method for computing the Hessian matrix, if applicable. + method : str {'newton','nm','bfgs','powell','cg','ncg','basinhopping', + 'minimize'} + Method can be 'newton' for Newton-Raphson, 'nm' for Nelder-Mead, + 'bfgs' for Broyden-Fletcher-Goldfarb-Shanno, 'powell' for modified + Powell's method, 'cg' for conjugate gradient, 'ncg' for Newton- + conjugate gradient, 'basinhopping' for global basin-hopping + solver, if available or a generic 'minimize' which is a wrapper for + scipy.optimize.minimize. `method` determines which solver from + scipy.optimize is used. The explicit arguments in `fit` are passed + to the solver, with the exception of the basin-hopping solver. Each + solver has several optional arguments that are not the same across + solvers. See the notes section below (or scipy.optimize) for the + available arguments and for the list of explicit arguments that the + basin-hopping solver supports.. + maxiter : int + The maximum number of iterations to perform. + full_output : bool + Set to True to have all available output in the Results object's + mle_retvals attribute. The output is dependent on the solver. + See LikelihoodModelResults notes section for more information. + disp : bool + Set to True to print convergence messages. + callback : callable callback(xk) + Called after each iteration, as callback(xk), where xk is the + current parameter vector. + retall : bool + Set to True to return list of solutions at each iteration. + Available in Results object's mle_retvals attribute. + + Returns + ------- + xopt : ndarray + The solution to the objective function + retvals : dict, None + If `full_output` is True then this is a dictionary which holds + information returned from the solver used. If it is False, this is + None. + optim_settings : dict + A dictionary that contains the parameters passed to the solver. + + Notes + ----- + The 'basinhopping' solver ignores `maxiter`, `retall`, `full_output` + explicit arguments. + + Optional arguments for the solvers (available in Results.mle_settings):: + + 'newton' + tol : float + Relative error in params acceptable for convergence. + 'nm' -- Nelder Mead + xtol : float + Relative error in params acceptable for convergence + ftol : float + Relative error in loglike(params) acceptable for + convergence + maxfun : int + Maximum number of function evaluations to make. + 'bfgs' + gtol : float + Stop when norm of gradient is less than gtol. + norm : float + Order of norm (np.inf is max, -np.inf is min) + epsilon + If fprime is approximated, use this value for the step + size. Only relevant if LikelihoodModel.score is None. + 'lbfgs' + m : int + The maximum number of variable metric corrections used to + define the limited memory matrix. (The limited memory BFGS + method does not store the full hessian but uses this many + terms in an approximation to it.) + pgtol : float + The iteration will stop when + ``max{|proj g_i | i = 1, ..., n} <= pgtol`` where pg_i is + the i-th component of the projected gradient. + factr : float + The iteration stops when + ``(f^k - f^{k+1})/max{|f^k|,|f^{k+1}|,1} <= factr * eps``, + where eps is the machine precision, which is automatically + generated by the code. Typical values for factr are: 1e12 + for low accuracy; 1e7 for moderate accuracy; 10.0 for + extremely high accuracy. See Notes for relationship to + ftol, which is exposed (instead of factr) by the + scipy.optimize.minimize interface to L-BFGS-B. + maxfun : int + Maximum number of iterations. + epsilon : float + Step size used when approx_grad is True, for numerically + calculating the gradient + approx_grad : bool + Whether to approximate the gradient numerically (in which + case func returns only the function value). + 'cg' + gtol : float + Stop when norm of gradient is less than gtol. + norm : float + Order of norm (np.inf is max, -np.inf is min) + epsilon : float + If fprime is approximated, use this value for the step + size. Can be scalar or vector. Only relevant if + Likelihoodmodel.score is None. + 'ncg' + fhess_p : callable f'(x,*args) + Function which computes the Hessian of f times an arbitrary + vector, p. Should only be supplied if + LikelihoodModel.hessian is None. + avextol : float + Stop when the average relative error in the minimizer + falls below this amount. + epsilon : float or ndarray + If fhess is approximated, use this value for the step size. + Only relevant if Likelihoodmodel.hessian is None. + 'powell' + xtol : float + Line-search error tolerance + ftol : float + Relative error in loglike(params) for acceptable for + convergence. + maxfun : int + Maximum number of function evaluations to make. + start_direc : ndarray + Initial direction set. + 'basinhopping' + niter : int + The number of basin hopping iterations. + niter_success : int + Stop the run if the global minimum candidate remains the + same for this number of iterations. + T : float + The "temperature" parameter for the accept or reject + criterion. Higher "temperatures" mean that larger jumps + in function value will be accepted. For best results + `T` should be comparable to the separation (in function + value) between local minima. + stepsize : float + Initial step size for use in the random displacement. + interval : int + The interval for how often to update the `stepsize`. + minimizer : dict + Extra keyword arguments to be passed to the minimizer + `scipy.optimize.minimize()`, for example 'method' - the + minimization method (e.g. 'L-BFGS-B'), or 'tol' - the + tolerance for termination. Other arguments are mapped from + explicit argument of `fit`: + - `args` <- `fargs` + - `jac` <- `score` + - `hess` <- `hess` + 'minimize' + min_method : str, optional + Name of minimization method to use. + Any method specific arguments can be passed directly. + For a list of methods and their arguments, see + documentation of `scipy.optimize.minimize`. + If no method is specified, then BFGS is used. + """ + # TODO: generalize the regularization stuff + # Extract kwargs specific to fit_regularized calling fit + extra_fit_funcs = kwargs.get('extra_fit_funcs', dict()) + + methods = ['newton', 'nm', 'bfgs', 'lbfgs', 'powell', 'cg', 'ncg', + 'basinhopping', 'minimize'] + methods += extra_fit_funcs.keys() + method = method.lower() + _check_method(method, methods) + + fit_funcs = { + 'newton': _fit_newton, + 'nm': _fit_nm, # Nelder-Mead + 'bfgs': _fit_bfgs, + 'lbfgs': _fit_lbfgs, + 'cg': _fit_cg, + 'ncg': _fit_ncg, + 'powell': _fit_powell, + 'basinhopping': _fit_basinhopping, + 'minimize': _fit_minimize # wrapper for scipy.optimize.minimize + } + + # NOTE: fit_regularized checks the methods for these but it should be + # moved up probably + if extra_fit_funcs: + fit_funcs.update(extra_fit_funcs) + + func = fit_funcs[method] + xopt, retvals = func(objective, gradient, start_params, fargs, kwargs, + disp=disp, maxiter=maxiter, callback=callback, + retall=retall, full_output=full_output, + hess=hessian) + + optim_settings = {'optimizer': method, 'start_params': start_params, + 'maxiter': maxiter, 'full_output': full_output, + 'disp': disp, 'fargs': fargs, 'callback': callback, + 'retall': retall, "extra_fit_funcs": extra_fit_funcs} + optim_settings.update(kwargs) + # set as attributes or return? + return xopt, retvals, optim_settings + + def _fit_constrained(self, params): + """ + TODO: how to add constraints? + + Something like + sm.add_constraint(Model, func) + + or + + model_instance.add_constraint(func) + model_instance.add_constraint("x1 + x2 = 2") + result = model_instance.fit() + """ + raise NotImplementedError + + def _fit_regularized(self, params): + # TODO: code will not necessarily be general here. 3 options. + # 1) setup for scipy.optimize.fmin_sqlsqp + # 2) setup for cvxopt + # 3) setup for openopt + raise NotImplementedError + + +######################################## +# Helper functions to fit + + +def _fit_minimize(f, score, start_params, fargs, kwargs, disp=True, + maxiter=100, callback=None, retall=False, + full_output=True, hess=None): + """ + Fit using scipy minimize, where kwarg `min_method` defines the algorithm. + + Parameters + ---------- + f : function + Returns negative log likelihood given parameters. + score : function + Returns gradient of negative log likelihood with respect to params. + start_params : array_like, optional + Initial guess of the solution for the loglikelihood maximization. + The default is an array of zeros. + fargs : tuple + Extra arguments passed to the objective function, i.e. + objective(x,*args) + kwargs : dict[str, Any] + Extra keyword arguments passed to the objective function, i.e. + objective(x,**kwargs) + disp : bool + Set to True to print convergence messages. + maxiter : int + The maximum number of iterations to perform. + callback : callable callback(xk) + Called after each iteration, as callback(xk), where xk is the + current parameter vector. + retall : bool + Set to True to return list of solutions at each iteration. + Available in Results object's mle_retvals attribute. + full_output : bool + Set to True to have all available output in the Results object's + mle_retvals attribute. The output is dependent on the solver. + See LikelihoodModelResults notes section for more information. + hess : str, optional + Method for computing the Hessian matrix, if applicable. + + Returns + ------- + xopt : ndarray + The solution to the objective function + retvals : dict, None + If `full_output` is True then this is a dictionary which holds + information returned from the solver used. If it is False, this is + None. + """ + kwargs.setdefault('min_method', 'BFGS') + + # prepare options dict for minimize + filter_opts = ['extra_fit_funcs', 'niter', 'min_method', 'tol', 'bounds', 'constraints'] + options = {k: v for k, v in kwargs.items() if k not in filter_opts} + options['disp'] = disp + options['maxiter'] = maxiter + + # Use Hessian/Jacobian only if they're required by the method + no_hess = ['Nelder-Mead', 'Powell', 'CG', 'BFGS', 'COBYLA', 'SLSQP'] + no_jac = ['Nelder-Mead', 'Powell', 'COBYLA'] + if kwargs['min_method'] in no_hess: + hess = None + if kwargs['min_method'] in no_jac: + score = None + + # Use bounds/constraints only if they're allowed by the method + has_bounds = ['L-BFGS-B', 'TNC', 'SLSQP', 'trust-constr'] + # Added in SP 1.5 + if not SP_LT_15: + has_bounds += ['Powell'] + # Added in SP 1.7 + if not SP_LT_17: + has_bounds += ['Nelder-Mead'] + has_constraints = ['COBYLA', 'SLSQP', 'trust-constr'] + + if 'bounds' in kwargs.keys() and kwargs['min_method'] in has_bounds: + bounds = kwargs['bounds'] + else: + bounds = None + + if 'constraints' in kwargs.keys() and kwargs['min_method'] in has_constraints: + constraints = kwargs['constraints'] + else: + constraints = () + + res = optimize.minimize(f, start_params, args=fargs, method=kwargs['min_method'], + jac=score, hess=hess, bounds=bounds, constraints=constraints, + callback=callback, options=options) + + xopt = res.x + retvals = None + if full_output: + nit = getattr(res, 'nit', np.nan) # scipy 0.14 compat + retvals = {'fopt': res.fun, 'iterations': nit, + 'fcalls': res.nfev, 'warnflag': res.status, + 'converged': res.success} + if retall: + retvals.update({'allvecs': res.values()}) + + return xopt, retvals + + +def _fit_newton(f, score, start_params, fargs, kwargs, disp=True, + maxiter=100, callback=None, retall=False, + full_output=True, hess=None, ridge_factor=1e-10): + """ + Fit using Newton-Raphson algorithm. + + Parameters + ---------- + f : function + Returns negative log likelihood given parameters. + score : function + Returns gradient of negative log likelihood with respect to params. + start_params : array_like, optional + Initial guess of the solution for the loglikelihood maximization. + The default is an array of zeros. + fargs : tuple + Extra arguments passed to the objective function, i.e. + objective(x,*args) + kwargs : dict[str, Any] + Extra keyword arguments passed to the objective function, i.e. + objective(x,**kwargs) + disp : bool + Set to True to print convergence messages. + maxiter : int + The maximum number of iterations to perform. + callback : callable callback(xk) + Called after each iteration, as callback(xk), where xk is the + current parameter vector. + retall : bool + Set to True to return list of solutions at each iteration. + Available in Results object's mle_retvals attribute. + full_output : bool + Set to True to have all available output in the Results object's + mle_retvals attribute. The output is dependent on the solver. + See LikelihoodModelResults notes section for more information. + hess : str, optional + Method for computing the Hessian matrix, if applicable. + ridge_factor : float + Regularization factor for Hessian matrix. + + Returns + ------- + xopt : ndarray + The solution to the objective function + retvals : dict, None + If `full_output` is True then this is a dictionary which holds + information returned from the solver used. If it is False, this is + None. + """ + check_kwargs(kwargs, ("tol", "ridge_factor"), "newton") + tol = kwargs.setdefault('tol', 1e-8) + ridge_factor = kwargs.setdefault('ridge_factor', 1e-10) + iterations = 0 + oldparams = np.inf + newparams = np.asarray(start_params) + if retall: + history = [oldparams, newparams] + while (iterations < maxiter and np.any(np.abs(newparams - + oldparams) > tol)): + H = np.asarray(hess(newparams)) + # regularize Hessian, not clear what ridge factor should be + # keyword option with absolute default 1e-10, see #1847 + if not np.all(ridge_factor == 0): + H[np.diag_indices(H.shape[0])] += ridge_factor + oldparams = newparams + newparams = oldparams - np.linalg.solve(H, score(oldparams)) + if retall: + history.append(newparams) + if callback is not None: + callback(newparams) + iterations += 1 + fval = f(newparams, *fargs) # this is the negative likelihood + if iterations == maxiter: + warnflag = 1 + if disp: + print("Warning: Maximum number of iterations has been " + "exceeded.") + print(" Current function value: %f" % fval) + print(" Iterations: %d" % iterations) + else: + warnflag = 0 + if disp: + print("Optimization terminated successfully.") + print(" Current function value: %f" % fval) + print(" Iterations %d" % iterations) + if full_output: + (xopt, fopt, niter, + gopt, hopt) = (newparams, f(newparams, *fargs), + iterations, score(newparams), + hess(newparams)) + converged = not warnflag + retvals = {'fopt': fopt, 'iterations': niter, 'score': gopt, + 'Hessian': hopt, 'warnflag': warnflag, + 'converged': converged} + if retall: + retvals.update({'allvecs': history}) + + else: + xopt = newparams + retvals = None + + return xopt, retvals + + +def _fit_bfgs(f, score, start_params, fargs, kwargs, disp=True, + maxiter=100, callback=None, retall=False, + full_output=True, hess=None): + """ + Fit using Broyden-Fletcher-Goldfarb-Shannon algorithm. + + Parameters + ---------- + f : function + Returns negative log likelihood given parameters. + score : function + Returns gradient of negative log likelihood with respect to params. + start_params : array_like, optional + Initial guess of the solution for the loglikelihood maximization. + The default is an array of zeros. + fargs : tuple + Extra arguments passed to the objective function, i.e. + objective(x,*args) + kwargs : dict[str, Any] + Extra keyword arguments passed to the objective function, i.e. + objective(x,**kwargs) + disp : bool + Set to True to print convergence messages. + maxiter : int + The maximum number of iterations to perform. + callback : callable callback(xk) + Called after each iteration, as callback(xk), where xk is the + current parameter vector. + retall : bool + Set to True to return list of solutions at each iteration. + Available in Results object's mle_retvals attribute. + full_output : bool + Set to True to have all available output in the Results object's + mle_retvals attribute. The output is dependent on the solver. + See LikelihoodModelResults notes section for more information. + hess : str, optional + Method for computing the Hessian matrix, if applicable. + + Returns + ------- + xopt : ndarray + The solution to the objective function + retvals : dict, None + If `full_output` is True then this is a dictionary which holds + information returned from the solver used. If it is False, this is + None. + """ + check_kwargs(kwargs, ("gtol", "norm", "epsilon"), "bfgs") + gtol = kwargs.setdefault('gtol', 1.0000000000000001e-05) + norm = kwargs.setdefault('norm', np.inf) + epsilon = kwargs.setdefault('epsilon', 1.4901161193847656e-08) + retvals = optimize.fmin_bfgs(f, start_params, score, args=fargs, + gtol=gtol, norm=norm, epsilon=epsilon, + maxiter=maxiter, full_output=full_output, + disp=disp, retall=retall, callback=callback) + if full_output: + if not retall: + xopt, fopt, gopt, Hinv, fcalls, gcalls, warnflag = retvals + else: + (xopt, fopt, gopt, Hinv, fcalls, + gcalls, warnflag, allvecs) = retvals + converged = not warnflag + retvals = {'fopt': fopt, 'gopt': gopt, 'Hinv': Hinv, + 'fcalls': fcalls, 'gcalls': gcalls, 'warnflag': + warnflag, 'converged': converged} + if retall: + retvals.update({'allvecs': allvecs}) + else: + xopt = retvals + retvals = None + + return xopt, retvals + + +def _fit_lbfgs(f, score, start_params, fargs, kwargs, disp=True, maxiter=100, + callback=None, retall=False, full_output=True, hess=None): + """ + Fit using Limited-memory Broyden-Fletcher-Goldfarb-Shannon algorithm. + + Parameters + ---------- + f : function + Returns negative log likelihood given parameters. + score : function + Returns gradient of negative log likelihood with respect to params. + start_params : array_like, optional + Initial guess of the solution for the loglikelihood maximization. + The default is an array of zeros. + fargs : tuple + Extra arguments passed to the objective function, i.e. + objective(x,*args) + kwargs : dict[str, Any] + Extra keyword arguments passed to the objective function, i.e. + objective(x,**kwargs) + disp : bool + Set to True to print convergence messages. + maxiter : int + The maximum number of iterations to perform. + callback : callable callback(xk) + Called after each iteration, as callback(xk), where xk is the + current parameter vector. + retall : bool + Set to True to return list of solutions at each iteration. + Available in Results object's mle_retvals attribute. + full_output : bool + Set to True to have all available output in the Results object's + mle_retvals attribute. The output is dependent on the solver. + See LikelihoodModelResults notes section for more information. + hess : str, optional + Method for computing the Hessian matrix, if applicable. + + Returns + ------- + xopt : ndarray + The solution to the objective function + retvals : dict, None + If `full_output` is True then this is a dictionary which holds + information returned from the solver used. If it is False, this is + None. + + Notes + ----- + Within the mle part of statsmodels, the log likelihood function and + its gradient with respect to the parameters do not have notationally + consistent sign. + """ + check_kwargs( + kwargs, + ("m", "pgtol", "factr", "maxfun", "epsilon", "approx_grad", "bounds", "loglike_and_score", "iprint"), + "lbfgs" + ) + # Use unconstrained optimization by default. + bounds = kwargs.setdefault('bounds', [(None, None)] * len(start_params)) + kwargs.setdefault('iprint', 0) + + # Pass the following keyword argument names through to fmin_l_bfgs_b + # if they are present in kwargs, otherwise use the fmin_l_bfgs_b + # default values. + names = ('m', 'pgtol', 'factr', 'maxfun', 'epsilon', 'approx_grad') + extra_kwargs = {x: kwargs[x] for x in names if x in kwargs} + + # Extract values for the options related to the gradient. + approx_grad = kwargs.get('approx_grad', False) + loglike_and_score = kwargs.get('loglike_and_score', None) + epsilon = kwargs.get('epsilon', None) + + # The approx_grad flag has superpowers nullifying the score function arg. + if approx_grad: + score = None + + # Choose among three options for dealing with the gradient (the gradient + # of a log likelihood function with respect to its parameters + # is more specifically called the score in statistics terminology). + # The first option is to use the finite-differences + # approximation that is built into the fmin_l_bfgs_b optimizer. + # The second option is to use the provided score function. + # The third option is to use the score component of a provided + # function that simultaneously evaluates the log likelihood and score. + if epsilon and not approx_grad: + raise ValueError('a finite-differences epsilon was provided ' + 'even though we are not using approx_grad') + if approx_grad and loglike_and_score: + raise ValueError('gradient approximation was requested ' + 'even though an analytic loglike_and_score function ' + 'was given') + if loglike_and_score: + func = lambda p, *a: tuple(-x for x in loglike_and_score(p, *a)) + elif score: + func = f + extra_kwargs['fprime'] = score + elif approx_grad: + func = f + + extended_kwargs = extra_kwargs.copy() + if SP_LT_116: + extended_kwargs["disp"]=disp + retvals = optimize.fmin_l_bfgs_b( + func, + start_params, + maxiter=maxiter, + callback=callback, + args=fargs, + bounds=bounds, + **extended_kwargs + ) + + + if full_output: + xopt, fopt, d = retvals + # The warnflag is + # 0 if converged + # 1 if too many function evaluations or too many iterations + # 2 if stopped for another reason, given in d['task'] + warnflag = d['warnflag'] + converged = (warnflag == 0) + gopt = d['grad'] + fcalls = d['funcalls'] + iterations = d['nit'] + retvals = {'fopt': fopt, 'gopt': gopt, 'fcalls': fcalls, + 'warnflag': warnflag, 'converged': converged, + 'iterations': iterations} + else: + xopt = retvals[0] + retvals = None + + return xopt, retvals + + +def _fit_nm(f, score, start_params, fargs, kwargs, disp=True, + maxiter=100, callback=None, retall=False, + full_output=True, hess=None): + """ + Fit using Nelder-Mead algorithm. + + Parameters + ---------- + f : function + Returns negative log likelihood given parameters. + score : function + Returns gradient of negative log likelihood with respect to params. + start_params : array_like, optional + Initial guess of the solution for the loglikelihood maximization. + The default is an array of zeros. + fargs : tuple + Extra arguments passed to the objective function, i.e. + objective(x,*args) + kwargs : dict[str, Any] + Extra keyword arguments passed to the objective function, i.e. + objective(x,**kwargs) + disp : bool + Set to True to print convergence messages. + maxiter : int + The maximum number of iterations to perform. + callback : callable callback(xk) + Called after each iteration, as callback(xk), where xk is the + current parameter vector. + retall : bool + Set to True to return list of solutions at each iteration. + Available in Results object's mle_retvals attribute. + full_output : bool + Set to True to have all available output in the Results object's + mle_retvals attribute. The output is dependent on the solver. + See LikelihoodModelResults notes section for more information. + hess : str, optional + Method for computing the Hessian matrix, if applicable. + + Returns + ------- + xopt : ndarray + The solution to the objective function + retvals : dict, None + If `full_output` is True then this is a dictionary which holds + information returned from the solver used. If it is False, this is + None. + """ + check_kwargs(kwargs, ("xtol", "ftol", "maxfun"), "nm") + xtol = kwargs.setdefault('xtol', 0.0001) + ftol = kwargs.setdefault('ftol', 0.0001) + maxfun = kwargs.setdefault('maxfun', None) + retvals = optimize.fmin(f, start_params, args=fargs, xtol=xtol, + ftol=ftol, maxiter=maxiter, maxfun=maxfun, + full_output=full_output, disp=disp, retall=retall, + callback=callback) + if full_output: + if not retall: + xopt, fopt, niter, fcalls, warnflag = retvals + else: + xopt, fopt, niter, fcalls, warnflag, allvecs = retvals + converged = not warnflag + retvals = {'fopt': fopt, 'iterations': niter, + 'fcalls': fcalls, 'warnflag': warnflag, + 'converged': converged} + if retall: + retvals.update({'allvecs': allvecs}) + else: + xopt = retvals + retvals = None + + return xopt, retvals + + +def _fit_cg(f, score, start_params, fargs, kwargs, disp=True, + maxiter=100, callback=None, retall=False, + full_output=True, hess=None): + """ + Fit using Conjugate Gradient algorithm. + + Parameters + ---------- + f : function + Returns negative log likelihood given parameters. + score : function + Returns gradient of negative log likelihood with respect to params. + start_params : array_like, optional + Initial guess of the solution for the loglikelihood maximization. + The default is an array of zeros. + fargs : tuple + Extra arguments passed to the objective function, i.e. + objective(x,*args) + kwargs : dict[str, Any] + Extra keyword arguments passed to the objective function, i.e. + objective(x,**kwargs) + disp : bool + Set to True to print convergence messages. + maxiter : int + The maximum number of iterations to perform. + callback : callable callback(xk) + Called after each iteration, as callback(xk), where xk is the + current parameter vector. + retall : bool + Set to True to return list of solutions at each iteration. + Available in Results object's mle_retvals attribute. + full_output : bool + Set to True to have all available output in the Results object's + mle_retvals attribute. The output is dependent on the solver. + See LikelihoodModelResults notes section for more information. + hess : str, optional + Method for computing the Hessian matrix, if applicable. + + Returns + ------- + xopt : ndarray + The solution to the objective function + retvals : dict, None + If `full_output` is True then this is a dictionary which holds + information returned from the solver used. If it is False, this is + None. + """ + check_kwargs(kwargs, ("gtol", "norm", "epsilon"), "cg") + gtol = kwargs.setdefault('gtol', 1.0000000000000001e-05) + norm = kwargs.setdefault('norm', np.inf) + epsilon = kwargs.setdefault('epsilon', 1.4901161193847656e-08) + retvals = optimize.fmin_cg(f, start_params, score, gtol=gtol, norm=norm, + epsilon=epsilon, maxiter=maxiter, + full_output=full_output, disp=disp, + retall=retall, callback=callback) + if full_output: + if not retall: + xopt, fopt, fcalls, gcalls, warnflag = retvals + else: + xopt, fopt, fcalls, gcalls, warnflag, allvecs = retvals + converged = not warnflag + retvals = {'fopt': fopt, 'fcalls': fcalls, 'gcalls': gcalls, + 'warnflag': warnflag, 'converged': converged} + if retall: + retvals.update({'allvecs': allvecs}) + + else: + xopt = retvals + retvals = None + + return xopt, retvals + + +def _fit_ncg(f, score, start_params, fargs, kwargs, disp=True, + maxiter=100, callback=None, retall=False, + full_output=True, hess=None): + """ + Fit using Newton Conjugate Gradient algorithm. + + Parameters + ---------- + f : function + Returns negative log likelihood given parameters. + score : function + Returns gradient of negative log likelihood with respect to params. + start_params : array_like, optional + Initial guess of the solution for the loglikelihood maximization. + The default is an array of zeros. + fargs : tuple + Extra arguments passed to the objective function, i.e. + objective(x,*args) + kwargs : dict[str, Any] + Extra keyword arguments passed to the objective function, i.e. + objective(x,**kwargs) + disp : bool + Set to True to print convergence messages. + maxiter : int + The maximum number of iterations to perform. + callback : callable callback(xk) + Called after each iteration, as callback(xk), where xk is the + current parameter vector. + retall : bool + Set to True to return list of solutions at each iteration. + Available in Results object's mle_retvals attribute. + full_output : bool + Set to True to have all available output in the Results object's + mle_retvals attribute. The output is dependent on the solver. + See LikelihoodModelResults notes section for more information. + hess : str, optional + Method for computing the Hessian matrix, if applicable. + + Returns + ------- + xopt : ndarray + The solution to the objective function + retvals : dict, None + If `full_output` is True then this is a dictionary which holds + information returned from the solver used. If it is False, this is + None. + """ + check_kwargs(kwargs, ("fhess_p", "avextol", "epsilon"), "ncg") + fhess_p = kwargs.setdefault('fhess_p', None) + avextol = kwargs.setdefault('avextol', 1.0000000000000001e-05) + epsilon = kwargs.setdefault('epsilon', 1.4901161193847656e-08) + retvals = optimize.fmin_ncg(f, start_params, score, fhess_p=fhess_p, + fhess=hess, args=fargs, avextol=avextol, + epsilon=epsilon, maxiter=maxiter, + full_output=full_output, disp=disp, + retall=retall, callback=callback) + if full_output: + if not retall: + xopt, fopt, fcalls, gcalls, hcalls, warnflag = retvals + else: + xopt, fopt, fcalls, gcalls, hcalls, warnflag, allvecs = \ + retvals + converged = not warnflag + retvals = {'fopt': fopt, 'fcalls': fcalls, 'gcalls': gcalls, + 'hcalls': hcalls, 'warnflag': warnflag, + 'converged': converged} + if retall: + retvals.update({'allvecs': allvecs}) + else: + xopt = retvals + retvals = None + + return xopt, retvals + + +def _fit_powell(f, score, start_params, fargs, kwargs, disp=True, + maxiter=100, callback=None, retall=False, + full_output=True, hess=None): + """ + Fit using Powell's conjugate direction algorithm. + + Parameters + ---------- + f : function + Returns negative log likelihood given parameters. + score : function + Returns gradient of negative log likelihood with respect to params. + start_params : array_like, optional + Initial guess of the solution for the loglikelihood maximization. + The default is an array of zeros. + fargs : tuple + Extra arguments passed to the objective function, i.e. + objective(x,*args) + kwargs : dict[str, Any] + Extra keyword arguments passed to the objective function, i.e. + objective(x,**kwargs) + disp : bool + Set to True to print convergence messages. + maxiter : int + The maximum number of iterations to perform. + callback : callable callback(xk) + Called after each iteration, as callback(xk), where xk is the + current parameter vector. + retall : bool + Set to True to return list of solutions at each iteration. + Available in Results object's mle_retvals attribute. + full_output : bool + Set to True to have all available output in the Results object's + mle_retvals attribute. The output is dependent on the solver. + See LikelihoodModelResults notes section for more information. + hess : str, optional + Method for computing the Hessian matrix, if applicable. + + Returns + ------- + xopt : ndarray + The solution to the objective function + retvals : dict, None + If `full_output` is True then this is a dictionary which holds + information returned from the solver used. If it is False, this is + None. + """ + check_kwargs(kwargs, ("xtol", "ftol", "maxfun", "start_direc"), "powell") + xtol = kwargs.setdefault('xtol', 0.0001) + ftol = kwargs.setdefault('ftol', 0.0001) + maxfun = kwargs.setdefault('maxfun', None) + start_direc = kwargs.setdefault('start_direc', None) + retvals = optimize.fmin_powell(f, start_params, args=fargs, xtol=xtol, + ftol=ftol, maxiter=maxiter, maxfun=maxfun, + full_output=full_output, disp=disp, + retall=retall, callback=callback, + direc=start_direc) + if full_output: + if not retall: + xopt, fopt, direc, niter, fcalls, warnflag = retvals + else: + xopt, fopt, direc, niter, fcalls, warnflag, allvecs = \ + retvals + converged = not warnflag + retvals = {'fopt': fopt, 'direc': direc, 'iterations': niter, + 'fcalls': fcalls, 'warnflag': warnflag, + 'converged': converged} + if retall: + retvals.update({'allvecs': allvecs}) + else: + xopt = retvals + retvals = None + + return xopt, retvals + + +def _fit_basinhopping(f, score, start_params, fargs, kwargs, disp=True, + maxiter=100, callback=None, retall=False, + full_output=True, hess=None): + """ + Fit using Basin-hopping algorithm. + + Parameters + ---------- + f : function + Returns negative log likelihood given parameters. + score : function + Returns gradient of negative log likelihood with respect to params. + start_params : array_like, optional + Initial guess of the solution for the loglikelihood maximization. + The default is an array of zeros. + fargs : tuple + Extra arguments passed to the objective function, i.e. + objective(x,*args) + kwargs : dict[str, Any] + Extra keyword arguments passed to the objective function, i.e. + objective(x,**kwargs) + disp : bool + Set to True to print convergence messages. + maxiter : int + The maximum number of iterations to perform. + callback : callable callback(xk) + Called after each iteration, as callback(xk), where xk is the + current parameter vector. + retall : bool + Set to True to return list of solutions at each iteration. + Available in Results object's mle_retvals attribute. + full_output : bool + Set to True to have all available output in the Results object's + mle_retvals attribute. The output is dependent on the solver. + See LikelihoodModelResults notes section for more information. + hess : str, optional + Method for computing the Hessian matrix, if applicable. + + Returns + ------- + xopt : ndarray + The solution to the objective function + retvals : dict, None + If `full_output` is True then this is a dictionary which holds + information returned from the solver used. If it is False, this is + None. + """ + check_kwargs( + kwargs, + ("niter", "niter_success", "T", "stepsize", "interval", "minimizer", "seed"), + "basinhopping" + ) + kwargs = {k: v for k, v in kwargs.items()} + niter = kwargs.setdefault('niter', 100) + niter_success = kwargs.setdefault('niter_success', None) + T = kwargs.setdefault('T', 1.0) + stepsize = kwargs.setdefault('stepsize', 0.5) + interval = kwargs.setdefault('interval', 50) + seed = kwargs.get("seed") + minimizer_kwargs = kwargs.get('minimizer', {}) + minimizer_kwargs['args'] = fargs + minimizer_kwargs['jac'] = score + method = minimizer_kwargs.get('method', None) + if method and method != 'L-BFGS-B': # l_bfgs_b does not take a hessian + minimizer_kwargs['hess'] = hess + + retvals = optimize.basinhopping(f, start_params, + minimizer_kwargs=minimizer_kwargs, + niter=niter, niter_success=niter_success, + T=T, stepsize=stepsize, disp=disp, + callback=callback, interval=interval, + seed=seed) + xopt = retvals.x + if full_output: + retvals = { + 'fopt': retvals.fun, + 'iterations': retvals.nit, + 'fcalls': retvals.nfev, + 'converged': 'completed successfully' in retvals.message[0] + } + else: + retvals = None + + return xopt, retvals diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/transform.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/transform.py new file mode 100644 index 0000000000000000000000000000000000000000..b96192921fa7740fd64e9fc97b11d20cc7cc492c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/transform.py @@ -0,0 +1,226 @@ +import numpy as np +from statsmodels.robust import mad +from scipy.optimize import minimize_scalar + + +class BoxCox: + """ + Mixin class to allow for a Box-Cox transformation. + """ + + def transform_boxcox(self, x, lmbda=None, method='guerrero', **kwargs): + """ + Performs a Box-Cox transformation on the data array x. If lmbda is None, + the indicated method is used to estimate a suitable lambda parameter. + + Parameters + ---------- + x : array_like + lmbda : float + The lambda parameter for the Box-Cox transform. If None, a value + will be estimated by means of the specified method. + method : {'guerrero', 'loglik'} + The method to estimate the lambda parameter. Will only be used if + lmbda is None, and defaults to 'guerrero', detailed in Guerrero + (1993). 'loglik' maximizes the profile likelihood. + **kwargs + Options for the specified method. + * For 'guerrero', this entails window_length, the grouping + parameter, scale, the dispersion measure, and options, to be + passed to the optimizer. + * For 'loglik': options, to be passed to the optimizer. + + Returns + ------- + y : array_like + The transformed series. + lmbda : float + The lmbda parameter used to transform the series. + + References + ---------- + Guerrero, Victor M. 1993. "Time-series analysis supported by power + transformations". `Journal of Forecasting`. 12 (1): 37-48. + + Guerrero, Victor M. and Perera, Rafael. 2004. "Variance Stabilizing + Power Transformation for Time Series," `Journal of Modern Applied + Statistical Methods`. 3 (2): 357-369. + + Box, G. E. P., and D. R. Cox. 1964. "An Analysis of Transformations". + `Journal of the Royal Statistical Society`. 26 (2): 211-252. + """ + x = np.asarray(x) + + if np.any(x <= 0): + raise ValueError("Non-positive x.") + + if lmbda is None: + lmbda = self._est_lambda(x, + method=method, + **kwargs) + + # if less than 0.01, treat lambda as zero. + if np.isclose(lmbda, 0.): + y = np.log(x) + else: + y = (np.power(x, lmbda) - 1.) / lmbda + + return y, lmbda + + def untransform_boxcox(self, x, lmbda, method='naive'): + """ + Back-transforms the Box-Cox transformed data array, by means of the + indicated method. The provided argument lmbda should be the lambda + parameter that was used to initially transform the data. + + Parameters + ---------- + x : array_like + The transformed series. + lmbda : float + The lambda parameter that was used to transform the series. + method : {'naive'} + Indicates the method to be used in the untransformation. Defaults + to 'naive', which reverses the transformation. + + NOTE: 'naive' is implemented natively, while other methods may be + available in subclasses! + + Returns + ------- + y : array_like + The untransformed series. + """ + method = method.lower() + x = np.asarray(x) + + if method == 'naive': + if np.isclose(lmbda, 0.): + y = np.exp(x) + else: + y = np.power(lmbda * x + 1, 1. / lmbda) + else: + raise ValueError(f"Method '{method}' not understood.") + + return y + + def _est_lambda(self, x, bounds=(-1, 2), method='guerrero', **kwargs): + """ + Computes an estimate for the lambda parameter in the Box-Cox + transformation using method. + + Parameters + ---------- + x : array_like + The untransformed data. + bounds : tuple + Numeric 2-tuple, that indicate the solution space for the lambda + parameter. Default (-1, 2). + method : {'guerrero', 'loglik'} + The method by which to estimate lambda. Defaults to 'guerrero', but + the profile likelihood ('loglik') is also available. + **kwargs + Options for the specified method. + * For 'guerrero': window_length (int), the seasonality/grouping + parameter. Scale ({'mad', 'sd'}), the dispersion measure. Options + (dict), to be passed to the optimizer. + * For 'loglik': Options (dict), to be passed to the optimizer. + + Returns + ------- + lmbda : float + The lambda parameter. + """ + method = method.lower() + + if len(bounds) != 2: + raise ValueError("Bounds of length {} not understood." + .format(len(bounds))) + elif bounds[0] >= bounds[1]: + raise ValueError("Lower bound exceeds upper bound.") + + if method == 'guerrero': + lmbda = self._guerrero_cv(x, bounds=bounds, **kwargs) + elif method == 'loglik': + lmbda = self._loglik_boxcox(x, bounds=bounds, **kwargs) + else: + raise ValueError(f"Method '{method}' not understood.") + + return lmbda + + def _guerrero_cv(self, x, bounds, window_length=4, scale='sd', + options={'maxiter': 25}): + """ + Computes lambda using guerrero's coefficient of variation. If no + seasonality is present in the data, window_length is set to 4 (as + per Guerrero and Perera, (2004)). + + NOTE: Seasonality-specific auxiliaries *should* provide their own + seasonality parameter. + + Parameters + ---------- + x : array_like + bounds : tuple + Numeric 2-tuple, that indicate the solution space for the lambda + parameter. + window_length : int + Seasonality/grouping parameter. Default 4, as per Guerrero and + Perera (2004). NOTE: this indicates the length of the individual + groups, not the total number of groups! + scale : {'sd', 'mad'} + The dispersion measure to be used. 'sd' indicates the sample + standard deviation, but the more robust 'mad' is also available. + options : dict + The options (as a dict) to be passed to the optimizer. + """ + nobs = len(x) + groups = int(nobs / window_length) + + # remove the first n < window_length observations from consideration. + grouped_data = np.reshape(x[nobs - (groups * window_length): nobs], + (groups, window_length)) + mean = np.mean(grouped_data, 1) + + scale = scale.lower() + if scale == 'sd': + dispersion = np.std(grouped_data, 1, ddof=1) + elif scale == 'mad': + dispersion = mad(grouped_data, axis=1) + else: + raise ValueError(f"Scale '{scale}' not understood.") + + def optim(lmbda): + rat = np.divide(dispersion, np.power(mean, 1 - lmbda)) # eq 6, p 40 + return np.std(rat, ddof=1) / np.mean(rat) + + res = minimize_scalar(optim, + bounds=bounds, + method='bounded', + options=options) + return res.x + + def _loglik_boxcox(self, x, bounds, options={'maxiter': 25}): + """ + Taken from the Stata manual on Box-Cox regressions, where this is the + special case of 'lhs only'. As an estimator for the variance, the + sample variance is used, by means of the well-known formula. + + Parameters + ---------- + x : array_like + options : dict + The options (as a dict) to be passed to the optimizer. + """ + sum_x = np.sum(np.log(x)) + nobs = len(x) + + def optim(lmbda): + y, lmbda = self.transform_boxcox(x, lmbda) + return (1 - lmbda) * sum_x + (nobs / 2.) * np.log(np.var(y)) + + res = minimize_scalar(optim, + bounds=bounds, + method='bounded', + options=options) + return res.x diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/wrapper.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..2fa0c707677bab4c436688b2d85f65b25e9fc1e6 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/base/wrapper.py @@ -0,0 +1,132 @@ +import functools +import inspect +from textwrap import dedent + + +class ResultsWrapper: + """ + Class which wraps a statsmodels estimation Results class and steps in to + reattach metadata to results (if available) + """ + _wrap_attrs = {} + _wrap_methods = {} + + def __init__(self, results): + self._results = results + self.__doc__ = results.__doc__ + + def __dir__(self): + return [x for x in dir(self._results)] + + def __getattribute__(self, attr): + get = lambda name: object.__getattribute__(self, name) + + try: + results = get('_results') + except AttributeError: + pass + + try: + return get(attr) + except AttributeError: + pass + + obj = getattr(results, attr) + data = results.model.data + how = self._wrap_attrs.get(attr) + if how and isinstance(how, tuple): + obj = data.wrap_output(obj, how[0], *how[1:]) + elif how: + obj = data.wrap_output(obj, how=how) + + return obj + + def __getstate__(self): + # print 'pickling wrapper', self.__dict__ + return self.__dict__ + + def __setstate__(self, dict_): + # print 'unpickling wrapper', dict_ + self.__dict__.update(dict_) + + def save(self, fname, remove_data=False): + """ + Save a pickle of this instance. + + Parameters + ---------- + fname : {str, handle} + Either a filename or a valid file handle. + remove_data : bool + If False (default), then the instance is pickled without changes. + If True, then all arrays with length nobs are set to None before + pickling. See the remove_data method. + In some cases not all arrays will be set to None. + """ + from statsmodels.iolib.smpickle import save_pickle + + if remove_data: + self.remove_data() + + save_pickle(self, fname) + + @classmethod + def load(cls, fname): + """ + Load a pickled results instance + + .. warning:: + + Loading pickled models is not secure against erroneous or + maliciously constructed data. Never unpickle data received from + an untrusted or unauthenticated source. + + Parameters + ---------- + fname : {str, handle} + A string filename or a file handle. + + Returns + ------- + Results + The unpickled results instance. + """ + from statsmodels.iolib.smpickle import load_pickle + return load_pickle(fname) + + +def union_dicts(*dicts): + result = {} + for d in dicts: + result.update(d) + return result + + +def make_wrapper(func, how): + @functools.wraps(func) + def wrapper(self, *args, **kwargs): + results = object.__getattribute__(self, '_results') + data = results.model.data + if how and isinstance(how, tuple): + obj = data.wrap_output(func(results, *args, **kwargs), how[0], how[1:]) + elif how: + obj = data.wrap_output(func(results, *args, **kwargs), how) + return obj + + sig = inspect.signature(func) + formatted = str(sig) + + doc = dedent(wrapper.__doc__) if wrapper.__doc__ else '' + wrapper.__doc__ = f"\n{func.__name__}{formatted}\n{doc}" + + return wrapper + + +def populate_wrapper(klass, wrapping): + for meth, how in klass._wrap_methods.items(): + if not hasattr(wrapping, meth): + continue + + func = getattr(wrapping, meth) + wrapper = make_wrapper(func, how) + setattr(klass, meth, wrapper) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/compat/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/compat/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..83cda0ee87dfcd65ae357704e34a825b9ef4fb92 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/compat/__init__.py @@ -0,0 +1,24 @@ +from statsmodels.tools._test_runner import PytestTester + +from .python import ( + asunicode, + asbytes, + asstr, + lrange, + lzip, + lmap, + lfilter, +) + +__all__ = [ + "asunicode", + "asbytes", + "asstr", + "lrange", + "lzip", + "lmap", + "lfilter", + "test", +] + +test = PytestTester() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/compat/_scipy_multivariate_t.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/compat/_scipy_multivariate_t.py new file mode 100644 index 0000000000000000000000000000000000000000..a9488499f621ddc6040dd6008de0b05b5df94682 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/compat/_scipy_multivariate_t.py @@ -0,0 +1,1193 @@ +# flake8: noqa: E501 +# +# Author: Joris Vankerschaver 2013 +# + +import numpy as np +import scipy.linalg +from scipy._lib import doccer +from scipy.special import gammaln + +from scipy._lib._util import check_random_state + +from scipy.stats import mvn + +_LOG_2PI = np.log(2 * np.pi) +_LOG_2 = np.log(2) +_LOG_PI = np.log(np.pi) + + +_doc_random_state = """\ +random_state : {None, int, np.random.RandomState, np.random.Generator}, optional + Used for drawing random variates. + If `seed` is `None` the `~np.random.RandomState` singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, seeded + with seed. + If `seed` is already a ``RandomState`` or ``Generator`` instance, + then that object is used. + Default is None. +""" + + +def _squeeze_output(out): + """ + Remove single-dimensional entries from array and convert to scalar, + if necessary. + + """ + out = out.squeeze() + if out.ndim == 0: + out = out[()] + return out + + +def _eigvalsh_to_eps(spectrum, cond=None, rcond=None): + """ + Determine which eigenvalues are "small" given the spectrum. + + This is for compatibility across various linear algebra functions + that should agree about whether or not a Hermitian matrix is numerically + singular and what is its numerical matrix rank. + This is designed to be compatible with scipy.linalg.pinvh. + + Parameters + ---------- + spectrum : 1d ndarray + Array of eigenvalues of a Hermitian matrix. + cond, rcond : float, optional + Cutoff for small eigenvalues. + Singular values smaller than rcond * largest_eigenvalue are + considered zero. + If None or -1, suitable machine precision is used. + + Returns + ------- + eps : float + Magnitude cutoff for numerical negligibility. + + """ + if rcond is not None: + cond = rcond + if cond in [None, -1]: + t = spectrum.dtype.char.lower() + factor = {'f': 1E3, 'd': 1E6} + cond = factor[t] * np.finfo(t).eps + eps = cond * np.max(abs(spectrum)) + return eps + + +def _pinv_1d(v, eps=1e-5): + """ + A helper function for computing the pseudoinverse. + + Parameters + ---------- + v : iterable of numbers + This may be thought of as a vector of eigenvalues or singular values. + eps : float + Values with magnitude no greater than eps are considered negligible. + + Returns + ------- + v_pinv : 1d float ndarray + A vector of pseudo-inverted numbers. + + """ + return np.array([0 if abs(x) <= eps else 1/x for x in v], dtype=float) + + +class _PSD: + """ + Compute coordinated functions of a symmetric positive semidefinite matrix. + + This class addresses two issues. Firstly it allows the pseudoinverse, + the logarithm of the pseudo-determinant, and the rank of the matrix + to be computed using one call to eigh instead of three. + Secondly it allows these functions to be computed in a way + that gives mutually compatible results. + All of the functions are computed with a common understanding as to + which of the eigenvalues are to be considered negligibly small. + The functions are designed to coordinate with scipy.linalg.pinvh() + but not necessarily with np.linalg.det() or with np.linalg.matrix_rank(). + + Parameters + ---------- + M : array_like + Symmetric positive semidefinite matrix (2-D). + cond, rcond : float, optional + Cutoff for small eigenvalues. + Singular values smaller than rcond * largest_eigenvalue are + considered zero. + If None or -1, suitable machine precision is used. + lower : bool, optional + Whether the pertinent array data is taken from the lower + or upper triangle of M. (Default: lower) + check_finite : bool, optional + Whether to check that the input matrices contain only finite + numbers. Disabling may give a performance gain, but may result + in problems (crashes, non-termination) if the inputs do contain + infinities or NaNs. + allow_singular : bool, optional + Whether to allow a singular matrix. (Default: True) + + Notes + ----- + The arguments are similar to those of scipy.linalg.pinvh(). + + """ + + def __init__(self, M, cond=None, rcond=None, lower=True, + check_finite=True, allow_singular=True): + # Compute the symmetric eigendecomposition. + # Note that eigh takes care of array conversion, chkfinite, + # and assertion that the matrix is square. + s, u = scipy.linalg.eigh(M, lower=lower, check_finite=check_finite) + + eps = _eigvalsh_to_eps(s, cond, rcond) + if np.min(s) < -eps: + raise ValueError('the input matrix must be positive semidefinite') + d = s[s > eps] + if len(d) < len(s) and not allow_singular: + raise np.linalg.LinAlgError('singular matrix') + s_pinv = _pinv_1d(s, eps) + U = np.multiply(u, np.sqrt(s_pinv)) + + # Initialize the eagerly precomputed attributes. + self.rank = len(d) + self.U = U + self.log_pdet = np.sum(np.log(d)) + + # Initialize an attribute to be lazily computed. + self._pinv = None + + @property + def pinv(self): + if self._pinv is None: + self._pinv = np.dot(self.U, self.U.T) + return self._pinv + + +class multi_rv_generic: + """ + Class which encapsulates common functionality between all multivariate + distributions. + + """ + def __init__(self, seed=None): + super().__init__() + self._random_state = check_random_state(seed) + + @property + def random_state(self): + """ Get or set the RandomState object for generating random variates. + + This can be either None, int, a RandomState instance, or a + np.random.Generator instance. + + If None (or np.random), use the RandomState singleton used by + np.random. + If already a RandomState or Generator instance, use it. + If an int, use a new RandomState instance seeded with seed. + + """ + return self._random_state + + @random_state.setter + def random_state(self, seed): + self._random_state = check_random_state(seed) + + def _get_random_state(self, random_state): + if random_state is not None: + return check_random_state(random_state) + else: + return self._random_state + + +class multi_rv_frozen: + """ + Class which encapsulates common functionality between all frozen + multivariate distributions. + """ + @property + def random_state(self): + return self._dist._random_state + + @random_state.setter + def random_state(self, seed): + self._dist._random_state = check_random_state(seed) + + +_mvn_doc_default_callparams = """\ +mean : array_like, optional + Mean of the distribution (default zero) +cov : array_like, optional + Covariance matrix of the distribution (default one) +allow_singular : bool, optional + Whether to allow a singular covariance matrix. (Default: False) +""" + +_mvn_doc_callparams_note = \ + """Setting the parameter `mean` to `None` is equivalent to having `mean` + be the zero-vector. The parameter `cov` can be a scalar, in which case + the covariance matrix is the identity times that value, a vector of + diagonal entries for the covariance matrix, or a two-dimensional + array_like. + """ + +_mvn_doc_frozen_callparams = "" + +_mvn_doc_frozen_callparams_note = \ + """See class definition for a detailed description of parameters.""" + +mvn_docdict_params = { + '_mvn_doc_default_callparams': _mvn_doc_default_callparams, + '_mvn_doc_callparams_note': _mvn_doc_callparams_note, + '_doc_random_state': _doc_random_state +} + +mvn_docdict_noparams = { + '_mvn_doc_default_callparams': _mvn_doc_frozen_callparams, + '_mvn_doc_callparams_note': _mvn_doc_frozen_callparams_note, + '_doc_random_state': _doc_random_state +} + + +class multivariate_normal_gen(multi_rv_generic): + r""" + A multivariate normal random variable. + + The `mean` keyword specifies the mean. The `cov` keyword specifies the + covariance matrix. + + Methods + ------- + ``pdf(x, mean=None, cov=1, allow_singular=False)`` + Probability density function. + ``logpdf(x, mean=None, cov=1, allow_singular=False)`` + Log of the probability density function. + ``cdf(x, mean=None, cov=1, allow_singular=False, maxpts=1000000*dim, abseps=1e-5, releps=1e-5)`` + Cumulative distribution function. + ``logcdf(x, mean=None, cov=1, allow_singular=False, maxpts=1000000*dim, abseps=1e-5, releps=1e-5)`` + Log of the cumulative distribution function. + ``rvs(mean=None, cov=1, size=1, random_state=None)`` + Draw random samples from a multivariate normal distribution. + ``entropy()`` + Compute the differential entropy of the multivariate normal. + + Parameters + ---------- + x : array_like + Quantiles, with the last axis of `x` denoting the components. + %(_mvn_doc_default_callparams)s + %(_doc_random_state)s + + Alternatively, the object may be called (as a function) to fix the mean + and covariance parameters, returning a "frozen" multivariate normal + random variable: + + rv = multivariate_normal(mean=None, cov=1, allow_singular=False) + - Frozen object with the same methods but holding the given + mean and covariance fixed. + + Notes + ----- + %(_mvn_doc_callparams_note)s + + The covariance matrix `cov` must be a (symmetric) positive + semi-definite matrix. The determinant and inverse of `cov` are computed + as the pseudo-determinant and pseudo-inverse, respectively, so + that `cov` does not need to have full rank. + + The probability density function for `multivariate_normal` is + + .. math:: + + f(x) = \frac{1}{\sqrt{(2 \pi)^k \det \Sigma}} + \exp\left( -\frac{1}{2} (x - \mu)^T \Sigma^{-1} (x - \mu) \right), + + where :math:`\mu` is the mean, :math:`\Sigma` the covariance matrix, + and :math:`k` is the dimension of the space where :math:`x` takes values. + + .. versionadded:: 0.14.0 + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from scipy.stats import multivariate_normal + + >>> x = np.linspace(0, 5, 10, endpoint=False) + >>> y = multivariate_normal.pdf(x, mean=2.5, cov=0.5); y + array([ 0.00108914, 0.01033349, 0.05946514, 0.20755375, 0.43939129, + 0.56418958, 0.43939129, 0.20755375, 0.05946514, 0.01033349]) + >>> fig1 = plt.figure() + >>> ax = fig1.add_subplot(111) + >>> ax.plot(x, y) + + The input quantiles can be any shape of array, as long as the last + axis labels the components. This allows us for instance to + display the frozen pdf for a non-isotropic random variable in 2D as + follows: + + >>> x, y = np.mgrid[-1:1:.01, -1:1:.01] + >>> pos = np.dstack((x, y)) + >>> rv = multivariate_normal([0.5, -0.2], [[2.0, 0.3], [0.3, 0.5]]) + >>> fig2 = plt.figure() + >>> ax2 = fig2.add_subplot(111) + >>> ax2.contourf(x, y, rv.pdf(pos)) + + """ + + def __init__(self, seed=None): + super().__init__(seed) + self.__doc__ = doccer.docformat(self.__doc__, mvn_docdict_params) + + def __call__(self, mean=None, cov=1, allow_singular=False, seed=None): + """ + Create a frozen multivariate normal distribution. + + See `multivariate_normal_frozen` for more information. + + """ + return multivariate_normal_frozen(mean, cov, + allow_singular=allow_singular, + seed=seed) + + def _process_parameters(self, dim, mean, cov): + """ + Infer dimensionality from mean or covariance matrix, ensure that + mean and covariance are full vector resp. matrix. + + """ + + # Try to infer dimensionality + if dim is None: + if mean is None: + if cov is None: + dim = 1 + else: + cov = np.asarray(cov, dtype=float) + if cov.ndim < 2: + dim = 1 + else: + dim = cov.shape[0] + else: + mean = np.asarray(mean, dtype=float) + dim = mean.size + else: + if not np.isscalar(dim): + raise ValueError("Dimension of random variable must be " + "a scalar.") + + # Check input sizes and return full arrays for mean and cov if + # necessary + if mean is None: + mean = np.zeros(dim) + mean = np.asarray(mean, dtype=float) + + if cov is None: + cov = 1.0 + cov = np.asarray(cov, dtype=float) + + if dim == 1: + mean.shape = (1,) + cov.shape = (1, 1) + + if mean.ndim != 1 or mean.shape[0] != dim: + raise ValueError("Array 'mean' must be a vector of length %d." % + dim) + if cov.ndim == 0: + cov = cov * np.eye(dim) + elif cov.ndim == 1: + cov = np.diag(cov) + elif cov.ndim == 2 and cov.shape != (dim, dim): + rows, cols = cov.shape + if rows != cols: + msg = ("Array 'cov' must be square if it is two dimensional," + " but cov.shape = %s." % str(cov.shape)) + else: + msg = ("Dimension mismatch: array 'cov' is of shape %s," + " but 'mean' is a vector of length %d.") + msg = msg % (str(cov.shape), len(mean)) + raise ValueError(msg) + elif cov.ndim > 2: + raise ValueError("Array 'cov' must be at most two-dimensional," + " but cov.ndim = %d" % cov.ndim) + + return dim, mean, cov + + def _process_quantiles(self, x, dim): + """ + Adjust quantiles array so that last axis labels the components of + each data point. + + """ + x = np.asarray(x, dtype=float) + + if x.ndim == 0: + x = x[np.newaxis] + elif x.ndim == 1: + if dim == 1: + x = x[:, np.newaxis] + else: + x = x[np.newaxis, :] + + return x + + def _logpdf(self, x, mean, prec_U, log_det_cov, rank): + """ + Parameters + ---------- + x : ndarray + Points at which to evaluate the log of the probability + density function + mean : ndarray + Mean of the distribution + prec_U : ndarray + A decomposition such that np.dot(prec_U, prec_U.T) + is the precision matrix, i.e. inverse of the covariance matrix. + log_det_cov : float + Logarithm of the determinant of the covariance matrix + rank : int + Rank of the covariance matrix. + + Notes + ----- + As this function does no argument checking, it should not be + called directly; use 'logpdf' instead. + + """ + dev = x - mean + maha = np.sum(np.square(np.dot(dev, prec_U)), axis=-1) + return -0.5 * (rank * _LOG_2PI + log_det_cov + maha) + + def logpdf(self, x, mean=None, cov=1, allow_singular=False): + """ + Log of the multivariate normal probability density function. + + Parameters + ---------- + x : array_like + Quantiles, with the last axis of `x` denoting the components. + %(_mvn_doc_default_callparams)s + + Returns + ------- + pdf : ndarray or scalar + Log of the probability density function evaluated at `x` + + Notes + ----- + %(_mvn_doc_callparams_note)s + + """ + dim, mean, cov = self._process_parameters(None, mean, cov) + x = self._process_quantiles(x, dim) + psd = _PSD(cov, allow_singular=allow_singular) + out = self._logpdf(x, mean, psd.U, psd.log_pdet, psd.rank) + return _squeeze_output(out) + + def pdf(self, x, mean=None, cov=1, allow_singular=False): + """ + Multivariate normal probability density function. + + Parameters + ---------- + x : array_like + Quantiles, with the last axis of `x` denoting the components. + %(_mvn_doc_default_callparams)s + + Returns + ------- + pdf : ndarray or scalar + Probability density function evaluated at `x` + + Notes + ----- + %(_mvn_doc_callparams_note)s + + """ + dim, mean, cov = self._process_parameters(None, mean, cov) + x = self._process_quantiles(x, dim) + psd = _PSD(cov, allow_singular=allow_singular) + out = np.exp(self._logpdf(x, mean, psd.U, psd.log_pdet, psd.rank)) + return _squeeze_output(out) + + def _cdf(self, x, mean, cov, maxpts, abseps, releps): + """ + Parameters + ---------- + x : ndarray + Points at which to evaluate the cumulative distribution function. + mean : ndarray + Mean of the distribution + cov : array_like + Covariance matrix of the distribution + maxpts: integer + The maximum number of points to use for integration + abseps: float + Absolute error tolerance + releps: float + Relative error tolerance + + Notes + ----- + As this function does no argument checking, it should not be + called directly; use 'cdf' instead. + + .. versionadded:: 1.0.0 + + """ + lower = np.full(mean.shape, -np.inf) + # mvnun expects 1-d arguments, so process points sequentially + func1d = lambda x_slice: mvn.mvnun(lower, x_slice, mean, cov, + maxpts, abseps, releps)[0] + out = np.apply_along_axis(func1d, -1, x) + return _squeeze_output(out) + + def logcdf(self, x, mean=None, cov=1, allow_singular=False, maxpts=None, + abseps=1e-5, releps=1e-5): + """ + Log of the multivariate normal cumulative distribution function. + + Parameters + ---------- + x : array_like + Quantiles, with the last axis of `x` denoting the components. + %(_mvn_doc_default_callparams)s + maxpts: integer, optional + The maximum number of points to use for integration + (default `1000000*dim`) + abseps: float, optional + Absolute error tolerance (default 1e-5) + releps: float, optional + Relative error tolerance (default 1e-5) + + Returns + ------- + cdf : ndarray or scalar + Log of the cumulative distribution function evaluated at `x` + + Notes + ----- + %(_mvn_doc_callparams_note)s + + .. versionadded:: 1.0.0 + + """ + dim, mean, cov = self._process_parameters(None, mean, cov) + x = self._process_quantiles(x, dim) + # Use _PSD to check covariance matrix + _PSD(cov, allow_singular=allow_singular) + if not maxpts: + maxpts = 1000000 * dim + out = np.log(self._cdf(x, mean, cov, maxpts, abseps, releps)) + return out + + def cdf(self, x, mean=None, cov=1, allow_singular=False, maxpts=None, + abseps=1e-5, releps=1e-5): + """ + Multivariate normal cumulative distribution function. + + Parameters + ---------- + x : array_like + Quantiles, with the last axis of `x` denoting the components. + %(_mvn_doc_default_callparams)s + maxpts: integer, optional + The maximum number of points to use for integration + (default `1000000*dim`) + abseps: float, optional + Absolute error tolerance (default 1e-5) + releps: float, optional + Relative error tolerance (default 1e-5) + + Returns + ------- + cdf : ndarray or scalar + Cumulative distribution function evaluated at `x` + + Notes + ----- + %(_mvn_doc_callparams_note)s + + .. versionadded:: 1.0.0 + + """ + dim, mean, cov = self._process_parameters(None, mean, cov) + x = self._process_quantiles(x, dim) + # Use _PSD to check covariance matrix + _PSD(cov, allow_singular=allow_singular) + if not maxpts: + maxpts = 1000000 * dim + out = self._cdf(x, mean, cov, maxpts, abseps, releps) + return out + + def rvs(self, mean=None, cov=1, size=1, random_state=None): + """ + Draw random samples from a multivariate normal distribution. + + Parameters + ---------- + %(_mvn_doc_default_callparams)s + size : integer, optional + Number of samples to draw (default 1). + %(_doc_random_state)s + + Returns + ------- + rvs : ndarray or scalar + Random variates of size (`size`, `N`), where `N` is the + dimension of the random variable. + + Notes + ----- + %(_mvn_doc_callparams_note)s + + """ + dim, mean, cov = self._process_parameters(None, mean, cov) + + random_state = self._get_random_state(random_state) + out = random_state.multivariate_normal(mean, cov, size) + return _squeeze_output(out) + + def entropy(self, mean=None, cov=1): + """ + Compute the differential entropy of the multivariate normal. + + Parameters + ---------- + %(_mvn_doc_default_callparams)s + + Returns + ------- + h : scalar + Entropy of the multivariate normal distribution + + Notes + ----- + %(_mvn_doc_callparams_note)s + + """ + dim, mean, cov = self._process_parameters(None, mean, cov) + _, logdet = np.linalg.slogdet(2 * np.pi * np.e * cov) + return 0.5 * logdet + + +multivariate_normal = multivariate_normal_gen() + + +class multivariate_normal_frozen(multi_rv_frozen): + def __init__(self, mean=None, cov=1, allow_singular=False, seed=None, + maxpts=None, abseps=1e-5, releps=1e-5): + """ + Create a frozen multivariate normal distribution. + + Parameters + ---------- + mean : array_like, optional + Mean of the distribution (default zero) + cov : array_like, optional + Covariance matrix of the distribution (default one) + allow_singular : bool, optional + If this flag is True then tolerate a singular + covariance matrix (default False). + seed : {None, int, `~np.random.RandomState`, `~np.random.Generator`}, optional + This parameter defines the object to use for drawing random + variates. + If `seed` is `None` the `~np.random.RandomState` singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, seeded + with seed. + If `seed` is already a ``RandomState`` or ``Generator`` instance, + then that object is used. + Default is None. + maxpts: integer, optional + The maximum number of points to use for integration of the + cumulative distribution function (default `1000000*dim`) + abseps: float, optional + Absolute error tolerance for the cumulative distribution function + (default 1e-5) + releps: float, optional + Relative error tolerance for the cumulative distribution function + (default 1e-5) + + Examples + -------- + When called with the default parameters, this will create a 1D random + variable with mean 0 and covariance 1: + + >>> from scipy.stats import multivariate_normal + >>> r = multivariate_normal() + >>> r.mean + array([ 0.]) + >>> r.cov + array([[1.]]) + + """ + self._dist = multivariate_normal_gen(seed) + self.dim, self.mean, self.cov = self._dist._process_parameters( + None, mean, cov) + self.cov_info = _PSD(self.cov, allow_singular=allow_singular) + if not maxpts: + maxpts = 1000000 * self.dim + self.maxpts = maxpts + self.abseps = abseps + self.releps = releps + + def logpdf(self, x): + x = self._dist._process_quantiles(x, self.dim) + out = self._dist._logpdf(x, self.mean, self.cov_info.U, + self.cov_info.log_pdet, self.cov_info.rank) + return _squeeze_output(out) + + def pdf(self, x): + return np.exp(self.logpdf(x)) + + def logcdf(self, x): + return np.log(self.cdf(x)) + + def cdf(self, x): + x = self._dist._process_quantiles(x, self.dim) + out = self._dist._cdf(x, self.mean, self.cov, self.maxpts, self.abseps, + self.releps) + return _squeeze_output(out) + + def rvs(self, size=1, random_state=None): + return self._dist.rvs(self.mean, self.cov, size, random_state) + + def entropy(self): + """ + Computes the differential entropy of the multivariate normal. + + Returns + ------- + h : scalar + Entropy of the multivariate normal distribution + + """ + log_pdet = self.cov_info.log_pdet + rank = self.cov_info.rank + return 0.5 * (rank * (_LOG_2PI + 1) + log_pdet) + + +_mvt_doc_default_callparams = \ +""" +loc : array_like, optional + Location of the distribution. (default ``0``) +shape : array_like, optional + Positive semidefinite matrix of the distribution. (default ``1``) +df : float, optional + Degrees of freedom of the distribution; must be greater than zero. + If ``np.inf`` then results are multivariate normal. The default is ``1``. +allow_singular : bool, optional + Whether to allow a singular matrix. (default ``False``) +""" + +_mvt_doc_callparams_note = \ +"""Setting the parameter `loc` to ``None`` is equivalent to having `loc` +be the zero-vector. The parameter `shape` can be a scalar, in which case +the shape matrix is the identity times that value, a vector of +diagonal entries for the shape matrix, or a two-dimensional array_like. +""" + +_mvt_doc_frozen_callparams_note = \ +"""See class definition for a detailed description of parameters.""" + +mvt_docdict_params = { + '_mvt_doc_default_callparams': _mvt_doc_default_callparams, + '_mvt_doc_callparams_note': _mvt_doc_callparams_note, + '_doc_random_state': _doc_random_state +} + +mvt_docdict_noparams = { + '_mvt_doc_default_callparams': "", + '_mvt_doc_callparams_note': _mvt_doc_frozen_callparams_note, + '_doc_random_state': _doc_random_state +} + + +class multivariate_t_gen(multi_rv_generic): + r""" + A multivariate t-distributed random variable. + + The `loc` parameter specifies the location. The `shape` parameter specifies + the positive semidefinite shape matrix. The `df` parameter specifies the + degrees of freedom. + + In addition to calling the methods below, the object itself may be called + as a function to fix the location, shape matrix, and degrees of freedom + parameters, returning a "frozen" multivariate t-distribution random. + + Methods + ------- + ``pdf(x, loc=None, shape=1, df=1, allow_singular=False)`` + Probability density function. + ``logpdf(x, loc=None, shape=1, df=1, allow_singular=False)`` + Log of the probability density function. + ``rvs(loc=None, shape=1, df=1, size=1, random_state=None)`` + Draw random samples from a multivariate t-distribution. + + Parameters + ---------- + x : array_like + Quantiles, with the last axis of `x` denoting the components. + %(_mvt_doc_default_callparams)s + %(_doc_random_state)s + + Notes + ----- + %(_mvt_doc_callparams_note)s + The matrix `shape` must be a (symmetric) positive semidefinite matrix. The + determinant and inverse of `shape` are computed as the pseudo-determinant + and pseudo-inverse, respectively, so that `shape` does not need to have + full rank. + + The probability density function for `multivariate_t` is + + .. math:: + + f(x) = \frac{\Gamma(\nu + p)/2}{\Gamma(\nu/2)\nu^{p/2}\pi^{p/2}|\Sigma|^{1/2}} + \exp\left[1 + \frac{1}{\nu} (\mathbf{x} - \boldsymbol{\mu})^{\top} + \boldsymbol{\Sigma}^{-1} + (\mathbf{x} - \boldsymbol{\mu}) \right]^{-(\nu + p)/2}, + + where :math:`p` is the dimension of :math:`\mathbf{x}`, + :math:`\boldsymbol{\mu}` is the :math:`p`-dimensional location, + :math:`\boldsymbol{\Sigma}` the :math:`p \times p`-dimensional shape + matrix, and :math:`\nu` is the degrees of freedom. + + .. versionadded:: 1.6.0 + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from scipy.stats import multivariate_t + >>> x, y = np.mgrid[-1:3:.01, -2:1.5:.01] + >>> pos = np.dstack((x, y)) + >>> rv = multivariate_t([1.0, -0.5], [[2.1, 0.3], [0.3, 1.5]], df=2) + >>> fig, ax = plt.subplots(1, 1) + >>> ax.set_aspect('equal') + >>> plt.contourf(x, y, rv.pdf(pos)) + + """ + + def __init__(self, seed=None): + """ + Initialize a multivariate t-distributed random variable. + + Parameters + ---------- + seed : Random state. + + """ + super().__init__(seed) + self.__doc__ = doccer.docformat(self.__doc__, mvt_docdict_params) + self._random_state = check_random_state(seed) + + def __call__(self, loc=None, shape=1, df=1, allow_singular=False, + seed=None): + """ + Create a frozen multivariate t-distribution. See + `multivariate_t_frozen` for parameters. + + """ + if df == np.inf: + return multivariate_normal_frozen(mean=loc, cov=shape, + allow_singular=allow_singular, + seed=seed) + return multivariate_t_frozen(loc=loc, shape=shape, df=df, + allow_singular=allow_singular, seed=seed) + + def pdf(self, x, loc=None, shape=1, df=1, allow_singular=False): + """ + Multivariate t-distribution probability density function. + + Parameters + ---------- + x : array_like + Points at which to evaluate the probability density function. + %(_mvt_doc_default_callparams)s + + Returns + ------- + pdf : Probability density function evaluated at `x`. + + Examples + -------- + >>> from scipy.stats import multivariate_t + >>> x = [0.4, 5] + >>> loc = [0, 1] + >>> shape = [[1, 0.1], [0.1, 1]] + >>> df = 7 + >>> multivariate_t.pdf(x, loc, shape, df) + array([0.00075713]) + + """ + dim, loc, shape, df = self._process_parameters(loc, shape, df) + x = self._process_quantiles(x, dim) + shape_info = _PSD(shape, allow_singular=allow_singular) + logpdf = self._logpdf(x, loc, shape_info.U, shape_info.log_pdet, df, + dim, shape_info.rank) + return np.exp(logpdf) + + def logpdf(self, x, loc=None, shape=1, df=1): + """ + Log of the multivariate t-distribution probability density function. + + Parameters + ---------- + x : array_like + Points at which to evaluate the log of the probability density + function. + %(_mvt_doc_default_callparams)s + + Returns + ------- + logpdf : Log of the probability density function evaluated at `x`. + + Examples + -------- + >>> from scipy.stats import multivariate_t + >>> x = [0.4, 5] + >>> loc = [0, 1] + >>> shape = [[1, 0.1], [0.1, 1]] + >>> df = 7 + >>> multivariate_t.logpdf(x, loc, shape, df) + array([-7.1859802]) + + See Also + -------- + pdf : Probability density function. + + """ + dim, loc, shape, df = self._process_parameters(loc, shape, df) + x = self._process_quantiles(x, dim) + shape_info = _PSD(shape) + return self._logpdf(x, loc, shape_info.U, shape_info.log_pdet, df, dim, + shape_info.rank) + + def _logpdf(self, x, loc, prec_U, log_pdet, df, dim, rank): + """Utility method `pdf`, `logpdf` for parameters. + + Parameters + ---------- + x : ndarray + Points at which to evaluate the log of the probability density + function. + loc : ndarray + Location of the distribution. + prec_U : ndarray + A decomposition such that `np.dot(prec_U, prec_U.T)` is the inverse + of the shape matrix. + log_pdet : float + Logarithm of the determinant of the shape matrix. + df : float + Degrees of freedom of the distribution. + dim : int + Dimension of the quantiles x. + rank : int + Rank of the shape matrix. + + Notes + ----- + As this function does no argument checking, it should not be called + directly; use 'logpdf' instead. + + """ + if df == np.inf: + return multivariate_normal._logpdf(x, loc, prec_U, log_pdet, rank) + + dev = x - loc + maha = np.square(np.dot(dev, prec_U)).sum(axis=-1) + + t = 0.5 * (df + dim) + A = gammaln(t) + B = gammaln(0.5 * df) + C = dim/2. * np.log(df * np.pi) + D = 0.5 * log_pdet + E = -t * np.log(1 + (1./df) * maha) + + return _squeeze_output(A - B - C - D + E) + + def rvs(self, loc=None, shape=1, df=1, size=1, random_state=None): + """ + Draw random samples from a multivariate t-distribution. + + Parameters + ---------- + %(_mvt_doc_default_callparams)s + size : integer, optional + Number of samples to draw (default 1). + %(_doc_random_state)s + + Returns + ------- + rvs : ndarray or scalar + Random variates of size (`size`, `P`), where `P` is the + dimension of the random variable. + + Examples + -------- + >>> from scipy.stats import multivariate_t + >>> x = [0.4, 5] + >>> loc = [0, 1] + >>> shape = [[1, 0.1], [0.1, 1]] + >>> df = 7 + >>> multivariate_t.rvs(loc, shape, df) + array([[0.93477495, 3.00408716]]) + + """ + # For implementation details, see equation (3): + # + # Hofert, "On Sampling from the Multivariatet Distribution", 2013 + # http://rjournal.github.io/archive/2013-2/hofert.pdf + # + dim, loc, shape, df = self._process_parameters(loc, shape, df) + if random_state is not None: + rng = check_random_state(random_state) + else: + rng = self._random_state + + if np.isinf(df): + x = np.ones(size) + else: + x = rng.chisquare(df, size=size) / df + + z = rng.multivariate_normal(np.zeros(dim), shape, size=size) + samples = loc + z / np.sqrt(x)[:, None] + return _squeeze_output(samples) + + def _process_quantiles(self, x, dim): + """ + Adjust quantiles array so that last axis labels the components of + each data point. + + """ + x = np.asarray(x, dtype=float) + if x.ndim == 0: + x = x[np.newaxis] + elif x.ndim == 1: + if dim == 1: + x = x[:, np.newaxis] + else: + x = x[np.newaxis, :] + return x + + def _process_parameters(self, loc, shape, df): + """ + Infer dimensionality from location array and shape matrix, handle + defaults, and ensure compatible dimensions. + + """ + if loc is None and shape is None: + loc = np.asarray(0, dtype=float) + shape = np.asarray(1, dtype=float) + dim = 1 + elif loc is None: + shape = np.asarray(shape, dtype=float) + if shape.ndim < 2: + dim = 1 + else: + dim = shape.shape[0] + loc = np.zeros(dim) + elif shape is None: + loc = np.asarray(loc, dtype=float) + dim = loc.size + shape = np.eye(dim) + else: + shape = np.asarray(shape, dtype=float) + loc = np.asarray(loc, dtype=float) + dim = loc.size + + if dim == 1: + loc.shape = (1,) + shape.shape = (1, 1) + + if loc.ndim != 1 or loc.shape[0] != dim: + raise ValueError("Array 'loc' must be a vector of length %d." % + dim) + if shape.ndim == 0: + shape = shape * np.eye(dim) + elif shape.ndim == 1: + shape = np.diag(shape) + elif shape.ndim == 2 and shape.shape != (dim, dim): + rows, cols = shape.shape + if rows != cols: + msg = ("Array 'cov' must be square if it is two dimensional," + " but cov.shape = %s." % str(shape.shape)) + else: + msg = ("Dimension mismatch: array 'cov' is of shape %s," + " but 'loc' is a vector of length %d.") + msg = msg % (str(shape.shape), len(loc)) + raise ValueError(msg) + elif shape.ndim > 2: + raise ValueError("Array 'cov' must be at most two-dimensional," + " but cov.ndim = %d" % shape.ndim) + + # Process degrees of freedom. + if df is None: + df = 1 + elif df <= 0: + raise ValueError("'df' must be greater than zero.") + elif np.isnan(df): + raise ValueError("'df' is 'nan' but must be greater than zero or 'np.inf'.") + + return dim, loc, shape, df + + +class multivariate_t_frozen(multi_rv_frozen): + + def __init__(self, loc=None, shape=1, df=1, allow_singular=False, + seed=None): + """ + Create a frozen multivariate t distribution. + + Parameters + ---------- + %(_mvt_doc_default_callparams)s + + Examples + -------- + >>> loc = np.zeros(3) + >>> shape = np.eye(3) + >>> df = 10 + >>> dist = multivariate_t(loc, shape, df) + >>> dist.rvs() + array([[ 0.81412036, -1.53612361, 0.42199647]]) + >>> dist.pdf([1, 1, 1]) + array([0.01237803]) + + """ + self._dist = multivariate_t_gen(seed) + dim, loc, shape, df = self._dist._process_parameters(loc, shape, df) + self.dim, self.loc, self.shape, self.df = dim, loc, shape, df + self.shape_info = _PSD(shape, allow_singular=allow_singular) + + def logpdf(self, x): + x = self._dist._process_quantiles(x, self.dim) + U = self.shape_info.U + log_pdet = self.shape_info.log_pdet + return self._dist._logpdf(x, self.loc, U, log_pdet, self.df, self.dim, + self.shape_info.rank) + + def pdf(self, x): + return np.exp(self.logpdf(x)) + + def rvs(self, size=1, random_state=None): + return self._dist.rvs(loc=self.loc, + shape=self.shape, + df=self.df, + size=size, + random_state=random_state) + + +multivariate_t = multivariate_t_gen() + + +# Set frozen generator docstrings from corresponding docstrings in +# matrix_normal_gen and fill in default strings in class docstrings +for name in ['logpdf', 'pdf', 'rvs']: + method = multivariate_t_gen.__dict__[name] + method_frozen = multivariate_t_frozen.__dict__[name] + method_frozen.__doc__ = doccer.docformat(method.__doc__, + mvt_docdict_noparams) + method.__doc__ = doccer.docformat(method.__doc__, mvt_docdict_params) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/compat/numpy.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/compat/numpy.py new file mode 100644 index 0000000000000000000000000000000000000000..917fd2bb8e4438378f985dd5ccd2059ea310dc75 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/compat/numpy.py @@ -0,0 +1,68 @@ +"""Compatibility functions for numpy versions in lib + +np_new_unique +------------- +Optionally provides the count of the number of occurrences of each +unique element. + +Copied from Numpy source, under license: + +Copyright (c) 2005-2015, NumPy Developers. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + +* Neither the name of the NumPy Developers nor the names of any + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +""" +import numpy as np +from packaging.version import Version, parse + +__all__ = [ + "NP_LT_2", + "NP_LT_123", + "NP_LT_114", + "lstsq", + "np_matrix_rank", + "np_new_unique", +] + +NP_LT_114 = parse(np.__version__) < Version("1.13.99") +NP_LT_123 = parse(np.__version__) < Version("1.22.99") +NP_LT_2 = parse(np.__version__) < Version("1.99.99") + +np_matrix_rank = np.linalg.matrix_rank +np_new_unique = np.unique + + +def lstsq(a, b, rcond=None): + """ + Shim that allows modern rcond setting with backward compat for NumPY + earlier than 1.14 + """ + if NP_LT_114 and rcond is None: + rcond = -1 + return np.linalg.lstsq(a, b, rcond=rcond) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/compat/pandas.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/compat/pandas.py new file mode 100644 index 0000000000000000000000000000000000000000..ac8c902c563c70e1f5a882e12a50d68d5316d884 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/compat/pandas.py @@ -0,0 +1,224 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Callable, Mapping, Optional, TypeVar + +import numpy as np +from packaging.version import Version, parse +import pandas as pd +from pandas.util._decorators import ( + Appender, + Substitution, + cache_readonly, + deprecate_kwarg as pd_deprecate_kwarg, +) + +if TYPE_CHECKING: + try: + from typing import TypeAlias + except ImportError: + from typing_extensions import TypeAlias + + +FuncType: TypeAlias = Callable[..., Any] +F = TypeVar("F", bound=FuncType) +__all__ = [ + "assert_frame_equal", + "assert_index_equal", + "assert_series_equal", + "data_klasses", + "frequencies", + "is_numeric_dtype", + "testing", + "cache_readonly", + "deprecate_kwarg", + "Appender", + "Substitution", + "is_int_index", + "is_float_index", + "make_dataframe", + "to_numpy", + "PD_LT_1_0_0", + "get_cached_func", + "get_cached_doc", + "call_cached_func", + "PD_LT_1_4", + "PD_LT_2", + "MONTH_END", + "QUARTER_END", + "YEAR_END", + "FUTURE_STACK", + "PD_LT_3", +] + +version = parse(pd.__version__) + +PD_LT_2_2_0 = version < Version("2.1.99") +PD_LT_2_1_0 = version < Version("2.0.99") +PD_LT_1_0_0 = version < Version("0.99.0") +PD_LT_1_4 = version < Version("1.3.99") +PD_LT_2 = version < Version("1.99.99") +PD_LT_3 = version < Version("2.99.99") + +try: + from pandas.api.types import is_numeric_dtype +except ImportError: + from pandas.core.common import is_numeric_dtype + +try: + from pandas.tseries import offsets as frequencies +except ImportError: + from pandas.tseries import frequencies + +data_klasses = (pd.Series, pd.DataFrame) + +try: + import pandas.testing as testing +except ImportError: + import pandas.util.testing as testing + +assert_frame_equal = testing.assert_frame_equal +assert_index_equal = testing.assert_index_equal +assert_series_equal = testing.assert_series_equal + + +def is_int_index(index: pd.Index) -> bool: + """ + Check if an index is integral + + Parameters + ---------- + index : pd.Index + Any numeric index + + Returns + ------- + bool + True if is an index with a standard integral type + """ + return ( + isinstance(index, pd.Index) + and isinstance(index.dtype, np.dtype) + and np.issubdtype(index.dtype, np.integer) + ) + + +def is_float_index(index: pd.Index) -> bool: + """ + Check if an index is floating + + Parameters + ---------- + index : pd.Index + Any numeric index + + Returns + ------- + bool + True if an index with a standard numpy floating dtype + """ + return ( + isinstance(index, pd.Index) + and isinstance(index.dtype, np.dtype) + and np.issubdtype(index.dtype, np.floating) + ) + + +try: + from pandas._testing import makeDataFrame as make_dataframe +except ImportError: + import string + + def rands_array(nchars, size, dtype="O"): + """ + Generate an array of byte strings. + """ + rands_chars = np.array( + list(string.ascii_letters + string.digits), dtype=(np.str_, 1) + ) + retval = ( + np.random.choice(rands_chars, size=nchars * np.prod(size)) + .view((np.str_, nchars)) + .reshape(size) + ) + if dtype is None: + return retval + else: + return retval.astype(dtype) + + def make_dataframe(): + """ + Simple verion of pandas._testing.makeDataFrame + """ + n = 30 + k = 4 + index = pd.Index(rands_array(nchars=10, size=n), name=None) + data = { + c: pd.Series(np.random.randn(n), index=index) + for c in string.ascii_uppercase[:k] + } + + return pd.DataFrame(data) + + +def to_numpy(po: pd.DataFrame) -> np.ndarray: + """ + Workaround legacy pandas lacking to_numpy + + Parameters + ---------- + po : Pandas obkect + + Returns + ------- + ndarray + A numpy array + """ + try: + return po.to_numpy() + except AttributeError: + return po.values + + +def get_cached_func(cached_prop): + try: + return cached_prop.fget + except AttributeError: + return cached_prop.func + + +def call_cached_func(cached_prop, *args, **kwargs): + f = get_cached_func(cached_prop) + return f(*args, **kwargs) + + +def get_cached_doc(cached_prop) -> Optional[str]: + return get_cached_func(cached_prop).__doc__ + + +MONTH_END = "M" if PD_LT_2_2_0 else "ME" +QUARTER_END = "Q" if PD_LT_2_2_0 else "QE" +YEAR_END = "Y" if PD_LT_2_2_0 else "YE" +FUTURE_STACK = {} if PD_LT_2_1_0 else {"future_stack": True} + + +def deprecate_kwarg( + old_arg_name: str, + new_arg_name: str | None, + mapping: Mapping[Any, Any] | Callable[[Any], Any] | None = None, + stacklevel: int = 2, +) -> Callable[[F], F]: + if PD_LT_3: + return pd_deprecate_kwarg( + old_arg_name=old_arg_name, + new_arg_name=new_arg_name, + mapping=mapping, + stacklevel=stacklevel, + ) + else: + return pd_deprecate_kwarg( + klass=FutureWarning, + old_arg_name=old_arg_name, + new_arg_name=new_arg_name, + mapping=mapping, + stacklevel=stacklevel, + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/compat/patsy.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/compat/patsy.py new file mode 100644 index 0000000000000000000000000000000000000000..9d762b4253fe9438f399369a5f20250c35f95076 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/compat/patsy.py @@ -0,0 +1,16 @@ +from statsmodels.compat.pandas import PD_LT_2 + +import pandas as pd +import patsy.util + + +def _safe_is_pandas_categorical_dtype(dt): + if PD_LT_2: + return pd.api.types.is_categorical_dtype(dt) + return isinstance(dt, pd.CategoricalDtype) + + +def monkey_patch_cat_dtype(): + patsy.util.safe_is_pandas_categorical_dtype = ( + _safe_is_pandas_categorical_dtype + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/compat/platform.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/compat/platform.py new file mode 100644 index 0000000000000000000000000000000000000000..715b5b4f6b34198f24fcd46ca9c6c68a7b9c84c1 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/compat/platform.py @@ -0,0 +1,18 @@ +import os +import sys + +__all__ = [ + "PLATFORM_OSX", + "PLATFORM_WIN", + "PLATFORM_WIN32", + "PLATFORM_32", + "PLATFORM_LINUX", + "PLATFORM_LINUX32", +] + +PLATFORM_OSX = sys.platform == "darwin" +PLATFORM_WIN = sys.platform in ("win32", "cygwin") or os.name == "nt" +PLATFORM_WIN32 = PLATFORM_WIN and sys.maxsize < 2 ** 33 +PLATFORM_LINUX = sys.platform[:5] == "linux" +PLATFORM_32 = sys.maxsize < 2 ** 33 +PLATFORM_LINUX32 = PLATFORM_32 and PLATFORM_LINUX diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/compat/pytest.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/compat/pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..1e820037f86271a0f18612f086669c1887aa7f37 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/compat/pytest.py @@ -0,0 +1,50 @@ +from __future__ import annotations + +import warnings + +from _pytest.recwarn import WarningsChecker +from pytest import warns + +__all__ = ["pytest_warns"] + + +class NoWarningsChecker: + def __init__(self): + self.cw = warnings.catch_warnings(record=True) + self.rec = [] + + def __enter__(self): + self.rec = self.cw.__enter__() + + def __exit__(self, type, value, traceback): + if self.rec: + warnings = [w.category.__name__ for w in self.rec] + joined = "\\n".join(warnings) + raise AssertionError( + "Function is marked as not warning but the following " + "warnings were found: \n" + f"{joined}" + ) + + +def pytest_warns( + warning: type[Warning] | tuple[type[Warning], ...] | None +) -> WarningsChecker | NoWarningsChecker: + """ + + Parameters + ---------- + warning : {None, Warning, Tuple[Warning]} + None if no warning is produced, or a single or multiple Warnings + + Returns + ------- + cm + + """ + if warning is None: + return NoWarningsChecker() + else: + assert warning is not None + + return warns(warning) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/compat/python.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/compat/python.py new file mode 100644 index 0000000000000000000000000000000000000000..959be7f229fb07ed78ad93f938bcad8683c955a8 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/compat/python.py @@ -0,0 +1,65 @@ +""" +Compatibility tools for differences between Python 2 and 3 +""" + +import platform +import sys + +asunicode = lambda x, _: str(x) # noqa:E731 + +PYTHON_IMPL_WASM = ( + sys.platform == "emscripten" or platform.machine() in ["wasm32", "wasm64"] +) + +__all__ = [ + "asunicode", + "asstr", + "asbytes", + "lmap", + "lzip", + "lrange", + "lfilter", + "with_metaclass", + "PYTHON_IMPL_WASM", +] + + +def asbytes(s): + if isinstance(s, bytes): + return s + return s.encode("latin1") + + +def asstr(s): + if isinstance(s, str): + return s + return s.decode("latin1") + + +# list-producing versions of the major Python iterating functions +def lrange(*args, **kwargs): + return list(range(*args, **kwargs)) + + +def lzip(*args, **kwargs): + return list(zip(*args, **kwargs)) + + +def lmap(*args, **kwargs): + return list(map(*args, **kwargs)) + + +def lfilter(*args, **kwargs): + return list(filter(*args, **kwargs)) + + +def with_metaclass(meta, *bases): + """Create a base class with a metaclass.""" + # This requires a bit of explanation: the basic idea is to make a dummy + # metaclass for one level of class instantiation that replaces itself with + # the actual metaclass. + class metaclass(meta): + def __new__(cls, name, this_bases, d): + return meta(name, bases, d) + + return type.__new__(metaclass, "temporary_class", (), {}) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/compat/scipy.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/compat/scipy.py new file mode 100644 index 0000000000000000000000000000000000000000..2649c878ca276e4a6137db67aea9dd28cca8e802 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/compat/scipy.py @@ -0,0 +1,135 @@ +from packaging.version import Version, parse + +import numpy as np +import scipy + +SP_VERSION = parse(scipy.__version__) +SP_LT_15 = SP_VERSION < Version("1.4.99") +SCIPY_GT_14 = not SP_LT_15 +SP_LT_16 = SP_VERSION < Version("1.5.99") +SP_LT_17 = SP_VERSION < Version("1.6.99") +SP_LT_19 = SP_VERSION < Version("1.8.99") +SP_LT_116 = SP_VERSION < Version("1.15.99") + + +def _next_regular(target): + """ + Find the next regular number greater than or equal to target. + Regular numbers are composites of the prime factors 2, 3, and 5. + Also known as 5-smooth numbers or Hamming numbers, these are the optimal + size for inputs to FFTPACK. + + Target must be a positive integer. + """ + if target <= 6: + return target + + # Quickly check if it's already a power of 2 + if not (target & (target - 1)): + return target + + match = float("inf") # Anything found will be smaller + p5 = 1 + while p5 < target: + p35 = p5 + while p35 < target: + # Ceiling integer division, avoiding conversion to float + # (quotient = ceil(target / p35)) + quotient = -(-target // p35) + # Quickly find next power of 2 >= quotient + p2 = 2 ** ((quotient - 1).bit_length()) + + N = p2 * p35 + if N == target: + return N + elif N < match: + match = N + p35 *= 3 + if p35 == target: + return p35 + if p35 < match: + match = p35 + p5 *= 5 + if p5 == target: + return p5 + if p5 < match: + match = p5 + return match + + +def _valarray(shape, value=np.nan, typecode=None): + """Return an array of all value.""" + + out = np.ones(shape, dtype=bool) * value + if typecode is not None: + out = out.astype(typecode) + if not isinstance(out, np.ndarray): + out = np.asarray(out) + return out + + +if SP_LT_16: + # copied from scipy, added to scipy in 1.6.0 + from ._scipy_multivariate_t import multivariate_t # noqa: F401 +else: + from scipy.stats import multivariate_t # noqa: F401 + + +def apply_where( # type: ignore[explicit-any] # numpydoc ignore=PR01,PR02 + cond, args, f1, f2=None, /, *, fill_value=None +): + """ + Run one of two elementwise functions depending on a condition. + + Equivalent to ``f1(*args) if cond else fill_value`` performed elementwise + when `fill_value` is defined, otherwise to ``f1(*args) if cond else f2(*args)``. + + Parameters + ---------- + cond : array + The condition, expressed as a boolean array. + args : Array or tuple of Arrays + Argument(s) to `f1` (and `f2`). Must be broadcastable with `cond`. + f1 : callable + Elementwise function of `args`, returning a single array. + Where `cond` is True, output will be ``f1(arg0[cond], arg1[cond], ...)``. + f2 : callable, optional + Elementwise function of `args`, returning a single array. + Where `cond` is False, output will be ``f2(arg0[cond], arg1[cond], ...)``. + Mutually exclusive with `fill_value`. + fill_value : Array or scalar, optional + If provided, value with which to fill output array where `cond` is False. + It does not need to be scalar; it needs however to be broadcastable with + `cond` and `args`. + Mutually exclusive with `f2`. You must provide one or the other. + xp : array_namespace, optional + The standard-compatible namespace for `cond` and `args`. Default: infer. + + Returns + ------- + Array + An array with elements from the output of `f1` where `cond` is True and either + the output of `f2` or `fill_value` where `cond` is False. The returned array has + data type determined by type promotion rules between the output of `f1` and + either `fill_value` or the output of `f2`. + + Notes + ----- + Falls back to _lazywhere if xpx.apply_where is not available. + + ``xp.where(cond, f1(*args), f2(*args))`` requires explicitly evaluating `f1` even + when `cond` is False, and `f2` when cond is True. This function evaluates each + function only for their matching condition, if the backend allows for it. + + On Dask, `f1` and `f2` are applied to the individual chunks and should use functions + from the namespace of the chunks. + + """ + try: + import scipy._lib.array_api_extra as xpx + + return xpx.apply_where(cond, args, f1, f2, fill_value=fill_value) + except (ImportError, AttributeError): + from scipy._lib._util import _lazywhere + + return _lazywhere(cond, args, f1, fill_value, f2) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/datasets/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/datasets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2232c1008d3ad03beb2d745988205b90bbcefe3a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/datasets/__init__.py @@ -0,0 +1,81 @@ +""" +Datasets module +""" +from statsmodels.tools._test_runner import PytestTester + +from . import ( + anes96, + cancer, + ccard, + china_smoking, + co2, + committee, + copper, + cpunish, + danish_data, + elnino, + engel, + fair, + fertility, + grunfeld, + heart, + interest_inflation, + longley, + macrodata, + modechoice, + nile, + randhie, + scotland, + spector, + stackloss, + star98, + statecrime, + strikes, + sunspots, +) +from .utils import ( + check_internet, + clear_data_home, + get_data_home, + get_rdataset, + webuse, +) + +__all__ = [ + "anes96", + "cancer", + "committee", + "ccard", + "copper", + "cpunish", + "elnino", + "engel", + "grunfeld", + "interest_inflation", + "longley", + "macrodata", + "modechoice", + "nile", + "randhie", + "scotland", + "spector", + "stackloss", + "star98", + "strikes", + "sunspots", + "fair", + "heart", + "statecrime", + "co2", + "fertility", + "china_smoking", + "get_rdataset", + "get_data_home", + "clear_data_home", + "webuse", + "check_internet", + "test", + "danish_data", +] + +test = PytestTester() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/datasets/template_data.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/datasets/template_data.py new file mode 100644 index 0000000000000000000000000000000000000000..312b9eb4570f8551df4545e2de0231e128fe5db1 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/datasets/template_data.py @@ -0,0 +1,56 @@ +"""Name of dataset.""" +from statsmodels.datasets import utils as du + +__docformat__ = 'restructuredtext' + +COPYRIGHT = """E.g., This is public domain.""" +TITLE = """Title of the dataset""" +SOURCE = """ +This section should provide a link to the original dataset if possible and +attribution and correspondance information for the dataset's original author +if so desired. +""" + +DESCRSHORT = """A short description.""" + +DESCRLONG = """A longer description of the dataset.""" + +#suggested notes +NOTE = """ +:: + + Number of observations: + Number of variables: + Variable name definitions: + +Any other useful information that does not fit into the above categories. +""" + + +def load(): + """ + Load the data and return a Dataset class instance. + + Returns + ------- + Dataset + See DATASET_PROPOSAL.txt for more information. + """ + return load_pandas() + + +def load_pandas(): + """ + Load the strikes data and return a Dataset class instance. + + Returns + ------- + Dataset + See DATASET_PROPOSAL.txt for more information. + """ + data = _get_data() + return du.process_pandas(data, endog_idx=0) + + +def _get_data(): + return du.load_csv(__file__, 'DatasetName.csv') diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/datasets/utils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/datasets/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..09972f7ea2acfc3223aeab68233ef4d0ead22103 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/datasets/utils.py @@ -0,0 +1,332 @@ +from statsmodels.compat.python import lrange + +from io import StringIO +from os import environ, makedirs +from os.path import abspath, dirname, exists, expanduser, join +import shutil +from urllib.error import HTTPError, URLError +from urllib.parse import urljoin +from urllib.request import urlopen + +import numpy as np +from pandas import Index, read_csv, read_stata + + +def webuse(data, baseurl='https://www.stata-press.com/data/r11/', as_df=True): + """ + Download and return an example dataset from Stata. + + Parameters + ---------- + data : str + Name of dataset to fetch. + baseurl : str + The base URL to the stata datasets. + as_df : bool + Deprecated. Always returns a DataFrame + + Returns + ------- + dta : DataFrame + A DataFrame containing the Stata dataset. + + Examples + -------- + >>> dta = webuse('auto') + + Notes + ----- + Make sure baseurl has trailing forward slash. Does not do any + error checking in response URLs. + """ + url = urljoin(baseurl, data+'.dta') + return read_stata(url) + + +class Dataset(dict): + def __init__(self, **kw): + # define some default attributes, so pylint can find them + self.endog = None + self.exog = None + self.data = None + self.names = None + + dict.__init__(self, kw) + self.__dict__ = self + # Some datasets have string variables. If you want a raw_data + # attribute you must create this in the dataset's load function. + try: # some datasets have string variables + self.raw_data = self.data.astype(float) + except: + pass + + def __repr__(self): + return str(self.__class__) + + +def process_pandas(data, endog_idx=0, exog_idx=None, index_idx=None): + names = data.columns + + if isinstance(endog_idx, int): + endog_name = names[endog_idx] + endog = data[endog_name].copy() + if exog_idx is None: + exog = data.drop([endog_name], axis=1) + else: + exog = data[names[exog_idx]].copy() + else: + endog = data.loc[:, endog_idx].copy() + endog_name = list(endog.columns) + if exog_idx is None: + exog = data.drop(endog_name, axis=1) + elif isinstance(exog_idx, int): + exog = data[names[exog_idx]].copy() + else: + exog = data[names[exog_idx]].copy() + + if index_idx is not None: # NOTE: will have to be improved for dates + index = Index(data.iloc[:, index_idx]) + endog.index = index + exog.index = index.copy() + data = data.set_index(names[index_idx]) + + exog_name = list(exog.columns) + dataset = Dataset(data=data, names=list(names), endog=endog, + exog=exog, endog_name=endog_name, exog_name=exog_name) + return dataset + + +def _maybe_reset_index(data): + """ + All the Rdatasets have the integer row.labels from R if there is no + real index. Strip this for a zero-based index + """ + if data.index.equals(Index(lrange(1, len(data) + 1))): + data = data.reset_index(drop=True) + return data + + +def _get_cache(cache): + if cache is False: + # do not do any caching or load from cache + cache = None + elif cache is True: # use default dir for cache + cache = get_data_home(None) + else: + cache = get_data_home(cache) + return cache + + +def _cache_it(data, cache_path): + import zlib + with open(cache_path, "wb") as zf: + zf.write(zlib.compress(data)) + + +def _open_cache(cache_path): + import zlib + # return as bytes object encoded in utf-8 for cross-compat of cached + with open(cache_path, 'rb') as zf: + return zlib.decompress(zf.read()) + + +def _urlopen_cached(url, cache): + """ + Tries to load data from cache location otherwise downloads it. If it + downloads the data and cache is not None then it will put the downloaded + data in the cache path. + """ + from_cache = False + if cache is not None: + file_name = url.split("://")[-1].replace('/', ',') + file_name = file_name.split('.') + if len(file_name) > 1: + file_name[-2] += '-v2' + else: + file_name[0] += '-v2' + file_name = '.'.join(file_name) + ".zip" + cache_path = join(cache, file_name) + try: + data = _open_cache(cache_path) + from_cache = True + except: + pass + + # not using the cache or did not find it in cache + if not from_cache: + data = urlopen(url, timeout=3).read() + if cache is not None: # then put it in the cache + _cache_it(data, cache_path) + return data, from_cache + + +def _get_data(base_url, dataname, cache, extension="csv"): + url = base_url + (dataname + ".%s") % extension + try: + data, from_cache = _urlopen_cached(url, cache) + except HTTPError as err: + if '404' in str(err): + raise ValueError("Dataset %s was not found." % dataname) + else: + raise err + + data = data.decode('utf-8', 'strict') + return StringIO(data), from_cache + + +def _get_dataset_meta(dataname, package, cache): + # get the index, you'll probably want this cached because you have + # to download info about all the data to get info about any of the data... + index_url = ("https://raw.githubusercontent.com/vincentarelbundock/" + "Rdatasets/master/datasets.csv") + data, _ = _urlopen_cached(index_url, cache) + data = data.decode('utf-8', 'strict') + index = read_csv(StringIO(data)) + idx = np.logical_and(index.Item == dataname, index.Package == package) + if not idx.any(): + raise ValueError( + f"Item {dataname} from Package {package} was not found. Check " + f"the CSV file at {index_url} to verify the Item and Package." + ) + dataset_meta = index.loc[idx] + return dataset_meta["Title"].iloc[0] + + +def get_rdataset(dataname, package="datasets", cache=False): + """download and return R dataset + + Parameters + ---------- + dataname : str + The name of the dataset you want to download + package : str + The package in which the dataset is found. The default is the core + 'datasets' package. + cache : bool or str + If True, will download this data into the STATSMODELS_DATA folder. + The default location is a folder called statsmodels_data in the + user home folder. Otherwise, you can specify a path to a folder to + use for caching the data. If False, the data will not be cached. + + Returns + ------- + dataset : Dataset + A `statsmodels.data.utils.Dataset` instance. This objects has + attributes: + + * data - A pandas DataFrame containing the data + * title - The dataset title + * package - The package from which the data came + * from_cache - Whether not cached data was retrieved + * __doc__ - The verbatim R documentation. + + Notes + ----- + If the R dataset has an integer index. This is reset to be zero-based. + Otherwise the index is preserved. The caching facilities are dumb. That + is, no download dates, e-tags, or otherwise identifying information + is checked to see if the data should be downloaded again or not. If the + dataset is in the cache, it's used. + """ + # NOTE: use raw github bc html site might not be most up to date + data_base_url = ("https://raw.githubusercontent.com/vincentarelbundock/Rdatasets/" + "master/csv/"+package+"/") + docs_base_url = ("https://raw.githubusercontent.com/vincentarelbundock/Rdatasets/" + "master/doc/"+package+"/rst/") + cache = _get_cache(cache) + data, from_cache = _get_data(data_base_url, dataname, cache) + data = read_csv(data, index_col=0) + data = _maybe_reset_index(data) + + title = _get_dataset_meta(dataname, package, cache) + doc, _ = _get_data(docs_base_url, dataname, cache, "rst") + + return Dataset(data=data, __doc__=doc.read(), package=package, title=title, + from_cache=from_cache) + +# The below function were taken from sklearn + + +def get_data_home(data_home=None): + """Return the path of the statsmodels data dir. + + This folder is used by some large dataset loaders to avoid + downloading the data several times. + + By default the data dir is set to a folder named 'statsmodels_data' + in the user home folder. + + Alternatively, it can be set by the 'STATSMODELS_DATA' environment + variable or programatically by giving an explicit folder path. The + '~' symbol is expanded to the user home folder. + + If the folder does not already exist, it is automatically created. + """ + if data_home is None: + data_home = environ.get('STATSMODELS_DATA', + join('~', 'statsmodels_data')) + data_home = expanduser(data_home) + if not exists(data_home): + makedirs(data_home) + return data_home + + +def clear_data_home(data_home=None): + """Delete all the content of the data home cache.""" + data_home = get_data_home(data_home) + shutil.rmtree(data_home) + + +def check_internet(url=None): + """Check if internet is available""" + url = "https://github.com" if url is None else url + try: + urlopen(url) + except URLError as err: + return False + return True + + +def strip_column_names(df): + """ + Remove leading and trailing single quotes + + Parameters + ---------- + df : DataFrame + DataFrame to process + + Returns + ------- + df : DataFrame + DataFrame with stripped column names + + Notes + ----- + In-place modification + """ + columns = [] + for c in df: + if c.startswith('\'') and c.endswith('\''): + c = c[1:-1] + elif c.startswith('\''): + c = c[1:] + elif c.endswith('\''): + c = c[:-1] + columns.append(c) + df.columns = columns + return df + + +def load_csv(base_file, csv_name, sep=',', convert_float=False): + """Standard simple csv loader""" + filepath = dirname(abspath(base_file)) + filename = join(filepath,csv_name) + engine = 'python' if sep != ',' else 'c' + float_precision = {} + if engine == 'c': + float_precision = {'float_precision': 'high'} + data = read_csv(filename, sep=sep, engine=engine, **float_precision) + if convert_float: + data = data.astype(float) + return data diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/emplike/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/emplike/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..691559ca60fe92a39e770cdb5d16c42a4c5651e1 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/emplike/__init__.py @@ -0,0 +1,3 @@ +from statsmodels.tools._test_runner import PytestTester + +test = PytestTester() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/emplike/aft_el.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/emplike/aft_el.py new file mode 100644 index 0000000000000000000000000000000000000000..86ed5b7792dabfa475da565a098a2ada21d4be86 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/emplike/aft_el.py @@ -0,0 +1,539 @@ +""" + +Accelerated Failure Time (AFT) Model with empirical likelihood inference. + +AFT regression analysis is applicable when the researcher has access +to a randomly right censored dependent variable, a matrix of exogenous +variables and an indicatior variable (delta) that takes a value of 0 if the +observation is censored and 1 otherwise. + +AFT References +-------------- + +Stute, W. (1993). "Consistent Estimation Under Random Censorship when +Covariables are Present." Journal of Multivariate Analysis. +Vol. 45. Iss. 1. 89-103 + +EL and AFT References +--------------------- + +Zhou, Kim And Bathke. "Empirical Likelihood Analysis for the Heteroskedastic +Accelerated Failure Time Model." Manuscript: +URL: www.ms.uky.edu/~mai/research/CasewiseEL20080724.pdf + +Zhou, M. (2005). Empirical Likelihood Ratio with Arbitrarily Censored/ +Truncated Data by EM Algorithm. Journal of Computational and Graphical +Statistics. 14:3, 643-656. + + +""" +import warnings + +import numpy as np +#from elregress import ElReg +from scipy import optimize +from scipy.stats import chi2 + +from statsmodels.regression.linear_model import OLS, WLS +from statsmodels.tools import add_constant +from statsmodels.tools.sm_exceptions import IterationLimitWarning + +from .descriptive import _OptFuncts + + +class OptAFT(_OptFuncts): + """ + Provides optimization functions used in estimating and conducting + inference in an AFT model. + + Methods + ------ + + _opt_wtd_nuis_regress: + Function optimized over nuisance parameters to compute + the profile likelihood + + _EM_test: + Uses the modified Em algorithm of Zhou 2005 to maximize the + likelihood of a parameter vector. + """ + def __init__(self): + pass + + def _opt_wtd_nuis_regress(self, test_vals): + """ + A function that is optimized over nuisance parameters to conduct a + hypothesis test for the parameters of interest + + Parameters + ---------- + + params: 1d array + The regression coefficients of the model. This includes the + nuisance and parameters of interests. + + Returns + ------- + llr : float + -2 times the log likelihood of the nuisance parameters and the + hypothesized value of the parameter(s) of interest. + """ + test_params = test_vals.reshape(self.model.nvar, 1) + est_vect = self.model.uncens_exog * (self.model.uncens_endog - + np.dot(self.model.uncens_exog, + test_params)) + eta_star = self._modif_newton(np.zeros(self.model.nvar), est_vect, + self.model._fit_weights) + denom = np.sum(self.model._fit_weights) + np.dot(eta_star, est_vect.T) + self.new_weights = self.model._fit_weights / denom + return -1 * np.sum(np.log(self.new_weights)) + + def _EM_test(self, nuisance_params, params=None, param_nums=None, + b0_vals=None, F=None, survidx=None, uncens_nobs=None, + numcensbelow=None, km=None, uncensored=None, censored=None, + maxiter=None, ftol=None): + """ + Uses EM algorithm to compute the maximum likelihood of a test + + Parameters + ---------- + + nuisance_params : ndarray + Vector of values to be used as nuisance params. + + maxiter : int + Number of iterations in the EM algorithm for a parameter vector + + Returns + ------- + -2 ''*'' log likelihood ratio at hypothesized values and + nuisance params + + Notes + ----- + Optional parameters are provided by the test_beta function. + """ + iters = 0 + params[param_nums] = b0_vals + + nuis_param_index = np.int_(np.delete(np.arange(self.model.nvar), + param_nums)) + params[nuis_param_index] = nuisance_params + to_test = params.reshape(self.model.nvar, 1) + opt_res = np.inf + diff = np.inf + while iters < maxiter and diff > ftol: + F = F.flatten() + death = np.cumsum(F[::-1]) + survivalprob = death[::-1] + surv_point_mat = np.dot(F.reshape(-1, 1), + 1. / survivalprob[survidx].reshape(1, - 1)) + surv_point_mat = add_constant(surv_point_mat) + summed_wts = np.cumsum(surv_point_mat, axis=1) + wts = summed_wts[np.int_(np.arange(uncens_nobs)), + numcensbelow[uncensored]] + # ^E step + # See Zhou 2005, section 3. + self.model._fit_weights = wts + new_opt_res = self._opt_wtd_nuis_regress(to_test) + # ^ Uncensored weights' contribution to likelihood value. + F = self.new_weights + # ^ M step + diff = np.abs(new_opt_res - opt_res) + opt_res = new_opt_res + iters = iters + 1 + death = np.cumsum(F.flatten()[::-1]) + survivalprob = death[::-1] + llike = -opt_res + np.sum(np.log(survivalprob[survidx])) + wtd_km = km.flatten() / np.sum(km) + survivalmax = np.cumsum(wtd_km[::-1])[::-1] + llikemax = np.sum(np.log(wtd_km[uncensored])) + \ + np.sum(np.log(survivalmax[censored])) + if iters == maxiter: + warnings.warn('The EM reached the maximum number of iterations', + IterationLimitWarning) + return -2 * (llike - llikemax) + + def _ci_limits_beta(self, b0, param_num=None): + """ + Returns the difference between the log likelihood for a + parameter and some critical value. + + Parameters + ---------- + b0: float + Value of a regression parameter + param_num : int + Parameter index of b0 + """ + return self.test_beta([b0], [param_num])[0] - self.r0 + + +class emplikeAFT: + """ + + Class for estimating and conducting inference in an AFT model. + + Parameters + ---------- + + endog: nx1 array + Response variables that are subject to random censoring + + exog: nxk array + Matrix of covariates + + censors: nx1 array + array with entries 0 or 1. 0 indicates a response was + censored. + + Attributes + ---------- + nobs : float + Number of observations + endog : ndarray + Endog attay + exog : ndarray + Exogenous variable matrix + censors + Censors array but sets the max(endog) to uncensored + nvar : float + Number of exogenous variables + uncens_nobs : float + Number of uncensored observations + uncens_endog : ndarray + Uncensored response variables + uncens_exog : ndarray + Exogenous variables of the uncensored observations + + Methods + ------- + + params: + Fits model parameters + + test_beta: + Tests if beta = b0 for any vector b0. + + Notes + ----- + + The data is immediately sorted in order of increasing endogenous + variables + + The last observation is assumed to be uncensored which makes + estimation and inference possible. + """ + def __init__(self, endog, exog, censors): + self.nobs = np.shape(exog)[0] + self.endog = endog.reshape(self.nobs, 1) + self.exog = exog.reshape(self.nobs, -1) + self.censors = np.asarray(censors).reshape(self.nobs, 1) + self.nvar = self.exog.shape[1] + idx = np.lexsort((-self.censors[:, 0], self.endog[:, 0])) + self.endog = self.endog[idx] + self.exog = self.exog[idx] + self.censors = self.censors[idx] + self.censors[-1] = 1 # Sort in init, not in function + self.uncens_nobs = int(np.sum(self.censors)) + mask = self.censors.ravel().astype(bool) + self.uncens_endog = self.endog[mask, :].reshape(-1, 1) + self.uncens_exog = self.exog[mask, :] + + + def _is_tied(self, endog, censors): + """ + Indicated if an observation takes the same value as the next + ordered observation. + + Parameters + ---------- + endog : ndarray + Models endogenous variable + censors : ndarray + arrat indicating a censored array + + Returns + ------- + indic_ties : ndarray + ties[i]=1 if endog[i]==endog[i+1] and + censors[i]=censors[i+1] + """ + nobs = int(self.nobs) + endog_idx = endog[np.arange(nobs - 1)] == ( + endog[np.arange(nobs - 1) + 1]) + censors_idx = censors[np.arange(nobs - 1)] == ( + censors[np.arange(nobs - 1) + 1]) + indic_ties = endog_idx * censors_idx # Both true + return np.int_(indic_ties) + + def _km_w_ties(self, tie_indic, untied_km): + """ + Computes KM estimator value at each observation, taking into acocunt + ties in the data. + + Parameters + ---------- + tie_indic: 1d array + Indicates if the i'th observation is the same as the ith +1 + untied_km: 1d array + Km estimates at each observation assuming no ties. + """ + # TODO: Vectorize, even though it is only 1 pass through for any + # function call + num_same = 1 + idx_nums = [] + for obs_num in np.arange(int(self.nobs - 1))[::-1]: + if tie_indic[obs_num] == 1: + idx_nums.append(obs_num) + num_same = num_same + 1 + untied_km[obs_num] = untied_km[obs_num + 1] + elif tie_indic[obs_num] == 0 and num_same > 1: + idx_nums.append(max(idx_nums) + 1) + idx_nums = np.asarray(idx_nums) + untied_km[idx_nums] = untied_km[idx_nums] + num_same = 1 + idx_nums = [] + return untied_km.reshape(self.nobs, 1) + + def _make_km(self, endog, censors): + """ + + Computes the Kaplan-Meier estimate for the weights in the AFT model + + Parameters + ---------- + endog: nx1 array + Array of response variables + censors: nx1 array + Censor-indicating variable + + Returns + ------- + Kaplan Meier estimate for each observation + + Notes + ----- + + This function makes calls to _is_tied and km_w_ties to handle ties in + the data.If a censored observation and an uncensored observation has + the same value, it is assumed that the uncensored happened first. + """ + nobs = self.nobs + num = (nobs - (np.arange(nobs) + 1.)) + denom = (nobs - (np.arange(nobs) + 1.) + 1.) + km = (num / denom).reshape(nobs, 1) + km = km ** np.abs(censors - 1.) + km = np.cumprod(km) # If no ties, this is kaplan-meier + tied = self._is_tied(endog, censors) + wtd_km = self._km_w_ties(tied, km) + return (censors / wtd_km).reshape(nobs, 1) + + def fit(self): + """ + + Fits an AFT model and returns results instance + + Parameters + ---------- + None + + + Returns + ------- + Results instance. + + Notes + ----- + To avoid dividing by zero, max(endog) is assumed to be uncensored. + """ + return AFTResults(self) + + def predict(self, params, endog=None): + if endog is None: + endog = self.endog + return np.dot(endog, params) + + +class AFTResults(OptAFT): + def __init__(self, model): + self.model = model + + def params(self): + """ + + Fits an AFT model and returns parameters. + + Parameters + ---------- + None + + + Returns + ------- + Fitted params + + Notes + ----- + To avoid dividing by zero, max(endog) is assumed to be uncensored. + """ + self.model.modif_censors = np.copy(self.model.censors) + self.model.modif_censors[-1] = 1 + wts = self.model._make_km(self.model.endog, self.model.modif_censors) + res = WLS(self.model.endog, self.model.exog, wts).fit() + params = res.params + return params + + def test_beta(self, b0_vals, param_nums, ftol=10 ** - 5, maxiter=30, + print_weights=1): + """ + Returns the profile log likelihood for regression parameters + 'param_num' at 'b0_vals.' + + Parameters + ---------- + b0_vals : list + The value of parameters to be tested + param_num : list + Which parameters to be tested + maxiter : int, optional + How many iterations to use in the EM algorithm. Default is 30 + ftol : float, optional + The function tolerance for the EM optimization. + Default is 10''**''-5 + print_weights : bool + If true, returns the weights tate maximize the profile + log likelihood. Default is False + + Returns + ------- + + test_results : tuple + The log-likelihood and p-pvalue of the test. + + Notes + ----- + + The function will warn if the EM reaches the maxiter. However, when + optimizing over nuisance parameters, it is possible to reach a + maximum number of inner iterations for a specific value for the + nuisance parameters while the resultsof the function are still valid. + This usually occurs when the optimization over the nuisance parameters + selects parameter values that yield a log-likihood ratio close to + infinity. + + Examples + -------- + + >>> import statsmodels.api as sm + >>> import numpy as np + + # Test parameter is .05 in one regressor no intercept model + >>> data=sm.datasets.heart.load() + >>> y = np.log10(data.endog) + >>> x = data.exog + >>> cens = data.censors + >>> model = sm.emplike.emplikeAFT(y, x, cens) + >>> res=model.test_beta([0], [0]) + >>> res + (1.4657739632606308, 0.22601365256959183) + + #Test slope is 0 in model with intercept + + >>> data=sm.datasets.heart.load() + >>> y = np.log10(data.endog) + >>> x = data.exog + >>> cens = data.censors + >>> model = sm.emplike.emplikeAFT(y, sm.add_constant(x), cens) + >>> res = model.test_beta([0], [1]) + >>> res + (4.623487775078047, 0.031537049752572731) + """ + censors = self.model.censors + endog = self.model.endog + exog = self.model.exog + uncensored = (censors == 1).flatten() + censored = (censors == 0).flatten() + uncens_endog = endog[uncensored] + uncens_exog = exog[uncensored, :] + reg_model = OLS(uncens_endog, uncens_exog).fit() + llr, pval, new_weights = reg_model.el_test(b0_vals, param_nums, + return_weights=True) # Needs to be changed + km = self.model._make_km(endog, censors).flatten() # when merged + uncens_nobs = self.model.uncens_nobs + F = np.asarray(new_weights).reshape(uncens_nobs) + # Step 0 ^ + params = self.params() + survidx = np.where(censors == 0) + survidx = survidx[0] - np.arange(len(survidx[0])) + numcensbelow = np.int_(np.cumsum(1 - censors)) + if len(param_nums) == len(params): + llr = self._EM_test([], F=F, params=params, + param_nums=param_nums, + b0_vals=b0_vals, survidx=survidx, + uncens_nobs=uncens_nobs, + numcensbelow=numcensbelow, km=km, + uncensored=uncensored, censored=censored, + ftol=ftol, maxiter=25) + return llr, chi2.sf(llr, self.model.nvar) + else: + x0 = np.delete(params, param_nums) + try: + res = optimize.fmin(self._EM_test, x0, + (params, param_nums, b0_vals, F, survidx, + uncens_nobs, numcensbelow, km, uncensored, + censored, maxiter, ftol), full_output=1, + disp=0) + + llr = res[1] + return llr, chi2.sf(llr, len(param_nums)) + except np.linalg.LinAlgError: + return np.inf, 0 + + def ci_beta(self, param_num, beta_high, beta_low, sig=.05): + """ + Returns the confidence interval for a regression + parameter in the AFT model. + + Parameters + ---------- + param_num : int + Parameter number of interest + beta_high : float + Upper bound for the confidence interval + beta_low : float + Lower bound for the confidence interval + sig : float, optional + Significance level. Default is .05 + + Notes + ----- + If the function returns f(a) and f(b) must have different signs, + consider widening the search area by adjusting beta_low and + beta_high. + + Also note that this process is computational intensive. There + are 4 levels of optimization/solving. From outer to inner: + + 1) Solving so that llr-critical value = 0 + 2) maximizing over nuisance parameters + 3) Using EM at each value of nuisamce parameters + 4) Using the _modified_Newton optimizer at each iteration + of the EM algorithm. + + Also, for very unlikely nuisance parameters, it is possible for + the EM algorithm to not converge. This is not an indicator + that the solver did not find the correct solution. It just means + for a specific iteration of the nuisance parameters, the optimizer + was unable to converge. + + If the user desires to verify the success of the optimization, + it is recommended to test the limits using test_beta. + """ + params = self.params() + self.r0 = chi2.ppf(1 - sig, 1) + ll = optimize.brentq(self._ci_limits_beta, beta_low, + params[param_num], (param_num)) + ul = optimize.brentq(self._ci_limits_beta, + params[param_num], beta_high, (param_num)) + return ll, ul diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/emplike/api.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/emplike/api.py new file mode 100644 index 0000000000000000000000000000000000000000..6a8b5f5eb3a3da7f2fa9d030a87594ca4c9e628a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/emplike/api.py @@ -0,0 +1,13 @@ +""" +API for empirical likelihood + +""" +__all__ = [ + "DescStat", "DescStatUV", "DescStatMV", + "ELOriginRegress", "ANOVA", "emplikeAFT" +] + +from .descriptive import DescStat, DescStatUV, DescStatMV +from .originregress import ELOriginRegress +from .elanova import ANOVA +from .aft_el import emplikeAFT diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/emplike/descriptive.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/emplike/descriptive.py new file mode 100644 index 0000000000000000000000000000000000000000..501e5aebe243e2a9d63793253955d6b903e98aec --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/emplike/descriptive.py @@ -0,0 +1,1144 @@ +""" +Empirical likelihood inference on descriptive statistics + +This module conducts hypothesis tests and constructs confidence +intervals for the mean, variance, skewness, kurtosis and correlation. + +If matplotlib is installed, this module can also generate multivariate +confidence region plots as well as mean-variance contour plots. + +See _OptFuncts docstring for technical details and optimization variable +definitions. + +General References: +------------------ +Owen, A. (2001). "Empirical Likelihood." Chapman and Hall + +""" +import numpy as np +from scipy import optimize +from scipy.stats import chi2, skew, kurtosis +from statsmodels.base.optimizer import _fit_newton +import itertools +from statsmodels.graphics import utils + + +def DescStat(endog): + """ + Returns an instance to conduct inference on descriptive statistics + via empirical likelihood. See DescStatUV and DescStatMV for more + information. + + Parameters + ---------- + endog : ndarray + Array of data + + Returns : DescStat instance + If k=1, the function returns a univariate instance, DescStatUV. + If k>1, the function returns a multivariate instance, DescStatMV. + """ + if endog.ndim == 1: + endog = endog.reshape(len(endog), 1) + if endog.shape[1] == 1: + return DescStatUV(endog) + if endog.shape[1] > 1: + return DescStatMV(endog) + + +class _OptFuncts: + """ + A class that holds functions that are optimized/solved. + + The general setup of the class is simple. Any method that starts with + _opt_ creates a vector of estimating equations named est_vect such that + np.dot(p, (est_vect))=0 where p is the weight on each + observation as a 1 x n array and est_vect is n x k. Then _modif_Newton is + called to determine the optimal p by solving for the Lagrange multiplier + (eta) in the profile likelihood maximization problem. In the presence + of nuisance parameters, _opt_ functions are optimized over to profile + out the nuisance parameters. + + Any method starting with _ci_limits calculates the log likelihood + ratio for a specific value of a parameter and then subtracts a + pre-specified critical value. This is solved so that llr - crit = 0. + """ + + def __init__(self, endog): + pass + + def _log_star(self, eta, est_vect, weights, nobs): + """ + Transforms the log of observation probabilities in terms of the + Lagrange multiplier to the log 'star' of the probabilities. + + Parameters + ---------- + eta : float + Lagrange multiplier + + est_vect : ndarray (n,k) + Estimating equations vector + + wts : nx1 array + Observation weights + + Returns + ------ + data_star : ndarray + The weighted logstar of the estimting equations + + Notes + ----- + This function is only a placeholder for the _fit_Newton. + The function value is not used in optimization and the optimal value + is disregarded when computing the log likelihood ratio. + """ + data_star = np.log(weights) + (np.sum(weights) +\ + np.dot(est_vect, eta)) + idx = data_star < 1. / nobs + not_idx = ~idx + nx = nobs * data_star[idx] + data_star[idx] = np.log(1. / nobs) - 1.5 + nx * (2. - nx / 2) + data_star[not_idx] = np.log(data_star[not_idx]) + return data_star + + def _hess(self, eta, est_vect, weights, nobs): + """ + Calculates the hessian of a weighted empirical likelihood + problem. + + Parameters + ---------- + eta : ndarray, (1,m) + Lagrange multiplier in the profile likelihood maximization + + est_vect : ndarray (n,k) + Estimating equations vector + + weights : 1darray + Observation weights + + Returns + ------- + hess : m x m array + Weighted hessian used in _wtd_modif_newton + """ + #eta = np.squeeze(eta) + data_star_doub_prime = np.sum(weights) + np.dot(est_vect, eta) + idx = data_star_doub_prime < 1. / nobs + not_idx = ~idx + data_star_doub_prime[idx] = - nobs ** 2 + data_star_doub_prime[not_idx] = - (data_star_doub_prime[not_idx]) ** -2 + wtd_dsdp = weights * data_star_doub_prime + return np.dot(est_vect.T, wtd_dsdp[:, None] * est_vect) + + def _grad(self, eta, est_vect, weights, nobs): + """ + Calculates the gradient of a weighted empirical likelihood + problem + + Parameters + ---------- + eta : ndarray, (1,m) + Lagrange multiplier in the profile likelihood maximization + + est_vect : ndarray, (n,k) + Estimating equations vector + + weights : 1darray + Observation weights + + Returns + ------- + gradient : ndarray (m,1) + The gradient used in _wtd_modif_newton + """ + #eta = np.squeeze(eta) + data_star_prime = np.sum(weights) + np.dot(est_vect, eta) + idx = data_star_prime < 1. / nobs + not_idx = ~idx + data_star_prime[idx] = nobs * (2 - nobs * data_star_prime[idx]) + data_star_prime[not_idx] = 1. / data_star_prime[not_idx] + return np.dot(weights * data_star_prime, est_vect) + + def _modif_newton(self, eta, est_vect, weights): + """ + Modified Newton's method for maximizing the log 'star' equation. This + function calls _fit_newton to find the optimal values of eta. + + Parameters + ---------- + eta : ndarray, (1,m) + Lagrange multiplier in the profile likelihood maximization + + est_vect : ndarray, (n,k) + Estimating equations vector + + weights : 1darray + Observation weights + + Returns + ------- + params : 1xm array + Lagrange multiplier that maximizes the log-likelihood + """ + nobs = len(est_vect) + f = lambda x0: - np.sum(self._log_star(x0, est_vect, weights, nobs)) + grad = lambda x0: - self._grad(x0, est_vect, weights, nobs) + hess = lambda x0: - self._hess(x0, est_vect, weights, nobs) + kwds = {'tol': 1e-8} + eta = eta.squeeze() + res = _fit_newton(f, grad, eta, (), kwds, hess=hess, maxiter=50, \ + disp=0) + return res[0] + + def _find_eta(self, eta): + """ + Finding the root of sum(xi-h0)/(1+eta(xi-mu)) solves for + eta when computing ELR for univariate mean. + + Parameters + ---------- + eta : float + Lagrange multiplier in the empirical likelihood maximization + + Returns + ------- + llr : float + n times the log likelihood value for a given value of eta + """ + return np.sum((self.endog - self.mu0) / \ + (1. + eta * (self.endog - self.mu0))) + + def _ci_limits_mu(self, mu): + """ + Calculates the difference between the log likelihood of mu_test and a + specified critical value. + + Parameters + ---------- + mu : float + Hypothesized value of the mean. + + Returns + ------- + diff : float + The difference between the log likelihood value of mu0 and + a specified value. + """ + return self.test_mean(mu)[0] - self.r0 + + def _find_gamma(self, gamma): + """ + Finds gamma that satisfies + sum(log(n * w(gamma))) - log(r0) = 0 + + Used for confidence intervals for the mean + + Parameters + ---------- + gamma : float + Lagrange multiplier when computing confidence interval + + Returns + ------- + diff : float + The difference between the log-liklihood when the Lagrange + multiplier is gamma and a pre-specified value + """ + denom = np.sum((self.endog - gamma) ** -1) + new_weights = (self.endog - gamma) ** -1 / denom + return -2 * np.sum(np.log(self.nobs * new_weights)) - \ + self.r0 + + def _opt_var(self, nuisance_mu, pval=False): + """ + This is the function to be optimized over a nuisance mean parameter + to determine the likelihood ratio for the variance + + Parameters + ---------- + nuisance_mu : float + Value of a nuisance mean parameter + + Returns + ------- + llr : float + Log likelihood of a pre-specified variance holding the nuisance + parameter constant + """ + endog = self.endog + nobs = self.nobs + sig_data = ((endog - nuisance_mu) ** 2 \ + - self.sig2_0) + mu_data = (endog - nuisance_mu) + est_vect = np.column_stack((mu_data, sig_data)) + eta_star = self._modif_newton(np.array([1. / nobs, + 1. / nobs]), est_vect, + np.ones(nobs) * (1. / nobs)) + + denom = 1 + np.dot(eta_star, est_vect.T) + self.new_weights = 1. / nobs * 1. / denom + llr = np.sum(np.log(nobs * self.new_weights)) + if pval: # Used for contour plotting + return chi2.sf(-2 * llr, 1) + return -2 * llr + + def _ci_limits_var(self, var): + """ + Used to determine the confidence intervals for the variance. + It calls test_var and when called by an optimizer, + finds the value of sig2_0 that is chi2.ppf(significance-level) + + Parameters + ---------- + var_test : float + Hypothesized value of the variance + + Returns + ------- + diff : float + The difference between the log likelihood ratio at var_test and a + pre-specified value. + """ + return self.test_var(var)[0] - self.r0 + + def _opt_skew(self, nuis_params): + """ + Called by test_skew. This function is optimized over + nuisance parameters mu and sigma + + Parameters + ---------- + nuis_params : 1darray + An array with a nuisance mean and variance parameter + + Returns + ------- + llr : float + The log likelihood ratio of a pre-specified skewness holding + the nuisance parameters constant. + """ + endog = self.endog + nobs = self.nobs + mu_data = endog - nuis_params[0] + sig_data = ((endog - nuis_params[0]) ** 2) - nuis_params[1] + skew_data = (((endog - nuis_params[0]) ** 3) / + (nuis_params[1] ** 1.5)) - self.skew0 + est_vect = np.column_stack((mu_data, sig_data, skew_data)) + eta_star = self._modif_newton(np.array([1. / nobs, + 1. / nobs, + 1. / nobs]), est_vect, + np.ones(nobs) * (1. / nobs)) + denom = 1. + np.dot(eta_star, est_vect.T) + self.new_weights = 1. / nobs * 1. / denom + llr = np.sum(np.log(nobs * self.new_weights)) + return -2 * llr + + def _opt_kurt(self, nuis_params): + """ + Called by test_kurt. This function is optimized over + nuisance parameters mu and sigma + + Parameters + ---------- + nuis_params : 1darray + An array with a nuisance mean and variance parameter + + Returns + ------- + llr : float + The log likelihood ratio of a pre-speified kurtosis holding the + nuisance parameters constant + """ + endog = self.endog + nobs = self.nobs + mu_data = endog - nuis_params[0] + sig_data = ((endog - nuis_params[0]) ** 2) - nuis_params[1] + kurt_data = ((((endog - nuis_params[0]) ** 4) / \ + (nuis_params[1] ** 2)) - 3) - self.kurt0 + est_vect = np.column_stack((mu_data, sig_data, kurt_data)) + eta_star = self._modif_newton(np.array([1. / nobs, + 1. / nobs, + 1. / nobs]), est_vect, + np.ones(nobs) * (1. / nobs)) + denom = 1 + np.dot(eta_star, est_vect.T) + self.new_weights = 1. / nobs * 1. / denom + llr = np.sum(np.log(nobs * self.new_weights)) + return -2 * llr + + def _opt_skew_kurt(self, nuis_params): + """ + Called by test_joint_skew_kurt. This function is optimized over + nuisance parameters mu and sigma + + Parameters + ---------- + nuis_params : 1darray + An array with a nuisance mean and variance parameter + + Returns + ------ + llr : float + The log likelihood ratio of a pre-speified skewness and + kurtosis holding the nuisance parameters constant. + """ + endog = self.endog + nobs = self.nobs + mu_data = endog - nuis_params[0] + sig_data = ((endog - nuis_params[0]) ** 2) - nuis_params[1] + skew_data = (((endog - nuis_params[0]) ** 3) / \ + (nuis_params[1] ** 1.5)) - self.skew0 + kurt_data = ((((endog - nuis_params[0]) ** 4) / \ + (nuis_params[1] ** 2)) - 3) - self.kurt0 + est_vect = np.column_stack((mu_data, sig_data, skew_data, kurt_data)) + eta_star = self._modif_newton(np.array([1. / nobs, + 1. / nobs, + 1. / nobs, + 1. / nobs]), est_vect, + np.ones(nobs) * (1. / nobs)) + denom = 1. + np.dot(eta_star, est_vect.T) + self.new_weights = 1. / nobs * 1. / denom + llr = np.sum(np.log(nobs * self.new_weights)) + return -2 * llr + + def _ci_limits_skew(self, skew): + """ + Parameters + ---------- + skew0 : float + Hypothesized value of skewness + + Returns + ------- + diff : float + The difference between the log likelihood ratio at skew and a + pre-specified value. + """ + return self.test_skew(skew)[0] - self.r0 + + def _ci_limits_kurt(self, kurt): + """ + Parameters + ---------- + skew0 : float + Hypothesized value of kurtosis + + Returns + ------- + diff : float + The difference between the log likelihood ratio at kurt and a + pre-specified value. + """ + return self.test_kurt(kurt)[0] - self.r0 + + def _opt_correl(self, nuis_params, corr0, endog, nobs, x0, weights0): + """ + Parameters + ---------- + nuis_params : 1darray + Array containing two nuisance means and two nuisance variances + + Returns + ------- + llr : float + The log-likelihood of the correlation coefficient holding nuisance + parameters constant + """ + mu1_data, mu2_data = (endog - nuis_params[::2]).T + sig1_data = mu1_data ** 2 - nuis_params[1] + sig2_data = mu2_data ** 2 - nuis_params[3] + correl_data = ((mu1_data * mu2_data) - corr0 * + (nuis_params[1] * nuis_params[3]) ** .5) + est_vect = np.column_stack((mu1_data, sig1_data, + mu2_data, sig2_data, correl_data)) + eta_star = self._modif_newton(x0, est_vect, weights0) + denom = 1. + np.dot(est_vect, eta_star) + self.new_weights = 1. / nobs * 1. / denom + llr = np.sum(np.log(nobs * self.new_weights)) + return -2 * llr + + def _ci_limits_corr(self, corr): + return self.test_corr(corr)[0] - self.r0 + + +class DescStatUV(_OptFuncts): + """ + A class to compute confidence intervals and hypothesis tests involving + mean, variance, kurtosis and skewness of a univariate random variable. + + Parameters + ---------- + endog : 1darray + Data to be analyzed + + Attributes + ---------- + endog : 1darray + Data to be analyzed + + nobs : float + Number of observations + """ + + def __init__(self, endog): + self.endog = np.squeeze(endog) + self.nobs = endog.shape[0] + + def test_mean(self, mu0, return_weights=False): + """ + Returns - 2 x log-likelihood ratio, p-value and weights + for a hypothesis test of the mean. + + Parameters + ---------- + mu0 : float + Mean value to be tested + + return_weights : bool + If return_weights is True the function returns + the weights of the observations under the null hypothesis. + Default is False + + Returns + ------- + test_results : tuple + The log-likelihood ratio and p-value of mu0 + """ + self.mu0 = mu0 + endog = self.endog + nobs = self.nobs + eta_min = (1. - (1. / nobs)) / (self.mu0 - max(endog)) + eta_max = (1. - (1. / nobs)) / (self.mu0 - min(endog)) + eta_star = optimize.brentq(self._find_eta, eta_min, eta_max) + new_weights = (1. / nobs) * 1. / (1. + eta_star * (endog - self.mu0)) + llr = -2 * np.sum(np.log(nobs * new_weights)) + if return_weights: + return llr, chi2.sf(llr, 1), new_weights + else: + return llr, chi2.sf(llr, 1) + + def ci_mean(self, sig=.05, method='gamma', epsilon=10 ** -8, + gamma_low=-10 ** 10, gamma_high=10 ** 10): + """ + Returns the confidence interval for the mean. + + Parameters + ---------- + sig : float + significance level. Default is .05 + + method : str + Root finding method, Can be 'nested-brent' or + 'gamma'. Default is 'gamma' + + 'gamma' Tries to solve for the gamma parameter in the + Lagrange (see Owen pg 22) and then determine the weights. + + 'nested brent' uses brents method to find the confidence + intervals but must maximize the likelihood ratio on every + iteration. + + gamma is generally much faster. If the optimizations does not + converge, try expanding the gamma_high and gamma_low + variable. + + gamma_low : float + Lower bound for gamma when finding lower limit. + If function returns f(a) and f(b) must have different signs, + consider lowering gamma_low. + + gamma_high : float + Upper bound for gamma when finding upper limit. + If function returns f(a) and f(b) must have different signs, + consider raising gamma_high. + + epsilon : float + When using 'nested-brent', amount to decrease (increase) + from the maximum (minimum) of the data when + starting the search. This is to protect against the + likelihood ratio being zero at the maximum (minimum) + value of the data. If data is very small in absolute value + (<10 ``**`` -6) consider shrinking epsilon + + When using 'gamma', amount to decrease (increase) the + minimum (maximum) by to start the search for gamma. + If function returns f(a) and f(b) must have different signs, + consider lowering epsilon. + + Returns + ------- + Interval : tuple + Confidence interval for the mean + """ + endog = self.endog + sig = 1 - sig + if method == 'nested-brent': + self.r0 = chi2.ppf(sig, 1) + middle = np.mean(endog) + epsilon_u = (max(endog) - np.mean(endog)) * epsilon + epsilon_l = (np.mean(endog) - min(endog)) * epsilon + ulim = optimize.brentq(self._ci_limits_mu, middle, + max(endog) - epsilon_u) + llim = optimize.brentq(self._ci_limits_mu, middle, + min(endog) + epsilon_l) + return llim, ulim + + if method == 'gamma': + self.r0 = chi2.ppf(sig, 1) + gamma_star_l = optimize.brentq(self._find_gamma, gamma_low, + min(endog) - epsilon) + gamma_star_u = optimize.brentq(self._find_gamma, \ + max(endog) + epsilon, gamma_high) + weights_low = ((endog - gamma_star_l) ** -1) / \ + np.sum((endog - gamma_star_l) ** -1) + weights_high = ((endog - gamma_star_u) ** -1) / \ + np.sum((endog - gamma_star_u) ** -1) + mu_low = np.sum(weights_low * endog) + mu_high = np.sum(weights_high * endog) + return mu_low, mu_high + + def test_var(self, sig2_0, return_weights=False): + """ + Returns -2 x log-likelihood ratio and the p-value for the + hypothesized variance + + Parameters + ---------- + sig2_0 : float + Hypothesized variance to be tested + + return_weights : bool + If True, returns the weights that maximize the + likelihood of observing sig2_0. Default is False + + Returns + ------- + test_results : tuple + The log-likelihood ratio and the p_value of sig2_0 + + Examples + -------- + >>> import numpy as np + >>> import statsmodels.api as sm + >>> random_numbers = np.random.standard_normal(1000)*100 + >>> el_analysis = sm.emplike.DescStat(random_numbers) + >>> hyp_test = el_analysis.test_var(9500) + """ + self.sig2_0 = sig2_0 + mu_max = max(self.endog) + mu_min = min(self.endog) + llr = optimize.fminbound(self._opt_var, mu_min, mu_max, \ + full_output=1)[1] + p_val = chi2.sf(llr, 1) + if return_weights: + return llr, p_val, self.new_weights.T + else: + return llr, p_val + + def ci_var(self, lower_bound=None, upper_bound=None, sig=.05): + """ + Returns the confidence interval for the variance. + + Parameters + ---------- + lower_bound : float + The minimum value the lower confidence interval can + take. The p-value from test_var(lower_bound) must be lower + than 1 - significance level. Default is .99 confidence + limit assuming normality + + upper_bound : float + The maximum value the upper confidence interval + can take. The p-value from test_var(upper_bound) must be lower + than 1 - significance level. Default is .99 confidence + limit assuming normality + + sig : float + The significance level. Default is .05 + + Returns + ------- + Interval : tuple + Confidence interval for the variance + + Examples + -------- + >>> import numpy as np + >>> import statsmodels.api as sm + >>> random_numbers = np.random.standard_normal(100) + >>> el_analysis = sm.emplike.DescStat(random_numbers) + >>> el_analysis.ci_var() + (0.7539322567470305, 1.229998852496268) + >>> el_analysis.ci_var(.5, 2) + (0.7539322567469926, 1.2299988524962664) + + Notes + ----- + If the function returns the error f(a) and f(b) must have + different signs, consider lowering lower_bound and raising + upper_bound. + """ + endog = self.endog + if upper_bound is None: + upper_bound = ((self.nobs - 1) * endog.var()) / \ + (chi2.ppf(.0001, self.nobs - 1)) + if lower_bound is None: + lower_bound = ((self.nobs - 1) * endog.var()) / \ + (chi2.ppf(.9999, self.nobs - 1)) + self.r0 = chi2.ppf(1 - sig, 1) + llim = optimize.brentq(self._ci_limits_var, lower_bound, endog.var()) + ulim = optimize.brentq(self._ci_limits_var, endog.var(), upper_bound) + return llim, ulim + + def plot_contour(self, mu_low, mu_high, var_low, var_high, mu_step, + var_step, + levs=[.2, .1, .05, .01, .001]): + """ + Returns a plot of the confidence region for a univariate + mean and variance. + + Parameters + ---------- + mu_low : float + Lowest value of the mean to plot + + mu_high : float + Highest value of the mean to plot + + var_low : float + Lowest value of the variance to plot + + var_high : float + Highest value of the variance to plot + + mu_step : float + Increments to evaluate the mean + + var_step : float + Increments to evaluate the mean + + levs : list + Which values of significance the contour lines will be drawn. + Default is [.2, .1, .05, .01, .001] + + Returns + ------- + Figure + The contour plot + """ + fig, ax = utils.create_mpl_ax() + ax.set_ylabel('Variance') + ax.set_xlabel('Mean') + mu_vect = list(np.arange(mu_low, mu_high, mu_step)) + var_vect = list(np.arange(var_low, var_high, var_step)) + z = [] + for sig0 in var_vect: + self.sig2_0 = sig0 + for mu0 in mu_vect: + z.append(self._opt_var(mu0, pval=True)) + z = np.asarray(z).reshape(len(var_vect), len(mu_vect)) + ax.contour(mu_vect, var_vect, z, levels=levs) + return fig + + def test_skew(self, skew0, return_weights=False): + """ + Returns -2 x log-likelihood and p-value for the hypothesized + skewness. + + Parameters + ---------- + skew0 : float + Skewness value to be tested + + return_weights : bool + If True, function also returns the weights that + maximize the likelihood ratio. Default is False. + + Returns + ------- + test_results : tuple + The log-likelihood ratio and p_value of skew0 + """ + self.skew0 = skew0 + start_nuisance = np.array([self.endog.mean(), + self.endog.var()]) + + llr = optimize.fmin_powell(self._opt_skew, start_nuisance, + full_output=1, disp=0)[1] + p_val = chi2.sf(llr, 1) + if return_weights: + return llr, p_val, self.new_weights.T + return llr, p_val + + def test_kurt(self, kurt0, return_weights=False): + """ + Returns -2 x log-likelihood and the p-value for the hypothesized + kurtosis. + + Parameters + ---------- + kurt0 : float + Kurtosis value to be tested + + return_weights : bool + If True, function also returns the weights that + maximize the likelihood ratio. Default is False. + + Returns + ------- + test_results : tuple + The log-likelihood ratio and p-value of kurt0 + """ + self.kurt0 = kurt0 + start_nuisance = np.array([self.endog.mean(), + self.endog.var()]) + + llr = optimize.fmin_powell(self._opt_kurt, start_nuisance, + full_output=1, disp=0)[1] + p_val = chi2.sf(llr, 1) + if return_weights: + return llr, p_val, self.new_weights.T + return llr, p_val + + def test_joint_skew_kurt(self, skew0, kurt0, return_weights=False): + """ + Returns - 2 x log-likelihood and the p-value for the joint + hypothesis test for skewness and kurtosis + + Parameters + ---------- + skew0 : float + Skewness value to be tested + kurt0 : float + Kurtosis value to be tested + + return_weights : bool + If True, function also returns the weights that + maximize the likelihood ratio. Default is False. + + Returns + ------- + test_results : tuple + The log-likelihood ratio and p-value of the joint hypothesis test. + """ + self.skew0 = skew0 + self.kurt0 = kurt0 + start_nuisance = np.array([self.endog.mean(), + self.endog.var()]) + + llr = optimize.fmin_powell(self._opt_skew_kurt, start_nuisance, + full_output=1, disp=0)[1] + p_val = chi2.sf(llr, 2) + if return_weights: + return llr, p_val, self.new_weights.T + return llr, p_val + + def ci_skew(self, sig=.05, upper_bound=None, lower_bound=None): + """ + Returns the confidence interval for skewness. + + Parameters + ---------- + sig : float + The significance level. Default is .05 + + upper_bound : float + Maximum value of skewness the upper limit can be. + Default is .99 confidence limit assuming normality. + + lower_bound : float + Minimum value of skewness the lower limit can be. + Default is .99 confidence level assuming normality. + + Returns + ------- + Interval : tuple + Confidence interval for the skewness + + Notes + ----- + If function returns f(a) and f(b) must have different signs, consider + expanding lower and upper bounds + """ + nobs = self.nobs + endog = self.endog + if upper_bound is None: + upper_bound = skew(endog) + \ + 2.5 * ((6. * nobs * (nobs - 1.)) / \ + ((nobs - 2.) * (nobs + 1.) * \ + (nobs + 3.))) ** .5 + if lower_bound is None: + lower_bound = skew(endog) - \ + 2.5 * ((6. * nobs * (nobs - 1.)) / \ + ((nobs - 2.) * (nobs + 1.) * \ + (nobs + 3.))) ** .5 + self.r0 = chi2.ppf(1 - sig, 1) + llim = optimize.brentq(self._ci_limits_skew, lower_bound, skew(endog)) + ulim = optimize.brentq(self._ci_limits_skew, skew(endog), upper_bound) + return llim, ulim + + def ci_kurt(self, sig=.05, upper_bound=None, lower_bound=None): + """ + Returns the confidence interval for kurtosis. + + Parameters + ---------- + + sig : float + The significance level. Default is .05 + + upper_bound : float + Maximum value of kurtosis the upper limit can be. + Default is .99 confidence limit assuming normality. + + lower_bound : float + Minimum value of kurtosis the lower limit can be. + Default is .99 confidence limit assuming normality. + + Returns + ------- + Interval : tuple + Lower and upper confidence limit + + Notes + ----- + For small n, upper_bound and lower_bound may have to be + provided by the user. Consider using test_kurt to find + values close to the desired significance level. + + If function returns f(a) and f(b) must have different signs, consider + expanding the bounds. + """ + endog = self.endog + nobs = self.nobs + if upper_bound is None: + upper_bound = kurtosis(endog) + \ + (2.5 * (2. * ((6. * nobs * (nobs - 1.)) / \ + ((nobs - 2.) * (nobs + 1.) * \ + (nobs + 3.))) ** .5) * \ + (((nobs ** 2.) - 1.) / ((nobs - 3.) *\ + (nobs + 5.))) ** .5) + if lower_bound is None: + lower_bound = kurtosis(endog) - \ + (2.5 * (2. * ((6. * nobs * (nobs - 1.)) / \ + ((nobs - 2.) * (nobs + 1.) * \ + (nobs + 3.))) ** .5) * \ + (((nobs ** 2.) - 1.) / ((nobs - 3.) *\ + (nobs + 5.))) ** .5) + self.r0 = chi2.ppf(1 - sig, 1) + llim = optimize.brentq(self._ci_limits_kurt, lower_bound, \ + kurtosis(endog)) + ulim = optimize.brentq(self._ci_limits_kurt, kurtosis(endog), \ + upper_bound) + return llim, ulim + + +class DescStatMV(_OptFuncts): + """ + A class for conducting inference on multivariate means and correlation. + + Parameters + ---------- + endog : ndarray + Data to be analyzed + + Attributes + ---------- + endog : ndarray + Data to be analyzed + + nobs : float + Number of observations + """ + + def __init__(self, endog): + self.endog = endog + self.nobs = endog.shape[0] + + def mv_test_mean(self, mu_array, return_weights=False): + """ + Returns -2 x log likelihood and the p-value + for a multivariate hypothesis test of the mean + + Parameters + ---------- + mu_array : 1d array + Hypothesized values for the mean. Must have same number of + elements as columns in endog + + return_weights : bool + If True, returns the weights that maximize the + likelihood of mu_array. Default is False. + + Returns + ------- + test_results : tuple + The log-likelihood ratio and p-value for mu_array + """ + endog = self.endog + nobs = self.nobs + if len(mu_array) != endog.shape[1]: + raise ValueError('mu_array must have the same number of ' + 'elements as the columns of the data.') + mu_array = mu_array.reshape(1, endog.shape[1]) + means = np.ones((endog.shape[0], endog.shape[1])) + means = mu_array * means + est_vect = endog - means + start_vals = 1. / nobs * np.ones(endog.shape[1]) + eta_star = self._modif_newton(start_vals, est_vect, + np.ones(nobs) * (1. / nobs)) + denom = 1 + np.dot(eta_star, est_vect.T) + self.new_weights = 1 / nobs * 1 / denom + llr = -2 * np.sum(np.log(nobs * self.new_weights)) + p_val = chi2.sf(llr, mu_array.shape[1]) + if return_weights: + return llr, p_val, self.new_weights.T + else: + return llr, p_val + + def mv_mean_contour(self, mu1_low, mu1_upp, mu2_low, mu2_upp, step1, step2, + levs=(.001, .01, .05, .1, .2), var1_name=None, + var2_name=None, plot_dta=False): + """ + Creates a confidence region plot for the mean of bivariate data + + Parameters + ---------- + m1_low : float + Minimum value of the mean for variable 1 + m1_upp : float + Maximum value of the mean for variable 1 + mu2_low : float + Minimum value of the mean for variable 2 + mu2_upp : float + Maximum value of the mean for variable 2 + step1 : float + Increment of evaluations for variable 1 + step2 : float + Increment of evaluations for variable 2 + levs : list + Levels to be drawn on the contour plot. + Default = (.001, .01, .05, .1, .2) + plot_dta : bool + If True, makes a scatter plot of the data on + top of the contour plot. Defaultis False. + var1_name : str + Name of variable 1 to be plotted on the x-axis + var2_name : str + Name of variable 2 to be plotted on the y-axis + + Notes + ----- + The smaller the step size, the more accurate the intervals + will be + + If the function returns optimization failed, consider narrowing + the boundaries of the plot + + Examples + -------- + >>> import statsmodels.api as sm + >>> two_rvs = np.random.standard_normal((20,2)) + >>> el_analysis = sm.emplike.DescStat(two_rvs) + >>> contourp = el_analysis.mv_mean_contour(-2, 2, -2, 2, .1, .1) + >>> contourp.show() + """ + if self.endog.shape[1] != 2: + raise ValueError('Data must contain exactly two variables') + fig, ax = utils.create_mpl_ax() + if var2_name is None: + ax.set_ylabel('Variable 2') + else: + ax.set_ylabel(var2_name) + if var1_name is None: + ax.set_xlabel('Variable 1') + else: + ax.set_xlabel(var1_name) + x = np.arange(mu1_low, mu1_upp, step1) + y = np.arange(mu2_low, mu2_upp, step2) + pairs = itertools.product(x, y) + z = [] + for i in pairs: + z.append(self.mv_test_mean(np.asarray(i))[0]) + X, Y = np.meshgrid(x, y) + z = np.asarray(z) + z = z.reshape(X.shape[1], Y.shape[0]) + ax.contour(x, y, z.T, levels=levs) + if plot_dta: + ax.plot(self.endog[:, 0], self.endog[:, 1], 'bo') + return fig + + def test_corr(self, corr0, return_weights=0): + """ + Returns -2 x log-likelihood ratio and p-value for the + correlation coefficient between 2 variables + + Parameters + ---------- + corr0 : float + Hypothesized value to be tested + + return_weights : bool + If true, returns the weights that maximize + the log-likelihood at the hypothesized value + """ + nobs = self.nobs + endog = self.endog + if endog.shape[1] != 2: + raise NotImplementedError('Correlation matrix not yet implemented') + nuis0 = np.array([endog[:, 0].mean(), + endog[:, 0].var(), + endog[:, 1].mean(), + endog[:, 1].var()]) + + x0 = np.zeros(5) + weights0 = np.array([1. / nobs] * int(nobs)) + args = (corr0, endog, nobs, x0, weights0) + llr = optimize.fmin(self._opt_correl, nuis0, args=args, + full_output=1, disp=0)[1] + p_val = chi2.sf(llr, 1) + if return_weights: + return llr, p_val, self.new_weights.T + return llr, p_val + + def ci_corr(self, sig=.05, upper_bound=None, lower_bound=None): + """ + Returns the confidence intervals for the correlation coefficient + + Parameters + ---------- + sig : float + The significance level. Default is .05 + + upper_bound : float + Maximum value the upper confidence limit can be. + Default is 99% confidence limit assuming normality. + + lower_bound : float + Minimum value the lower confidence limit can be. + Default is 99% confidence limit assuming normality. + + Returns + ------- + interval : tuple + Confidence interval for the correlation + """ + endog = self.endog + nobs = self.nobs + self.r0 = chi2.ppf(1 - sig, 1) + point_est = np.corrcoef(endog[:, 0], endog[:, 1])[0, 1] + if upper_bound is None: + upper_bound = min(.999, point_est + \ + 2.5 * ((1. - point_est ** 2.) / \ + (nobs - 2.)) ** .5) + + if lower_bound is None: + lower_bound = max(- .999, point_est - \ + 2.5 * (np.sqrt((1. - point_est ** 2.) / \ + (nobs - 2.)))) + + llim = optimize.brenth(self._ci_limits_corr, lower_bound, point_est) + ulim = optimize.brenth(self._ci_limits_corr, point_est, upper_bound) + return llim, ulim diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/emplike/elanova.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/emplike/elanova.py new file mode 100644 index 0000000000000000000000000000000000000000..7783ae31220ea14b7f28fe3929962d2ec39c8699 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/emplike/elanova.py @@ -0,0 +1,121 @@ +""" +This script contains empirical likelihood ANOVA. + +Currently the script only contains one feature that allows the user to compare +means of multiple groups. + +General References +------------------ + +Owen, A. B. (2001). Empirical Likelihood. Chapman and Hall. +""" +import numpy as np +from .descriptive import _OptFuncts +from scipy import optimize +from scipy.stats import chi2 + + +class _ANOVAOpt(_OptFuncts): + """ + + Class containing functions that are optimized over when + conducting ANOVA. + """ + def _opt_common_mu(self, mu): + """ + Optimizes the likelihood under the null hypothesis that all groups have + mean mu. + + Parameters + ---------- + mu : float + The common mean. + + Returns + ------- + llr : float + -2 times the llr ratio, which is the test statistic. + """ + nobs = self.nobs + endog = self.endog + num_groups = self.num_groups + endog_asarray = np.zeros((nobs, num_groups)) + obs_num = 0 + for arr_num in range(len(endog)): + new_obs_num = obs_num + len(endog[arr_num]) + endog_asarray[obs_num: new_obs_num, arr_num] = endog[arr_num] - \ + mu + obs_num = new_obs_num + est_vect = endog_asarray + wts = np.ones(est_vect.shape[0]) * (1. / (est_vect.shape[0])) + eta_star = self._modif_newton(np.zeros(num_groups), est_vect, wts) + denom = 1. + np.dot(eta_star, est_vect.T) + self.new_weights = 1. / nobs * 1. / denom + llr = np.sum(np.log(nobs * self.new_weights)) + return -2 * llr + + +class ANOVA(_ANOVAOpt): + """ + A class for ANOVA and comparing means. + + Parameters + ---------- + + endog : list of arrays + endog should be a list containing 1 dimensional arrays. Each array + is the data collected from a certain group. + """ + + def __init__(self, endog): + self.endog = endog + self.num_groups = len(self.endog) + self.nobs = 0 + for i in self.endog: + self.nobs = self.nobs + len(i) + + def compute_ANOVA(self, mu=None, mu_start=0, return_weights=0): + """ + Returns -2 log likelihood, the pvalue and the maximum likelihood + estimate for a common mean. + + Parameters + ---------- + + mu : float + If a mu is specified, ANOVA is conducted with mu as the + common mean. Otherwise, the common mean is the maximum + empirical likelihood estimate of the common mean. + Default is None. + + mu_start : float + Starting value for commean mean if specific mu is not specified. + Default = 0. + + return_weights : bool + if TRUE, returns the weights on observations that maximize the + likelihood. Default is FALSE. + + Returns + ------- + + res: tuple + The log-likelihood, p-value and estimate for the common mean. + """ + if mu is not None: + llr = self._opt_common_mu(mu) + pval = 1 - chi2.cdf(llr, self.num_groups - 1) + if return_weights: + return llr, pval, mu, self.new_weights + else: + return llr, pval, mu + else: + res = optimize.fmin_powell(self._opt_common_mu, mu_start, + full_output=1, disp=False) + llr = res[1] + mu_common = float(np.squeeze(res[0])) + pval = 1 - chi2.cdf(llr, self.num_groups - 1) + if return_weights: + return llr, pval, mu_common, self.new_weights + else: + return llr, pval, mu_common diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/emplike/elregress.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/emplike/elregress.py new file mode 100644 index 0000000000000000000000000000000000000000..58113bf4646a80f5cd42a9171a318b12b86dd4e5 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/emplike/elregress.py @@ -0,0 +1,87 @@ +""" +Empirical Likelihood Linear Regression Inference + +The script contains the function that is optimized over nuisance parameters to + conduct inference on linear regression parameters. It is called by eltest +in OLSResults. + + +General References +----------------- + +Owen, A.B.(2001). Empirical Likelihood. Chapman and Hall + +""" +import numpy as np +from statsmodels.emplike.descriptive import _OptFuncts + + + +class _ELRegOpts(_OptFuncts): + """ + + A class that holds functions to be optimized over when conducting + hypothesis tests and calculating confidence intervals. + + Parameters + ---------- + + OLSResults : Results instance + A fitted OLS result. + """ + def __init__(self): + pass + + def _opt_nuis_regress(self, nuisance_params, param_nums=None, + endog=None, exog=None, + nobs=None, nvar=None, params=None, b0_vals=None, + stochastic_exog=None): + """ + A function that is optimized over nuisance parameters to conduct a + hypothesis test for the parameters of interest. + + Parameters + ---------- + nuisance_params: 1darray + Parameters to be optimized over. + + Returns + ------- + llr : float + -2 x the log-likelihood of the nuisance parameters and the + hypothesized value of the parameter(s) of interest. + """ + params[param_nums] = b0_vals + nuis_param_index = np.int_(np.delete(np.arange(nvar), + param_nums)) + params[nuis_param_index] = nuisance_params + new_params = params.reshape(nvar, 1) + self.new_params = new_params + est_vect = exog * \ + (endog - np.squeeze(np.dot(exog, new_params))).reshape(int(nobs), 1) + if not stochastic_exog: + exog_means = np.mean(exog, axis=0)[1:] + exog_mom2 = (np.sum(exog * exog, axis=0))[1:]\ + / nobs + mean_est_vect = exog[:, 1:] - exog_means + mom2_est_vect = (exog * exog)[:, 1:] - exog_mom2 + regressor_est_vect = np.concatenate((mean_est_vect, mom2_est_vect), + axis=1) + est_vect = np.concatenate((est_vect, regressor_est_vect), + axis=1) + + wts = np.ones(int(nobs)) * (1. / nobs) + x0 = np.zeros(est_vect.shape[1]).reshape(-1, 1) + try: + eta_star = self._modif_newton(x0, est_vect, wts) + denom = 1. + np.dot(eta_star, est_vect.T) + self.new_weights = 1. / nobs * 1. / denom + # the following commented out code is to verify weights + # see open issue #1845 + #self.new_weights /= self.new_weights.sum() + #if not np.allclose(self.new_weights.sum(), 1., rtol=0, atol=1e-10): + # raise RuntimeError('weights do not sum to 1') + llr = np.sum(np.log(nobs * self.new_weights)) + return -2 * llr + except np.linalg.LinAlgError: + return np.inf diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/emplike/originregress.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/emplike/originregress.py new file mode 100644 index 0000000000000000000000000000000000000000..28956a5e3b6c4c4a6e4576c4aa4bdc507a1008ba --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/emplike/originregress.py @@ -0,0 +1,259 @@ +""" +This module implements empirical likelihood regression that is forced through +the origin. + +This is different than regression not forced through the origin because the +maximum empirical likelihood estimate is calculated with a vector of ones in +the exogenous matrix but restricts the intercept parameter to be 0. This +results in significantly more narrow confidence intervals and different +parameter estimates. + +For notes on regression not forced through the origin, see empirical likelihood +methods in the OLSResults class. + +General References +------------------ +Owen, A.B. (2001). Empirical Likelihood. Chapman and Hall. p. 82. + +""" +import numpy as np +from scipy import optimize +from scipy.stats import chi2 + +from statsmodels.regression.linear_model import OLS, RegressionResults +# When descriptive merged, this will be changed +from statsmodels.tools.tools import add_constant + + +class ELOriginRegress: + """ + Empirical Likelihood inference and estimation for linear regression + through the origin. + + Parameters + ---------- + endog: nx1 array + Array of response variables. + + exog: nxk array + Array of exogenous variables. Assumes no array of ones + + Attributes + ---------- + endog : nx1 array + Array of response variables + + exog : nxk array + Array of exogenous variables. Assumes no array of ones. + + nobs : float + Number of observations. + + nvar : float + Number of exogenous regressors. + """ + def __init__(self, endog, exog): + self.endog = endog + self.exog = exog + self.nobs = self.exog.shape[0] + try: + self.nvar = float(exog.shape[1]) + except IndexError: + self.nvar = 1. + + def fit(self): + """ + Fits the model and provides regression results. + + Returns + ------- + Results : class + Empirical likelihood regression class. + """ + exog_with = add_constant(self.exog, prepend=True) + restricted_model = OLS(self.endog, exog_with) + restricted_fit = restricted_model.fit() + restricted_el = restricted_fit.el_test( + np.array([0]), np.array([0]), ret_params=1) + params = np.squeeze(restricted_el[3]) + beta_hat_llr = restricted_el[0] + llf = np.sum(np.log(restricted_el[2])) + return OriginResults(restricted_model, params, beta_hat_llr, llf) + + def predict(self, params, exog=None): + if exog is None: + exog = self.exog + return np.dot(add_constant(exog, prepend=True), params) + + +class OriginResults(RegressionResults): + """ + A Results class for empirical likelihood regression through the origin. + + Parameters + ---------- + model : class + An OLS model with an intercept. + + params : 1darray + Fitted parameters. + + est_llr : float + The log likelihood ratio of the model with the intercept restricted to + 0 at the maximum likelihood estimates of the parameters. + llr_restricted/llr_unrestricted + + llf_el : float + The log likelihood of the fitted model with the intercept restricted to 0. + + Attributes + ---------- + model : class + An OLS model with an intercept. + + params : 1darray + Fitted parameter. + + llr : float + The log likelihood ratio of the maximum empirical likelihood estimate. + + llf_el : float + The log likelihood of the fitted model with the intercept restricted to 0. + + Notes + ----- + IMPORTANT. Since EL estimation does not drop the intercept parameter but + instead estimates the slope parameters conditional on the slope parameter + being 0, the first element for params will be the intercept, which is + restricted to 0. + + IMPORTANT. This class inherits from RegressionResults but inference is + conducted via empirical likelihood. Therefore, any methods that + require an estimate of the covariance matrix will not function. Instead + use el_test and conf_int_el to conduct inference. + + Examples + -------- + >>> import statsmodels.api as sm + >>> data = sm.datasets.bc.load() + >>> model = sm.emplike.ELOriginRegress(data.endog, data.exog) + >>> fitted = model.fit() + >>> fitted.params # 0 is the intercept term. + array([ 0. , 0.00351813]) + + >>> fitted.el_test(np.array([.0034]), np.array([1])) + (3.6696503297979302, 0.055411808127497755) + >>> fitted.conf_int_el(1) + (0.0033971871114706867, 0.0036373150174892847) + + # No covariance matrix so normal inference is not valid + >>> fitted.conf_int() + TypeError: unsupported operand type(s) for *: 'instancemethod' and 'float' + """ + def __init__(self, model, params, est_llr, llf_el): + self.model = model + self.params = np.squeeze(params) + self.llr = est_llr + self.llf_el = llf_el + def el_test(self, b0_vals, param_nums, method='nm', + stochastic_exog=1, return_weights=0): + """ + Returns the llr and p-value for a hypothesized parameter value + for a regression that goes through the origin. + + Parameters + ---------- + b0_vals : 1darray + The hypothesized value to be tested. + + param_num : 1darray + Which parameters to test. Note this uses python + indexing but the '0' parameter refers to the intercept term, + which is assumed 0. Therefore, param_num should be > 0. + + return_weights : bool + If true, returns the weights that optimize the likelihood + ratio at b0_vals. Default is False. + + method : str + Can either be 'nm' for Nelder-Mead or 'powell' for Powell. The + optimization method that optimizes over nuisance parameters. + Default is 'nm'. + + stochastic_exog : bool + When TRUE, the exogenous variables are assumed to be stochastic. + When the regressors are nonstochastic, moment conditions are + placed on the exogenous variables. Confidence intervals for + stochastic regressors are at least as large as non-stochastic + regressors. Default is TRUE. + + Returns + ------- + res : tuple + pvalue and likelihood ratio. + """ + b0_vals = np.hstack((0, b0_vals)) + param_nums = np.hstack((0, param_nums)) + test_res = self.model.fit().el_test(b0_vals, param_nums, method=method, + stochastic_exog=stochastic_exog, + return_weights=return_weights) + llr_test = test_res[0] + llr_res = llr_test - self.llr + pval = chi2.sf(llr_res, self.model.exog.shape[1] - 1) + if return_weights: + return llr_res, pval, test_res[2] + else: + return llr_res, pval + + def conf_int_el(self, param_num, upper_bound=None, + lower_bound=None, sig=.05, method='nm', + stochastic_exog=True): + """ + Returns the confidence interval for a regression parameter when the + regression is forced through the origin. + + Parameters + ---------- + param_num : int + The parameter number to be tested. Note this uses python + indexing but the '0' parameter refers to the intercept term. + upper_bound : float + The maximum value the upper confidence limit can be. The + closer this is to the confidence limit, the quicker the + computation. Default is .00001 confidence limit under normality. + lower_bound : float + The minimum value the lower confidence limit can be. + Default is .00001 confidence limit under normality. + sig : float, optional + The significance level. Default .05. + method : str, optional + Algorithm to optimize of nuisance params. Can be 'nm' or + 'powell'. Default is 'nm'. + stochastic_exog : bool + Default is True. + + Returns + ------- + ci: tuple + The confidence interval for the parameter 'param_num'. + """ + r0 = chi2.ppf(1 - sig, 1) + param_num = np.array([param_num]) + if upper_bound is None: + ci = np.asarray(self.model.fit().conf_int(.0001)) + upper_bound = (np.squeeze(ci[param_num])[1]) + if lower_bound is None: + ci = np.asarray(self.model.fit().conf_int(.0001)) + lower_bound = (np.squeeze(ci[param_num])[0]) + + def f(b0): + b0 = np.array([b0]) + val = self.el_test( + b0, param_num, method=method, stochastic_exog=stochastic_exog + ) + return val[0] - r0 + + _param = np.squeeze(self.params[param_num]) + lowerl = optimize.brentq(f, np.squeeze(lower_bound), _param) + upperl = optimize.brentq(f, _param, np.squeeze(upper_bound)) + return (lowerl, upperl) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/gam/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/gam/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..691559ca60fe92a39e770cdb5d16c42a4c5651e1 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/gam/__init__.py @@ -0,0 +1,3 @@ +from statsmodels.tools._test_runner import PytestTester + +test = PytestTester() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/gam/api.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/gam/api.py new file mode 100644 index 0000000000000000000000000000000000000000..c1f7c5cf799a655ed853be8f5ec063d3173ba636 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/gam/api.py @@ -0,0 +1,5 @@ +from .generalized_additive_model import GLMGam +from .gam_cross_validation.gam_cross_validation import MultivariateGAMCVPath +from .smooth_basis import BSplines, CyclicCubicSplines + +__all__ = ["BSplines", "CyclicCubicSplines", "GLMGam", "MultivariateGAMCVPath"] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/gam/gam_penalties.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/gam/gam_penalties.py new file mode 100644 index 0000000000000000000000000000000000000000..f4225770e232ba74724840c7d4da07ebf9cc7c1d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/gam/gam_penalties.py @@ -0,0 +1,306 @@ +""" +Penalty classes for Generalized Additive Models + +Author: Luca Puggini +Author: Josef Perktold + +""" + +import numpy as np +from scipy.linalg import block_diag +from statsmodels.base._penalties import Penalty + + +class UnivariateGamPenalty(Penalty): + """ + Penalty for smooth term in Generalized Additive Models + + Parameters + ---------- + univariate_smoother : instance + instance of univariate smoother or spline class + alpha : float + default penalty weight, alpha can be provided to each method + weights: + TODO: not used and verified, might be removed + + Attributes + ---------- + Parameters are stored, additionally + nob s: The number of samples used during the estimation + n_columns : number of columns in smoother basis + """ + + def __init__(self, univariate_smoother, alpha=1, weights=1): + self.weights = weights + self.alpha = alpha + self.univariate_smoother = univariate_smoother + self.nobs = self.univariate_smoother.nobs + self.n_columns = self.univariate_smoother.dim_basis + + def func(self, params, alpha=None): + """evaluate penalization at params + + Parameters + ---------- + params : ndarray + coefficients for the spline basis in the regression model + alpha : float + default penalty weight + + Returns + ------- + func : float + value of the penalty evaluated at params + """ + if alpha is None: + alpha = self.alpha + + f = params.dot(self.univariate_smoother.cov_der2.dot(params)) + return alpha * f / self.nobs + + def deriv(self, params, alpha=None): + """evaluate derivative of penalty with respect to params + + Parameters + ---------- + params : ndarray + coefficients for the spline basis in the regression model + alpha : float + default penalty weight + + Returns + ------- + deriv : ndarray + derivative, gradient of the penalty with respect to params + """ + if alpha is None: + alpha = self.alpha + + d = 2 * alpha * np.dot(self.univariate_smoother.cov_der2, params) + d /= self.nobs + return d + + def deriv2(self, params, alpha=None): + """evaluate second derivative of penalty with respect to params + + Parameters + ---------- + params : ndarray + coefficients for the spline basis in the regression model + alpha : float + default penalty weight + + Returns + ------- + deriv2 : ndarray, 2-Dim + second derivative, hessian of the penalty with respect to params + """ + if alpha is None: + alpha = self.alpha + + d2 = 2 * alpha * self.univariate_smoother.cov_der2 + d2 /= self.nobs + return d2 + + def penalty_matrix(self, alpha=None): + """penalty matrix for the smooth term of a GAM + + Parameters + ---------- + alpha : list of floats or None + penalty weights + + Returns + ------- + penalty matrix + square penalty matrix for quadratic penalization. The number + of rows and columns are equal to the number of columns in the + smooth terms, i.e. the number of parameters for this smooth + term in the regression model + """ + if alpha is None: + alpha = self.alpha + + return alpha * self.univariate_smoother.cov_der2 + + +class MultivariateGamPenalty(Penalty): + """ + Penalty for Generalized Additive Models + + Parameters + ---------- + multivariate_smoother : instance + instance of additive smoother or spline class + alpha : list of float + default penalty weight, list with length equal to the number of smooth + terms. ``alpha`` can also be provided to each method. + weights : array_like + currently not used + is a list of doubles of the same length as alpha or a list + of ndarrays where each component has the length equal to the number + of columns in that component + start_idx : int + number of parameters that come before the smooth terms. If the model + has a linear component, then the parameters for the smooth components + start at ``start_index``. + + Attributes + ---------- + Parameters are stored, additionally + nob s: The number of samples used during the estimation + + dim_basis : number of columns of additive smoother. Number of columns + in all smoothers. + k_variables : number of smooth terms + k_params : total number of parameters in the regression model + """ + + def __init__(self, multivariate_smoother, alpha, weights=None, + start_idx=0): + + if len(multivariate_smoother.smoothers) != len(alpha): + msg = ('all the input values should be of the same length.' + ' len(smoothers)=%d, len(alphas)=%d') % ( + len(multivariate_smoother.smoothers), len(alpha)) + raise ValueError(msg) + + self.multivariate_smoother = multivariate_smoother + self.dim_basis = self.multivariate_smoother.dim_basis + self.k_variables = self.multivariate_smoother.k_variables + self.nobs = self.multivariate_smoother.nobs + self.alpha = alpha + self.start_idx = start_idx + self.k_params = start_idx + self.dim_basis + + # TODO: Review this, + if weights is None: + # weights should have total length as params + # but it can also be scalar in individual component + self.weights = [1. for _ in range(self.k_variables)] + else: + import warnings + warnings.warn('weights is currently ignored') + self.weights = weights + + self.mask = [np.zeros(self.k_params, dtype=bool) + for _ in range(self.k_variables)] + param_count = start_idx + for i, smoother in enumerate(self.multivariate_smoother.smoothers): + # the mask[i] contains a vector of length k_columns. The index + # corresponding to the i-th input variable are set to True. + self.mask[i][param_count: param_count + smoother.dim_basis] = True + param_count += smoother.dim_basis + + self.gp = [] + for i in range(self.k_variables): + gp = UnivariateGamPenalty(self.multivariate_smoother.smoothers[i], + weights=self.weights[i], + alpha=self.alpha[i]) + self.gp.append(gp) + + def func(self, params, alpha=None): + """evaluate penalization at params + + Parameters + ---------- + params : ndarray + coefficients in the regression model + alpha : float or list of floats + penalty weights + + Returns + ------- + func : float + value of the penalty evaluated at params + """ + if alpha is None: + alpha = [None] * self.k_variables + + cost = 0 + for i in range(self.k_variables): + params_i = params[self.mask[i]] + cost += self.gp[i].func(params_i, alpha=alpha[i]) + + return cost + + def deriv(self, params, alpha=None): + """evaluate derivative of penalty with respect to params + + Parameters + ---------- + params : ndarray + coefficients in the regression model + alpha : list of floats or None + penalty weights + + Returns + ------- + deriv : ndarray + derivative, gradient of the penalty with respect to params + """ + if alpha is None: + alpha = [None] * self.k_variables + + grad = [np.zeros(self.start_idx)] + for i in range(self.k_variables): + params_i = params[self.mask[i]] + grad.append(self.gp[i].deriv(params_i, alpha=alpha[i])) + + return np.concatenate(grad) + + def deriv2(self, params, alpha=None): + """evaluate second derivative of penalty with respect to params + + Parameters + ---------- + params : ndarray + coefficients in the regression model + alpha : list of floats or None + penalty weights + + Returns + ------- + deriv2 : ndarray, 2-Dim + second derivative, hessian of the penalty with respect to params + """ + if alpha is None: + alpha = [None] * self.k_variables + + deriv2 = [np.zeros((self.start_idx, self.start_idx))] + for i in range(self.k_variables): + params_i = params[self.mask[i]] + deriv2.append(self.gp[i].deriv2(params_i, alpha=alpha[i])) + + return block_diag(*deriv2) + + def penalty_matrix(self, alpha=None): + """penalty matrix for generalized additive model + + Parameters + ---------- + alpha : list of floats or None + penalty weights + + Returns + ------- + penalty matrix + block diagonal, square penalty matrix for quadratic penalization. + The number of rows and columns are equal to the number of + parameters in the regression model ``k_params``. + + Notes + ----- + statsmodels does not support backwards compatibility when keywords are + used as positional arguments. The order of keywords might change. + We might need to add a ``params`` keyword if the need arises. + """ + if alpha is None: + alpha = self.alpha + + s_all = [np.zeros((self.start_idx, self.start_idx))] + for i in range(self.k_variables): + s_all.append(self.gp[i].penalty_matrix(alpha=alpha[i])) + + return block_diag(*s_all) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/gam/generalized_additive_model.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/gam/generalized_additive_model.py new file mode 100644 index 0000000000000000000000000000000000000000..b12e9c3d65d4c005fc6ba9a9311c71d8fa78a8fc --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/gam/generalized_additive_model.py @@ -0,0 +1,1012 @@ +""" +Generalized Additive Models + +Author: Luca Puggini +Author: Josef Perktold + +created on 08/07/2015 +""" + +from collections.abc import Iterable +import copy # check if needed when dropping python 2.7 + +import numpy as np +from scipy import optimize +import pandas as pd + +import statsmodels.base.wrapper as wrap + +from statsmodels.discrete.discrete_model import Logit +from statsmodels.genmod.generalized_linear_model import ( + GLM, GLMResults, GLMResultsWrapper, _check_convergence) +import statsmodels.regression.linear_model as lm +# import statsmodels.regression._tools as reg_tools # TODO: use this for pirls +from statsmodels.tools.sm_exceptions import (PerfectSeparationError, + ValueWarning) +from statsmodels.tools.decorators import cache_readonly +from statsmodels.tools.data import _is_using_pandas +from statsmodels.tools.linalg import matrix_sqrt + +from statsmodels.base._penalized import PenalizedMixin +from statsmodels.gam.gam_penalties import MultivariateGamPenalty +from statsmodels.gam.gam_cross_validation.gam_cross_validation import ( + MultivariateGAMCVPath) +from statsmodels.gam.gam_cross_validation.cross_validators import KFold + + +def _transform_predict_exog(model, exog, design_info=None): + """transform exog for predict using design_info + + Note: this is copied from base.model.Results.predict and converted to + standalone function with additional options. + """ + + is_pandas = _is_using_pandas(exog, None) + + exog_index = exog.index if is_pandas else None + + if design_info is None: + design_info = getattr(model.data, 'design_info', None) + + if design_info is not None and (exog is not None): + from patsy import dmatrix + if isinstance(exog, pd.Series): + # we are guessing whether it should be column or row + if (hasattr(exog, 'name') and isinstance(exog.name, str) and + exog.name in design_info.describe()): + # assume we need one column + exog = pd.DataFrame(exog) + else: + # assume we need a row + exog = pd.DataFrame(exog).T + orig_exog_len = len(exog) + is_dict = isinstance(exog, dict) + exog = dmatrix(design_info, exog, return_type="dataframe") + if orig_exog_len > len(exog) and not is_dict: + import warnings + if exog_index is None: + warnings.warn('nan values have been dropped', ValueWarning) + else: + exog = exog.reindex(exog_index) + exog_index = exog.index + + if exog is not None: + exog = np.asarray(exog) + if exog.ndim == 1 and (model.exog.ndim == 1 or + model.exog.shape[1] == 1): + exog = exog[:, None] + exog = np.atleast_2d(exog) # needed in count model shape[1] + + return exog, exog_index + + +class GLMGamResults(GLMResults): + """Results class for generalized additive models, GAM. + + This inherits from GLMResults. + + Warning: some inherited methods might not correctly take account of the + penalization + + GLMGamResults inherits from GLMResults + All methods related to the loglikelihood function return the penalized + values. + + Attributes + ---------- + + edf + list of effective degrees of freedom for each column of the design + matrix. + hat_matrix_diag + diagonal of hat matrix + gcv + generalized cross-validation criterion computed as + ``gcv = scale / (1. - hat_matrix_trace / self.nobs)**2`` + cv + cross-validation criterion computed as + ``cv = ((resid_pearson / (1 - hat_matrix_diag))**2).sum() / nobs`` + + Notes + ----- + status: experimental + """ + + def __init__(self, model, params, normalized_cov_params, scale, **kwds): + + # this is a messy way to compute edf and update scale + # need several attributes to compute edf + self.model = model + self.params = params + self.normalized_cov_params = normalized_cov_params + self.scale = scale + edf = self.edf.sum() + self.df_model = edf - 1 # assume constant + # need to use nobs or wnobs attribute + self.df_resid = self.model.endog.shape[0] - edf + + # we are setting the model df for the case when super is using it + # df in model will be incorrect state when alpha/pen_weight changes + self.model.df_model = self.df_model + self.model.df_resid = self.df_resid + mu = self.fittedvalues + self.scale = scale = self.model.estimate_scale(mu) + super().__init__( + model, params, normalized_cov_params, scale, **kwds + ) + + def _tranform_predict_exog(self, exog=None, exog_smooth=None, + transform=True): + """Transform original explanatory variables for prediction + + Parameters + ---------- + exog : array_like, optional + The values for the linear explanatory variables. + exog_smooth : array_like + values for the variables in the smooth terms + transform : bool, optional + If transform is False, then ``exog`` is returned unchanged and + ``x`` is ignored. It is assumed that exog contains the full + design matrix for the predict observations. + If transform is True, then the basis representation of the smooth + term will be constructed from the provided ``x``. + + Returns + ------- + exog_transformed : ndarray + design matrix for the prediction + """ + if exog_smooth is not None: + exog_smooth = np.asarray(exog_smooth) + exog_index = None + if transform is False: + # the following allows that either or both exog are not None + if exog_smooth is None: + # exog could be None or array + ex = exog + else: + if exog is None: + ex = exog_smooth + else: + ex = np.column_stack((exog, exog_smooth)) + else: + # transform exog_linear if needed + if exog is not None and hasattr(self.model, 'design_info_linear'): + exog, exog_index = _transform_predict_exog( + self.model, exog, self.model.design_info_linear) + + # create smooth basis + if exog_smooth is not None: + ex_smooth = self.model.smoother.transform(exog_smooth) + if exog is None: + ex = ex_smooth + else: + # TODO: there might be problems is exog_smooth is 1-D + ex = np.column_stack((exog, ex_smooth)) + else: + ex = exog + + return ex, exog_index + + def predict(self, exog=None, exog_smooth=None, transform=True, **kwargs): + """" + compute prediction + + Parameters + ---------- + exog : array_like, optional + The values for the linear explanatory variables + exog_smooth : array_like + values for the variables in the smooth terms + transform : bool, optional + If transform is True, then the basis representation of the smooth + term will be constructed from the provided ``exog``. + kwargs : + Some models can take additional arguments or keywords, see the + predict method of the model for the details. + + Returns + ------- + prediction : ndarray, pandas.Series or pandas.DataFrame + predicted values + """ + ex, exog_index = self._tranform_predict_exog(exog=exog, + exog_smooth=exog_smooth, + transform=transform) + predict_results = super().predict(ex, transform=False, **kwargs) + if exog_index is not None and not hasattr( + predict_results, 'predicted_values'): + if predict_results.ndim == 1: + return pd.Series(predict_results, index=exog_index) + else: + return pd.DataFrame(predict_results, index=exog_index) + else: + return predict_results + + def get_prediction(self, exog=None, exog_smooth=None, transform=True, + **kwargs): + """compute prediction results + + Parameters + ---------- + exog : array_like, optional + The values for which you want to predict. + exog_smooth : array_like + values for the variables in the smooth terms + transform : bool, optional + If transform is True, then the basis representation of the smooth + term will be constructed from the provided ``x``. + kwargs : + Some models can take additional arguments or keywords, see the + predict method of the model for the details. + + Returns + ------- + prediction_results : generalized_linear_model.PredictionResults + The prediction results instance contains prediction and prediction + variance and can on demand calculate confidence intervals and + summary tables for the prediction of the mean and of new + observations. + """ + ex, exog_index = self._tranform_predict_exog(exog=exog, + exog_smooth=exog_smooth, + transform=transform) + return super().get_prediction(ex, transform=False, **kwargs) + + def partial_values(self, smooth_index, include_constant=True): + """contribution of a smooth term to the linear prediction + + Warning: This will be replaced by a predict method + + Parameters + ---------- + smooth_index : int + index of the smooth term within list of smooth terms + include_constant : bool + If true, then the estimated intercept is added to the prediction + and its standard errors. This avoids that the confidence interval + has zero width at the imposed identification constraint, e.g. + either at a reference point or at the mean. + + Returns + ------- + predicted : nd_array + predicted value of linear term. + This is not the expected response if the link function is not + linear. + se_pred : nd_array + standard error of linear prediction + """ + variable = smooth_index + smoother = self.model.smoother + mask = smoother.mask[variable] + + start_idx = self.model.k_exog_linear + idx = start_idx + np.nonzero(mask)[0] + + # smoother has only smooth parts, not exog_linear + exog_part = smoother.basis[:, mask] + + const_idx = self.model.data.const_idx + if include_constant and const_idx is not None: + idx = np.concatenate(([const_idx], idx)) + exog_part = self.model.exog[:, idx] + + linpred = np.dot(exog_part, self.params[idx]) + # select the submatrix corresponding to a single variable + partial_cov_params = self.cov_params(column=idx) + + covb = partial_cov_params + var = (exog_part * np.dot(covb, exog_part.T).T).sum(1) + se = np.sqrt(var) + + return linpred, se + + def plot_partial(self, smooth_index, plot_se=True, cpr=False, + include_constant=True, ax=None): + """plot the contribution of a smooth term to the linear prediction + + Parameters + ---------- + smooth_index : int + index of the smooth term within list of smooth terms + plot_se : bool + If plot_se is true, then the confidence interval for the linear + prediction will be added to the plot. + cpr : bool + If cpr (component plus residual) is true, then a scatter plot of + the partial working residuals will be added to the plot. + include_constant : bool + If true, then the estimated intercept is added to the prediction + and its standard errors. This avoids that the confidence interval + has zero width at the imposed identification constraint, e.g. + either at a reference point or at the mean. + ax : None or matplotlib axis instance + If ax is not None, then the plot will be added to it. + + Returns + ------- + Figure + If `ax` is None, the created figure. Otherwise, the Figure to which + `ax` is connected. + """ + from statsmodels.graphics.utils import _import_mpl, create_mpl_ax + _import_mpl() + + variable = smooth_index + y_est, se = self.partial_values(variable, + include_constant=include_constant) + smoother = self.model.smoother + x = smoother.smoothers[variable].x + sort_index = np.argsort(x) + x = x[sort_index] + y_est = y_est[sort_index] + se = se[sort_index] + + fig, ax = create_mpl_ax(ax) + + if cpr: + # TODO: resid_response does not make sense with nonlinear link + # use resid_working ? + residual = self.resid_working[sort_index] + cpr_ = y_est + residual + ax.scatter(x, cpr_, s=4) + + ax.plot(x, y_est, c='blue', lw=2) + if plot_se: + ax.plot(x, y_est + 1.96 * se, '-', c='blue') + ax.plot(x, y_est - 1.96 * se, '-', c='blue') + + ax.set_xlabel(smoother.smoothers[variable].variable_name) + + return fig + + def test_significance(self, smooth_index): + """hypothesis test that a smooth component is zero. + + This calls `wald_test` to compute the hypothesis test, but uses + effective degrees of freedom. + + Parameters + ---------- + smooth_index : int + index of the smooth term within list of smooth terms + + Returns + ------- + wald_test : ContrastResults instance + the results instance created by `wald_test` + """ + + variable = smooth_index + smoother = self.model.smoother + start_idx = self.model.k_exog_linear + + k_params = len(self.params) + # a bit messy, we need first index plus length of smooth term + mask = smoother.mask[variable] + k_constraints = mask.sum() + idx = start_idx + np.nonzero(mask)[0][0] + constraints = np.eye(k_constraints, k_params, idx) + df_constraints = self.edf[idx: idx + k_constraints].sum() + + return self.wald_test(constraints, df_constraints=df_constraints) + + def get_hat_matrix_diag(self, observed=True, _axis=1): + """ + Compute the diagonal of the hat matrix + + Parameters + ---------- + observed : bool + If true, then observed hessian is used in the hat matrix + computation. If false, then the expected hessian is used. + In the case of a canonical link function both are the same. + This is only relevant for models that implement both observed + and expected Hessian, which is currently only GLM. Other + models only use the observed Hessian. + _axis : int + This is mainly for internal use. By default it returns the usual + diagonal of the hat matrix. If _axis is zero, then the result + corresponds to the effective degrees of freedom, ``edf`` for each + column of exog. + + Returns + ------- + hat_matrix_diag : ndarray + The diagonal of the hat matrix computed from the observed + or expected hessian. + """ + weights = self.model.hessian_factor(self.params, scale=self.scale, + observed=observed) + wexog = np.sqrt(weights)[:, None] * self.model.exog + + # we can use inverse hessian directly instead of computing it from + # WLS/IRLS as in GLM + + # TODO: does `normalized_cov_params * scale` work in all cases? + # this avoids recomputing hessian, check when used for other models. + hess_inv = self.normalized_cov_params * self.scale + # this is in GLM equivalent to the more generic and direct + # hess_inv = np.linalg.inv(-self.model.hessian(self.params)) + hd = (wexog * hess_inv.dot(wexog.T).T).sum(axis=_axis) + return hd + + @cache_readonly + def edf(self): + return self.get_hat_matrix_diag(_axis=0) + + @cache_readonly + def hat_matrix_trace(self): + return self.hat_matrix_diag.sum() + + @cache_readonly + def hat_matrix_diag(self): + return self.get_hat_matrix_diag(observed=True) + + @cache_readonly + def gcv(self): + return self.scale / (1. - self.hat_matrix_trace / self.nobs)**2 + + @cache_readonly + def cv(self): + cv_ = ((self.resid_pearson / (1. - self.hat_matrix_diag))**2).sum() + cv_ /= self.nobs + return cv_ + + +class GLMGamResultsWrapper(GLMResultsWrapper): + pass + + +wrap.populate_wrapper(GLMGamResultsWrapper, GLMGamResults) + + +class GLMGam(PenalizedMixin, GLM): + """ + Generalized Additive Models (GAM) + + This inherits from `GLM`. + + Warning: Not all inherited methods might take correctly account of the + penalization. Not all options including offset and exposure have been + verified yet. + + Parameters + ---------- + endog : array_like + The response variable. + exog : array_like or None + This explanatory variables are treated as linear. The model in this + case is a partial linear model. + smoother : instance of additive smoother class + Examples of smoother instances include Bsplines or CyclicCubicSplines. + alpha : float or list of floats + Penalization weights for smooth terms. The length of the list needs + to be the same as the number of smooth terms in the ``smoother``. + family : instance of GLM family + See GLM. + offset : None or array_like + See GLM. + exposure : None or array_like + See GLM. + missing : 'none' + Missing value handling is not supported in this class. + **kwargs + Extra keywords are used in call to the super classes. + + Notes + ----- + Status: experimental. This has full unit test coverage for the core + results with Gaussian and Poisson (without offset and exposure). Other + options and additional results might not be correctly supported yet. + (Binomial with counts, i.e. with n_trials, is most likely wrong in pirls. + User specified var or freq weights are most likely also not correct for + all results.) + """ + + _results_class = GLMGamResults + _results_class_wrapper = GLMGamResultsWrapper + + def __init__(self, endog, exog=None, smoother=None, alpha=0, family=None, + offset=None, exposure=None, missing='none', **kwargs): + + # TODO: check usage of hasconst + hasconst = kwargs.get('hasconst', None) + xnames_linear = None + if hasattr(exog, 'design_info'): + self.design_info_linear = exog.design_info + xnames_linear = self.design_info_linear.column_names + + is_pandas = _is_using_pandas(exog, None) + + # TODO: handle data is experimental, see #5469 + # This is a bit wasteful because we need to `handle_data twice` + self.data_linear = self._handle_data(endog, exog, missing, hasconst) + if xnames_linear is None: + xnames_linear = self.data_linear.xnames + if exog is not None: + exog_linear = self.data_linear.exog + k_exog_linear = exog_linear.shape[1] + else: + exog_linear = None + k_exog_linear = 0 + self.k_exog_linear = k_exog_linear + # We need exog_linear for k-fold cross validation + # TODO: alternative is to take columns from combined exog + self.exog_linear = exog_linear + + self.smoother = smoother + self.k_smooths = smoother.k_variables + self.alpha = self._check_alpha(alpha) + penal = MultivariateGamPenalty(smoother, alpha=self.alpha, + start_idx=k_exog_linear) + kwargs.pop('penal', None) + if exog_linear is not None: + exog = np.column_stack((exog_linear, smoother.basis)) + else: + exog = smoother.basis + + # TODO: check: xnames_linear will be None instead of empty list + # if no exog_linear + # can smoother be empty ? I guess not allowed. + if xnames_linear is None: + xnames_linear = [] + xnames = xnames_linear + self.smoother.col_names + + if is_pandas and exog_linear is not None: + # we a dataframe so we can get a PandasData instance for wrapping + exog = pd.DataFrame(exog, index=self.data_linear.row_labels, + columns=xnames) + + super().__init__(endog, exog=exog, family=family, + offset=offset, exposure=exposure, + penal=penal, missing=missing, **kwargs) + + if not is_pandas: + # set exog nanmes if not given by pandas DataFrame + self.exog_names[:] = xnames + + # TODO: the generic data handling might attach the design_info from the + # linear part, but this is incorrect for the full model and + # causes problems in wald_test_terms + + if hasattr(self.data, 'design_info'): + del self.data.design_info + # formula also might be attached which causes problems in predict + if hasattr(self, 'formula'): + self.formula_linear = self.formula + self.formula = None + del self.formula + + def _check_alpha(self, alpha): + """check and convert alpha to required list format + + Parameters + ---------- + alpha : scalar, list or array_like + penalization weight + + Returns + ------- + alpha : list + penalization weight, list with length equal to the number of + smooth terms + """ + if not isinstance(alpha, Iterable): + alpha = [alpha] * len(self.smoother.smoothers) + elif not isinstance(alpha, list): + # we want alpha to be a list + alpha = list(alpha) + return alpha + + def fit(self, start_params=None, maxiter=1000, method='pirls', tol=1e-8, + scale=None, cov_type='nonrobust', cov_kwds=None, use_t=None, + full_output=True, disp=False, max_start_irls=3, **kwargs): + """estimate parameters and create instance of GLMGamResults class + + Parameters + ---------- + most parameters are the same as for GLM + method : optimization method + The special optimization method is "pirls" which uses a penalized + version of IRLS. Other methods are gradient optimizers as used in + base.model.LikelihoodModel. + + Returns + ------- + res : instance of wrapped GLMGamResults + """ + # TODO: temporary hack to remove attribute + # formula also might be attached which in inherited from_formula + # causes problems in predict + if hasattr(self, 'formula'): + self.formula_linear = self.formula + del self.formula + + # TODO: alpha not allowed yet, but is in `_fit_pirls` + # alpha = self._check_alpha() + + if method.lower() in ['pirls', 'irls']: + res = self._fit_pirls(self.alpha, start_params=start_params, + maxiter=maxiter, tol=tol, scale=scale, + cov_type=cov_type, cov_kwds=cov_kwds, + use_t=use_t, **kwargs) + else: + if max_start_irls > 0 and (start_params is None): + res = self._fit_pirls(self.alpha, start_params=start_params, + maxiter=max_start_irls, tol=tol, + scale=scale, + cov_type=cov_type, cov_kwds=cov_kwds, + use_t=use_t, **kwargs) + start_params = res.params + del res + res = super().fit(start_params=start_params, + maxiter=maxiter, method=method, + tol=tol, scale=scale, + cov_type=cov_type, cov_kwds=cov_kwds, + use_t=use_t, + full_output=full_output, disp=disp, + max_start_irls=0, + **kwargs) + return res + + # pag 165 4.3 # pag 136 PIRLS + def _fit_pirls(self, alpha, start_params=None, maxiter=100, tol=1e-8, + scale=None, cov_type='nonrobust', cov_kwds=None, use_t=None, + weights=None): + """fit model with penalized reweighted least squares + """ + # TODO: this currently modifies several attributes + # self.scale, self.scaletype, self.mu, self.weights + # self.data_weights, + # and possibly self._offset_exposure + # several of those might not be necessary, e.g. mu and weights + + # alpha = alpha * len(y) * self.scale / 100 + # TODO: we need to rescale alpha + endog = self.endog + wlsexog = self.exog # smoother.basis + spl_s = self.penal.penalty_matrix(alpha=alpha) + + nobs, n_columns = wlsexog.shape + + # TODO what are these values? + if weights is None: + self.data_weights = np.array([1.] * nobs) + else: + self.data_weights = weights + + if not hasattr(self, '_offset_exposure'): + self._offset_exposure = 0 + + self.scaletype = scale + # TODO: check default scale types + # self.scaletype = 'dev' + # during iteration + self.scale = 1 + + if start_params is None: + mu = self.family.starting_mu(endog) + lin_pred = self.family.predict(mu) + else: + lin_pred = np.dot(wlsexog, start_params) + self._offset_exposure + mu = self.family.fitted(lin_pred) + dev = self.family.deviance(endog, mu) + + history = dict(params=[None, start_params], deviance=[np.inf, dev]) + converged = False + criterion = history['deviance'] + # This special case is used to get the likelihood for a specific + # params vector. + if maxiter == 0: + mu = self.family.fitted(lin_pred) + self.scale = self.estimate_scale(mu) + wls_results = lm.RegressionResults(self, start_params, None) + iteration = 0 + + for iteration in range(maxiter): + + # TODO: is this equivalent to point 1 of page 136: + # w = 1 / (V(mu) * g'(mu)) ? + self.weights = self.data_weights * self.family.weights(mu) + + # TODO: is this equivalent to point 1 of page 136: + # z = g(mu)(y - mu) + X beta ? + wlsendog = (lin_pred + self.family.link.deriv(mu) * (endog - mu) + - self._offset_exposure) + + # this defines the augmented matrix point 2a on page 136 + wls_results = penalized_wls(wlsendog, wlsexog, spl_s, self.weights) + lin_pred = np.dot(wlsexog, wls_results.params).ravel() + lin_pred += self._offset_exposure + mu = self.family.fitted(lin_pred) + + # We do not need to update scale in GLM/LEF models + # We might need it in dispersion models. + # self.scale = self.estimate_scale(mu) + history = self._update_history(wls_results, mu, history) + + if endog.squeeze().ndim == 1 and np.allclose(mu - endog, 0): + msg = "Perfect separation detected, results not available" + raise PerfectSeparationError(msg) + + # TODO need atol, rtol + # args of _check_convergence: (criterion, iteration, atol, rtol) + converged = _check_convergence(criterion, iteration, tol, 0) + if converged: + break + self.mu = mu + self.scale = self.estimate_scale(mu) + glm_results = GLMGamResults(self, wls_results.params, + wls_results.normalized_cov_params, + self.scale, + cov_type=cov_type, cov_kwds=cov_kwds, + use_t=use_t) + + glm_results.method = "PIRLS" + history['iteration'] = iteration + 1 + glm_results.fit_history = history + glm_results.converged = converged + + return GLMGamResultsWrapper(glm_results) + + def select_penweight(self, criterion='aic', start_params=None, + start_model_params=None, + method='basinhopping', **fit_kwds): + """find alpha by minimizing results criterion + + The objective for the minimization can be results attributes like + ``gcv``, ``aic`` or ``bic`` where the latter are based on effective + degrees of freedom. + + Warning: In many case the optimization might converge to a local + optimum or near optimum. Different start_params or using a global + optimizer is recommended, default is basinhopping. + + Parameters + ---------- + criterion='aic' + name of results attribute to be minimized. + Default is 'aic', other options are 'gcv', 'cv' or 'bic'. + start_params : None or array + starting parameters for alpha in the penalization weight + minimization. The parameters are internally exponentiated and + the minimization is with respect to ``exp(alpha)`` + start_model_params : None or array + starting parameter for the ``model._fit_pirls``. + method : 'basinhopping', 'nm' or 'minimize' + 'basinhopping' and 'nm' directly use the underlying scipy.optimize + functions `basinhopping` and `fmin`. 'minimize' provides access + to the high level interface, `scipy.optimize.minimize`. + fit_kwds : keyword arguments + additional keyword arguments will be used in the call to the + scipy optimizer. Which keywords are supported depends on the + scipy optimization function. + + Returns + ------- + alpha : ndarray + penalization parameter found by minimizing the criterion. + Note that this can be only a local (near) optimum. + fit_res : tuple + results returned by the scipy optimization routine. The + parameters in the optimization problem are `log(alpha)` + history : dict + history of calls to pirls and contains alpha, the fit + criterion and the parameters to which pirls converged to for the + given alpha. + + Notes + ----- + In the test cases Nelder-Mead and bfgs often converge to local optima, + see also https://github.com/statsmodels/statsmodels/issues/5381. + + This does not use any analytical derivatives for the criterion + minimization. + + Status: experimental, It is possible that defaults change if there + is a better way to find a global optimum. API (e.g. type of return) + might also change. + """ + # copy attributes that are changed, so we can reset them + scale_keep = self.scale + scaletype_keep = self.scaletype + # TODO: use .copy() method when available for all types + alpha_keep = copy.copy(self.alpha) + + if start_params is None: + start_params = np.zeros(self.k_smooths) + else: + start_params = np.log(1e-20 + start_params) + + history = {} + history['alpha'] = [] + history['params'] = [start_model_params] + history['criterion'] = [] + + def fun(p): + a = np.exp(p) + res_ = self._fit_pirls(start_params=history['params'][-1], + alpha=a) + history['alpha'].append(a) + history['params'].append(np.asarray(res_.params)) + return getattr(res_, criterion) + + if method == 'nm': + kwds = dict(full_output=True, maxiter=1000, maxfun=2000) + kwds.update(fit_kwds) + fit_res = optimize.fmin(fun, start_params, **kwds) + opt = fit_res[0] + elif method == 'basinhopping': + kwds = dict(minimizer_kwargs={'method': 'Nelder-Mead', + 'options': {'maxiter': 100, 'maxfev': 500}}, + niter=10) + kwds.update(fit_kwds) + fit_res = optimize.basinhopping(fun, start_params, **kwds) + opt = fit_res.x + elif method == 'minimize': + fit_res = optimize.minimize(fun, start_params, **fit_kwds) + opt = fit_res.x + else: + raise ValueError('method not recognized') + + del history['params'][0] # remove the model start_params + + alpha = np.exp(opt) + + # reset attributes that have or might have changed + self.scale = scale_keep + self.scaletype = scaletype_keep + self.alpha = alpha_keep + + return alpha, fit_res, history + + def select_penweight_kfold(self, alphas=None, cv_iterator=None, cost=None, + k_folds=5, k_grid=11): + """find alphas by k-fold cross-validation + + Warning: This estimates ``k_folds`` models for each point in the + grid of alphas. + + Parameters + ---------- + alphas : None or list of arrays + cv_iterator : instance + instance of a cross-validation iterator, by default this is a + KFold instance + cost : function + default is mean squared error. The cost function to evaluate the + prediction error for the left out sample. This should take two + arrays as argument and return one float. + k_folds : int + number of folds if default Kfold iterator is used. + This is ignored if ``cv_iterator`` is not None. + + Returns + ------- + alpha_cv : list of float + Best alpha in grid according to cross-validation + res_cv : instance of MultivariateGAMCVPath + The instance was used for cross-validation and holds the results + + Notes + ----- + The default alphas are defined as + ``alphas = [np.logspace(0, 7, k_grid) for _ in range(k_smooths)]`` + """ + + if cost is None: + def cost(x1, x2): + return np.linalg.norm(x1 - x2) / len(x1) + + if alphas is None: + alphas = [np.logspace(0, 7, k_grid) for _ in range(self.k_smooths)] + + if cv_iterator is None: + cv_iterator = KFold(k_folds=k_folds, shuffle=True) + + gam_cv = MultivariateGAMCVPath(smoother=self.smoother, alphas=alphas, + gam=GLMGam, cost=cost, endog=self.endog, + exog=self.exog_linear, + cv_iterator=cv_iterator) + gam_cv_res = gam_cv.fit() + + return gam_cv_res.alpha_cv, gam_cv_res + + +class LogitGam(PenalizedMixin, Logit): + """Generalized Additive model for discrete Logit + + This subclasses discrete_model Logit. + + Warning: not all inherited methods might take correctly account of the + penalization + + not verified yet. + """ + def __init__(self, endog, smoother, alpha, *args, **kwargs): + if not isinstance(alpha, Iterable): + alpha = np.array([alpha] * len(smoother.smoothers)) + + self.smoother = smoother + self.alpha = alpha + self.pen_weight = 1 # TODO: pen weight should not be defined here!! + penal = MultivariateGamPenalty(smoother, alpha=alpha) + + super().__init__(endog, smoother.basis, penal=penal, *args, **kwargs) + + +def penalized_wls(endog, exog, penalty_matrix, weights): + """weighted least squares with quadratic penalty + + Parameters + ---------- + endog : ndarray + response or endogenous variable + exog : ndarray + design matrix, matrix of exogenous or explanatory variables + penalty_matrix : ndarray, 2-Dim square + penality matrix for quadratic penalization. Note, the penalty_matrix + is multiplied by two to match non-pirls fitting methods. + weights : ndarray + weights for WLS + + Returns + ------- + results : Results instance of WLS + """ + y, x, s = endog, exog, penalty_matrix + # TODO: I do not understand why I need 2 * s + aug_y, aug_x, aug_weights = make_augmented_matrix(y, x, 2 * s, weights) + wls_results = lm.WLS(aug_y, aug_x, aug_weights).fit() + # TODO: use MinimalWLS during iterations, less overhead + # However, MinimalWLS does not return normalized_cov_params + # which we need at the end of the iterations + # call would be + # wls_results = reg_tools._MinimalWLS(aug_y, aug_x, aug_weights).fit() + wls_results.params = wls_results.params.ravel() + + return wls_results + + +def make_augmented_matrix(endog, exog, penalty_matrix, weights): + """augment endog, exog and weights with stochastic restriction matrix + + Parameters + ---------- + endog : ndarray + response or endogenous variable + exog : ndarray + design matrix, matrix of exogenous or explanatory variables + penalty_matrix : ndarray, 2-Dim square + penality matrix for quadratic penalization + weights : ndarray + weights for WLS + + Returns + ------- + endog_aug : ndarray + augmented response variable + exog_aug : ndarray + augmented design matrix + weights_aug : ndarray + augmented weights for WLS + """ + y, x, s, = endog, exog, penalty_matrix + nobs = x.shape[0] + + # TODO: needs full because of broadcasting with weights + # check what weights should be doing + rs = matrix_sqrt(s) + x1 = np.vstack([x, rs]) # augmented x + n_samp1es_x1 = x1.shape[0] + + y1 = np.array([0.] * n_samp1es_x1) # augmented y + y1[:nobs] = y + + id1 = np.array([1.] * rs.shape[0]) + w1 = np.concatenate([weights, id1]) + + return y1, x1, w1 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/gam/smooth_basis.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/gam/smooth_basis.py new file mode 100644 index 0000000000000000000000000000000000000000..e68fd4d865e8f14ac8ffba72b7fbf15da809b92f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/gam/smooth_basis.py @@ -0,0 +1,1069 @@ +""" +Spline and other smoother classes for Generalized Additive Models + +Author: Luca Puggini +Author: Josef Perktold + +Created on Fri Jun 5 16:32:00 2015 +""" + +# import useful only for development +from abc import ABCMeta, abstractmethod +from statsmodels.compat.python import with_metaclass + +import numpy as np +import pandas as pd +from patsy import dmatrix +from patsy.mgcv_cubic_splines import _get_all_sorted_knots + +from statsmodels.tools.linalg import transf_constraints + + +# Obtain b splines from patsy + +def _equally_spaced_knots(x, df): + n_knots = df - 2 + x_min = x.min() + x_max = x.max() + knots = np.linspace(x_min, x_max, n_knots) + return knots + + +def _R_compat_quantile(x, probs): + # return np.percentile(x, 100 * np.asarray(probs)) + probs = np.asarray(probs) + quantiles = np.asarray([np.percentile(x, 100 * prob) + for prob in probs.ravel(order="C")]) + return quantiles.reshape(probs.shape, order="C") + + +# FIXME: is this copy/pasted? If so, why do we need it? If not, get +# rid of the try/except for scipy import +# from patsy splines.py +def _eval_bspline_basis(x, knots, degree, deriv='all', include_intercept=True): + try: + from scipy.interpolate import splev + except ImportError: + raise ImportError("spline functionality requires scipy") + # 'knots' are assumed to be already pre-processed. E.g. usually you + # want to include duplicate copies of boundary knots; you should do + # that *before* calling this constructor. + knots = np.atleast_1d(np.asarray(knots, dtype=float)) + assert knots.ndim == 1 + knots.sort() + degree = int(degree) + x = np.atleast_1d(x) + if x.ndim == 2 and x.shape[1] == 1: + x = x[:, 0] + assert x.ndim == 1 + # XX FIXME: when points fall outside of the boundaries, splev and R seem + # to handle them differently. I do not know why yet. So until we understand + # this and decide what to do with it, I'm going to play it safe and + # disallow such points. + if np.min(x) < np.min(knots) or np.max(x) > np.max(knots): + raise NotImplementedError("some data points fall outside the " + "outermost knots, and I'm not sure how " + "to handle them. (Patches accepted!)") + # Thanks to Charles Harris for explaining splev. It's not well + # documented, but basically it computes an arbitrary b-spline basis + # given knots and degree on some specificed points (or derivatives + # thereof, but we do not use that functionality), and then returns some + # linear combination of these basis functions. To get out the basis + # functions themselves, we use linear combinations like [1, 0, 0], [0, + # 1, 0], [0, 0, 1]. + # NB: This probably makes it rather inefficient (though I have not checked + # to be sure -- maybe the fortran code actually skips computing the basis + # function for coefficients that are zero). + # Note: the order of a spline is the same as its degree + 1. + # Note: there are (len(knots) - order) basis functions. + + k_const = 1 - int(include_intercept) + n_bases = len(knots) - (degree + 1) - k_const + if deriv in ['all', 0]: + basis = np.empty((x.shape[0], n_bases), dtype=float) + ret = basis + if deriv in ['all', 1]: + der1_basis = np.empty((x.shape[0], n_bases), dtype=float) + ret = der1_basis + if deriv in ['all', 2]: + der2_basis = np.empty((x.shape[0], n_bases), dtype=float) + ret = der2_basis + + for i in range(n_bases): + coefs = np.zeros((n_bases + k_const,)) + # we are skipping the first column of the basis to drop constant + coefs[i + k_const] = 1 + ii = i + if deriv in ['all', 0]: + basis[:, ii] = splev(x, (knots, coefs, degree)) + if deriv in ['all', 1]: + der1_basis[:, ii] = splev(x, (knots, coefs, degree), der=1) + if deriv in ['all', 2]: + der2_basis[:, ii] = splev(x, (knots, coefs, degree), der=2) + + if deriv == 'all': + return basis, der1_basis, der2_basis + else: + return ret + + +def compute_all_knots(x, df, degree): + order = degree + 1 + n_inner_knots = df - order + lower_bound = np.min(x) + upper_bound = np.max(x) + knot_quantiles = np.linspace(0, 1, n_inner_knots + 2)[1:-1] + inner_knots = _R_compat_quantile(x, knot_quantiles) + all_knots = np.concatenate(([lower_bound, upper_bound] * order, + inner_knots)) + return all_knots, lower_bound, upper_bound, inner_knots + + +def make_bsplines_basis(x, df, degree): + ''' make a spline basis for x ''' + + all_knots, _, _, _ = compute_all_knots(x, df, degree) + basis, der_basis, der2_basis = _eval_bspline_basis(x, all_knots, degree) + return basis, der_basis, der2_basis + + +def get_knots_bsplines(x=None, df=None, knots=None, degree=3, + spacing='quantile', lower_bound=None, + upper_bound=None, all_knots=None): + """knots for use in B-splines + + There are two main options for the knot placement + + - quantile spacing with multiplicity of boundary knots + - equal spacing extended to boundary or exterior knots + + The first corresponds to splines as used by patsy. the second is the + knot spacing for P-Splines. + """ + # based on patsy memorize_finish + if all_knots is not None: + return all_knots + + x_min = x.min() + x_max = x.max() + + if degree < 0: + raise ValueError("degree must be greater than 0 (not %r)" + % (degree,)) + if int(degree) != degree: + raise ValueError("degree must be an integer (not %r)" + % (degree,)) + + # These are guaranteed to all be 1d vectors by the code above + # x = np.concatenate(tmp["xs"]) + if df is None and knots is None: + raise ValueError("must specify either df or knots") + order = degree + 1 + if df is not None: + n_inner_knots = df - order + if n_inner_knots < 0: + raise ValueError("df=%r is too small for degree=%r; must be >= %s" + % (df, degree, + # We know that n_inner_knots is negative; + # if df were that much larger, it would + # have been zero, and things would work. + df - n_inner_knots)) + if knots is not None: + if len(knots) != n_inner_knots: + raise ValueError("df=%s with degree=%r implies %s knots, " + "but %s knots were provided" + % (df, degree, + n_inner_knots, len(knots))) + elif spacing == 'quantile': + # Need to compute inner knots + knot_quantiles = np.linspace(0, 1, n_inner_knots + 2)[1:-1] + inner_knots = _R_compat_quantile(x, knot_quantiles) + elif spacing == 'equal': + # Need to compute inner knots + grid = np.linspace(0, 1, n_inner_knots + 2)[1:-1] + inner_knots = x_min + grid * (x_max - x_min) + diff_knots = inner_knots[1] - inner_knots[0] + else: + raise ValueError("incorrect option for spacing") + if knots is not None: + inner_knots = knots + if lower_bound is None: + lower_bound = np.min(x) + if upper_bound is None: + upper_bound = np.max(x) + + if lower_bound > upper_bound: + raise ValueError("lower_bound > upper_bound (%r > %r)" + % (lower_bound, upper_bound)) + inner_knots = np.asarray(inner_knots) + if inner_knots.ndim > 1: + raise ValueError("knots must be 1 dimensional") + if np.any(inner_knots < lower_bound): + raise ValueError("some knot values (%s) fall below lower bound " + "(%r)" + % (inner_knots[inner_knots < lower_bound], + lower_bound)) + if np.any(inner_knots > upper_bound): + raise ValueError("some knot values (%s) fall above upper bound " + "(%r)" + % (inner_knots[inner_knots > upper_bound], + upper_bound)) + + if spacing == "equal": + diffs = np.arange(1, order + 1) * diff_knots + lower_knots = inner_knots[0] - diffs[::-1] + upper_knots = inner_knots[-1] + diffs + all_knots = np.concatenate((lower_knots, inner_knots, upper_knots)) + else: + all_knots = np.concatenate(([lower_bound, upper_bound] * order, + inner_knots)) + all_knots.sort() + + return all_knots + + +def _get_integration_points(knots, k_points=3): + """add points to each subinterval defined by knots + + inserts k_points between each two consecutive knots + """ + k_points = k_points + 1 + knots = np.unique(knots) + dxi = np.arange(k_points) / k_points + dxk = np.diff(knots) + dx = dxk[:, None] * dxi + x = np.concatenate(((knots[:-1, None] + dx).ravel(), [knots[-1]])) + return x + + +def get_covder2(smoother, k_points=3, integration_points=None, + skip_ctransf=False, deriv=2): + """ + Approximate integral of cross product of second derivative of smoother + + This uses scipy.integrate simps to compute an approximation to the + integral of the smoother derivative cross-product at knots plus k_points + in between knots. + """ + try: + from scipy.integrate import simpson + except ImportError: + # Remove after SciPy 1.7 is the minimum version + from scipy.integrate import simps as simpson + knots = smoother.knots + if integration_points is None: + x = _get_integration_points(knots, k_points=k_points) + else: + x = integration_points + d2 = smoother.transform(x, deriv=deriv, skip_ctransf=skip_ctransf) + covd2 = simpson(d2[:, :, None] * d2[:, None, :], x=x, axis=0) + return covd2 + + +# TODO: this function should be deleted +def make_poly_basis(x, degree, intercept=True): + ''' + given a vector x returns poly=(1, x, x^2, ..., x^degree) + and its first and second derivative + ''' + + if intercept: + start = 0 + else: + start = 1 + + nobs = len(x) + basis = np.zeros(shape=(nobs, degree + 1 - start)) + der_basis = np.zeros(shape=(nobs, degree + 1 - start)) + der2_basis = np.zeros(shape=(nobs, degree + 1 - start)) + + for i in range(start, degree + 1): + basis[:, i - start] = x ** i + der_basis[:, i - start] = i * x ** (i - 1) + der2_basis[:, i - start] = i * (i - 1) * x ** (i - 2) + + return basis, der_basis, der2_basis + + +# TODO: try to include other kinds of splines from patsy +# x = np.linspace(0, 1, 30) +# df = 10 +# degree = 3 +# from patsy.mgcv_cubic_splines import cc, cr, te +# all_knots, lower, upper, inner = compute_all_knots(x, df, degree) +# result = cc(x, df=df, knots=all_knots, lower_bound=lower, upper_bound=upper, +# constraints=None) +# +# import matplotlib.pyplot as plt +# +# result = np.array(result) +# print(result.shape) +# plt.plot(result.T) +# plt.show() + +class UnivariateGamSmoother(with_metaclass(ABCMeta)): + """Base Class for single smooth component + """ + def __init__(self, x, constraints=None, variable_name='x'): + self.x = x + self.constraints = constraints + self.variable_name = variable_name + self.nobs, self.k_variables = len(x), 1 + + base4 = self._smooth_basis_for_single_variable() + if constraints == 'center': + constraints = base4[0].mean(0)[None, :] + + if constraints is not None and not isinstance(constraints, str): + ctransf = transf_constraints(constraints) + self.ctransf = ctransf + else: + # subclasses might set ctransf directly + # only used if constraints is None + if not hasattr(self, 'ctransf'): + self.ctransf = None + + self.basis, self.der_basis, self.der2_basis, self.cov_der2 = base4 + if self.ctransf is not None: + ctransf = self.ctransf + # transform attributes that are not None + if base4[0] is not None: + self.basis = base4[0].dot(ctransf) + if base4[1] is not None: + self.der_basis = base4[1].dot(ctransf) + if base4[2] is not None: + self.der2_basis = base4[2].dot(ctransf) + if base4[3] is not None: + self.cov_der2 = ctransf.T.dot(base4[3]).dot(ctransf) + + self.dim_basis = self.basis.shape[1] + self.col_names = [self.variable_name + "_s" + str(i) + for i in range(self.dim_basis)] + + @abstractmethod + def _smooth_basis_for_single_variable(self): + return + + +class UnivariateGenericSmoother(UnivariateGamSmoother): + """Generic single smooth component + """ + def __init__(self, x, basis, der_basis, der2_basis, cov_der2, + variable_name='x'): + self.basis = basis + self.der_basis = der_basis + self.der2_basis = der2_basis + self.cov_der2 = cov_der2 + + super().__init__(x, variable_name=variable_name) + + def _smooth_basis_for_single_variable(self): + return self.basis, self.der_basis, self.der2_basis, self.cov_der2 + + +class UnivariatePolynomialSmoother(UnivariateGamSmoother): + """polynomial single smooth component + """ + def __init__(self, x, degree, variable_name='x'): + self.degree = degree + super().__init__(x, variable_name=variable_name) + + def _smooth_basis_for_single_variable(self): + # TODO: unclear description + """ + given a vector x returns poly=(1, x, x^2, ..., x^degree) + and its first and second derivative + """ + + basis = np.zeros(shape=(self.nobs, self.degree)) + der_basis = np.zeros(shape=(self.nobs, self.degree)) + der2_basis = np.zeros(shape=(self.nobs, self.degree)) + for i in range(self.degree): + dg = i + 1 + basis[:, i] = self.x ** dg + der_basis[:, i] = dg * self.x ** (dg - 1) + if dg > 1: + der2_basis[:, i] = dg * (dg - 1) * self.x ** (dg - 2) + else: + der2_basis[:, i] = 0 + + cov_der2 = np.dot(der2_basis.T, der2_basis) + + return basis, der_basis, der2_basis, cov_der2 + + +class UnivariateBSplines(UnivariateGamSmoother): + """B-Spline single smooth component + + This creates and holds the B-Spline basis function for one + component. + + Parameters + ---------- + x : ndarray, 1-D + underlying explanatory variable for smooth terms. + df : int + number of basis functions or degrees of freedom + degree : int + degree of the spline + include_intercept : bool + If False, then the basis functions are transformed so that they + do not include a constant. This avoids perfect collinearity if + a constant or several components are included in the model. + constraints : {None, str, array} + Constraints are used to transform the basis functions to satisfy + those constraints. + `constraints = 'center'` applies a linear transform to remove the + constant and center the basis functions. + variable_name : {None, str} + The name for the underlying explanatory variable, x, used in for + creating the column and parameter names for the basis functions. + covder2_kwds : {None, dict} + options for computing the penalty matrix from the second derivative + of the spline. + knot_kwds : {None, list[dict]} + option for the knot selection. + By default knots are selected in the same way as in patsy, however the + number of knots is independent of keeping or removing the constant. + Interior knot selection is based on quantiles of the data and is the + same in patsy and mgcv. Boundary points are at the limits of the data + range. + The available options use with `get_knots_bsplines` are + + - knots : None or array + interior knots + - spacing : 'quantile' or 'equal' + - lower_bound : None or float + location of lower boundary knots, all boundary knots are at the same + point + - upper_bound : None or float + location of upper boundary knots, all boundary knots are at the same + point + - all_knots : None or array + If all knots are provided, then those will be taken as given and + all other options will be ignored. + """ + def __init__(self, x, df, degree=3, include_intercept=False, + constraints=None, variable_name='x', + covder2_kwds=None, **knot_kwds): + self.degree = degree + self.df = df + self.include_intercept = include_intercept + self.knots = get_knots_bsplines(x, degree=degree, df=df, **knot_kwds) + self.covder2_kwds = (covder2_kwds if covder2_kwds is not None + else {}) + super().__init__( + x, constraints=constraints, variable_name=variable_name + ) + + def _smooth_basis_for_single_variable(self): + basis, der_basis, der2_basis = _eval_bspline_basis( + self.x, self.knots, self.degree, + include_intercept=self.include_intercept) + # cov_der2 = np.dot(der2_basis.T, der2_basis) + + cov_der2 = get_covder2(self, skip_ctransf=True, + **self.covder2_kwds) + + return basis, der_basis, der2_basis, cov_der2 + + def transform(self, x_new, deriv=0, skip_ctransf=False): + """create the spline basis for new observations + + The main use of this stateful transformation is for prediction + using the same specification of the spline basis. + + Parameters + ---------- + x_new : ndarray + observations of the underlying explanatory variable + deriv : int + which derivative of the spline basis to compute + This is an options for internal computation. + skip_ctransf : bool + whether to skip the constraint transform + This is an options for internal computation. + + Returns + ------- + basis : ndarray + design matrix for the spline basis for given ``x_new`` + """ + + if x_new is None: + x_new = self.x + exog = _eval_bspline_basis(x_new, self.knots, self.degree, + deriv=deriv, + include_intercept=self.include_intercept) + + # ctransf does not exist yet when cov_der2 is computed + ctransf = getattr(self, 'ctransf', None) + if ctransf is not None and not skip_ctransf: + exog = exog.dot(self.ctransf) + return exog + + +class UnivariateCubicSplines(UnivariateGamSmoother): + """Cubic Spline single smooth component + + Cubic splines as described in the wood's book in chapter 3 + """ + + def __init__(self, x, df, constraints=None, transform='domain', + variable_name='x'): + + self.degree = 3 + self.df = df + self.transform_data_method = transform + + self.x = x = self.transform_data(x, initialize=True) + self.knots = _equally_spaced_knots(x, df) + super().__init__( + x, constraints=constraints, variable_name=variable_name + ) + + def transform_data(self, x, initialize=False): + tm = self.transform_data_method + if tm is None: + return x + + if initialize is True: + if tm == 'domain': + self.domain_low = x.min(0) + self.domain_upp = x.max(0) + elif isinstance(tm, tuple): + self.domain_low = tm[0] + self.domain_upp = tm[1] + self.transform_data_method = 'domain' + else: + raise ValueError("transform should be None, 'domain' " + "or a tuple") + self.domain_diff = self.domain_upp - self.domain_low + + if self.transform_data_method == 'domain': + x = (x - self.domain_low) / self.domain_diff + return x + else: + raise ValueError("incorrect transform_data_method") + + def _smooth_basis_for_single_variable(self): + + basis = self._splines_x()[:, :-1] + # demean except for constant, does not affect derivatives + if not self.constraints == 'none': + self.transf_mean = basis[:, 1:].mean(0) + basis[:, 1:] -= self.transf_mean + else: + self.transf_mean = np.zeros(basis.shape[1]) + s = self._splines_s()[:-1, :-1] + if not self.constraints == 'none': + ctransf = np.diag(1/np.max(np.abs(basis), axis=0)) + else: + ctransf = np.eye(basis.shape[1]) + # use np.eye to avoid rescaling + # ctransf = np.eye(basis.shape[1]) + + if self.constraints == 'no-const': + ctransf = ctransf[1:] + + self.ctransf = ctransf + + return basis, None, None, s + + def _rk(self, x, z): + p1 = ((z - 1 / 2) ** 2 - 1 / 12) * ((x - 1 / 2) ** 2 - 1 / 12) / 4 + p2 = ((np.abs(z - x) - 1 / 2) ** 4 - + 1 / 2 * (np.abs(z - x) - 1 / 2) ** 2 + + 7 / 240) / 24. + return p1 - p2 + + def _splines_x(self, x=None): + if x is None: + x = self.x + n_columns = len(self.knots) + 2 + nobs = x.shape[0] + basis = np.ones(shape=(nobs, n_columns)) + basis[:, 1] = x + # for loop equivalent to outer(x, xk, fun=rk) + for i, xi in enumerate(x): + for j, xkj in enumerate(self.knots): + s_ij = self._rk(xi, xkj) + basis[i, j + 2] = s_ij + return basis + + def _splines_s(self): + q = len(self.knots) + 2 + s = np.zeros(shape=(q, q)) + for i, x1 in enumerate(self.knots): + for j, x2 in enumerate(self.knots): + s[i + 2, j + 2] = self._rk(x1, x2) + return s + + def transform(self, x_new): + x_new = self.transform_data(x_new, initialize=False) + exog = self._splines_x(x_new) + exog[:, 1:] -= self.transf_mean + if self.ctransf is not None: + exog = exog.dot(self.ctransf) + return exog + + +class UnivariateCubicCyclicSplines(UnivariateGamSmoother): + """cyclic cubic regression spline single smooth component + + This creates and holds the Cyclic CubicSpline basis function for one + component. + + Parameters + ---------- + x : ndarray, 1-D + underlying explanatory variable for smooth terms. + df : int + number of basis functions or degrees of freedom + degree : int + degree of the spline + include_intercept : bool + If False, then the basis functions are transformed so that they + do not include a constant. This avoids perfect collinearity if + a constant or several components are included in the model. + constraints : {None, str, array} + Constraints are used to transform the basis functions to satisfy + those constraints. + `constraints = 'center'` applies a linear transform to remove the + constant and center the basis functions. + variable_name : None or str + The name for the underlying explanatory variable, x, used in for + creating the column and parameter names for the basis functions. + """ + def __init__(self, x, df, constraints=None, variable_name='x'): + self.degree = 3 + self.df = df + self.x = x + self.knots = _equally_spaced_knots(x, df) + super().__init__( + x, constraints=constraints, variable_name=variable_name + ) + + def _smooth_basis_for_single_variable(self): + basis = dmatrix("cc(x, df=" + str(self.df) + ") - 1", {"x": self.x}) + self.design_info = basis.design_info + n_inner_knots = self.df - 2 + 1 # +n_constraints + # TODO: from CubicRegressionSplines class + all_knots = _get_all_sorted_knots(self.x, n_inner_knots=n_inner_knots, + inner_knots=None, + lower_bound=None, upper_bound=None) + + b, d = self._get_b_and_d(all_knots) + s = self._get_s(b, d) + + return basis, None, None, s + + def _get_b_and_d(self, knots): + """Returns mapping of cyclic cubic spline values to 2nd derivatives. + + .. note:: See 'Generalized Additive Models', Simon N. Wood, 2006, + pp 146-147 + + Parameters + ---------- + knots : ndarray + The 1-d array knots used for cubic spline parametrization, + must be sorted in ascending order. + + Returns + ------- + b : ndarray + Array for mapping cyclic cubic spline values at knots to + second derivatives. + d : ndarray + Array for mapping cyclic cubic spline values at knots to + second derivatives. + + Notes + ----- + The penalty matrix is equal to ``s = d.T.dot(b^-1).dot(d)`` + """ + h = knots[1:] - knots[:-1] + n = knots.size - 1 + + # b and d are defined such that the penalty matrix is equivalent to: + # s = d.T.dot(b^-1).dot(d) + # reference in particular to pag 146 of Wood's book + b = np.zeros((n, n)) # the b matrix on page 146 of Wood's book + d = np.zeros((n, n)) # the d matrix on page 146 of Wood's book + + b[0, 0] = (h[n - 1] + h[0]) / 3. + b[0, n - 1] = h[n - 1] / 6. + b[n - 1, 0] = h[n - 1] / 6. + + d[0, 0] = -1. / h[0] - 1. / h[n - 1] + d[0, n - 1] = 1. / h[n - 1] + d[n - 1, 0] = 1. / h[n - 1] + + for i in range(1, n): + b[i, i] = (h[i - 1] + h[i]) / 3. + b[i, i - 1] = h[i - 1] / 6. + b[i - 1, i] = h[i - 1] / 6. + + d[i, i] = -1. / h[i - 1] - 1. / h[i] + d[i, i - 1] = 1. / h[i - 1] + d[i - 1, i] = 1. / h[i - 1] + + return b, d + + def _get_s(self, b, d): + return d.T.dot(np.linalg.inv(b)).dot(d) + + def transform(self, x_new): + exog = dmatrix(self.design_info, {"x": x_new}) + if self.ctransf is not None: + exog = exog.dot(self.ctransf) + return exog + + +class AdditiveGamSmoother(with_metaclass(ABCMeta)): + """Base class for additive smooth components + """ + def __init__(self, x, variable_names=None, include_intercept=False, + **kwargs): + + # get pandas names before using asarray + if isinstance(x, pd.DataFrame): + data_names = x.columns.tolist() + elif isinstance(x, pd.Series): + data_names = [x.name] + else: + data_names = None + + x = np.asarray(x) + + if x.ndim == 1: + self.x = x.copy() + self.x.shape = (len(x), 1) + else: + self.x = x + + self.nobs, self.k_variables = self.x.shape + if isinstance(include_intercept, bool): + self.include_intercept = [include_intercept] * self.k_variables + else: + self.include_intercept = include_intercept + + if variable_names is None: + if data_names is not None: + self.variable_names = data_names + else: + self.variable_names = ['x' + str(i) + for i in range(self.k_variables)] + else: + self.variable_names = variable_names + + self.smoothers = self._make_smoothers_list() + self.basis = np.hstack(list(smoother.basis + for smoother in self.smoothers)) + self.dim_basis = self.basis.shape[1] + self.penalty_matrices = [smoother.cov_der2 + for smoother in self.smoothers] + self.col_names = [] + for smoother in self.smoothers: + self.col_names.extend(smoother.col_names) + + self.mask = [] + last_column = 0 + for smoother in self.smoothers: + mask = np.array([False] * self.dim_basis) + mask[last_column:smoother.dim_basis + last_column] = True + last_column = last_column + smoother.dim_basis + self.mask.append(mask) + + @abstractmethod + def _make_smoothers_list(self): + pass + + def transform(self, x_new): + """create the spline basis for new observations + + The main use of this stateful transformation is for prediction + using the same specification of the spline basis. + + Parameters + ---------- + x_new: ndarray + observations of the underlying explanatory variable + + Returns + ------- + basis : ndarray + design matrix for the spline basis for given ``x_new``. + """ + if x_new.ndim == 1 and self.k_variables == 1: + x_new = x_new.reshape(-1, 1) + exog = np.hstack(list(self.smoothers[i].transform(x_new[:, i]) + for i in range(self.k_variables))) + return exog + + +class GenericSmoothers(AdditiveGamSmoother): + """generic class for additive smooth components for GAM + """ + def __init__(self, x, smoothers): + self.smoothers = smoothers + super().__init__(x, variable_names=None) + + def _make_smoothers_list(self): + return self.smoothers + + +class PolynomialSmoother(AdditiveGamSmoother): + """additive polynomial components for GAM + """ + def __init__(self, x, degrees, variable_names=None): + self.degrees = degrees + super().__init__(x, variable_names=variable_names) + + def _make_smoothers_list(self): + smoothers = [] + for v in range(self.k_variables): + uv_smoother = UnivariatePolynomialSmoother( + self.x[:, v], + degree=self.degrees[v], + variable_name=self.variable_names[v]) + smoothers.append(uv_smoother) + return smoothers + + +class BSplines(AdditiveGamSmoother): + """additive smooth components using B-Splines + + This creates and holds the B-Spline basis function for several + components. + + Parameters + ---------- + x : array_like, 1-D or 2-D + underlying explanatory variable for smooth terms. + If 2-dimensional, then observations should be in rows and + explanatory variables in columns. + df : {int, array_like[int]} + number of basis functions or degrees of freedom; should be equal + in length to the number of columns of `x`; may be an integer if + `x` has one column or is 1-D. + degree : {int, array_like[int]} + degree(s) of the spline; the same length and type rules apply as + to `df` + include_intercept : bool + If False, then the basis functions are transformed so that they + do not include a constant. This avoids perfect collinearity if + a constant or several components are included in the model. + constraints : {None, str, array} + Constraints are used to transform the basis functions to satisfy + those constraints. + `constraints = 'center'` applies a linear transform to remove the + constant and center the basis functions. + variable_names : {list[str], None} + The names for the underlying explanatory variables, x used in for + creating the column and parameter names for the basis functions. + If ``x`` is a pandas object, then the names will be taken from it. + knot_kwds : None or list of dict + option for the knot selection. + By default knots are selected in the same way as in patsy, however the + number of knots is independent of keeping or removing the constant. + Interior knot selection is based on quantiles of the data and is the + same in patsy and mgcv. Boundary points are at the limits of the data + range. + The available options use with `get_knots_bsplines` are + + - knots : None or array + interior knots + - spacing : 'quantile' or 'equal' + - lower_bound : None or float + location of lower boundary knots, all boundary knots are at the same + point + - upper_bound : None or float + location of upper boundary knots, all boundary knots are at the same + point + - all_knots : None or array + If all knots are provided, then those will be taken as given and + all other options will be ignored. + + + Attributes + ---------- + smoothers : list of univariate smooth component instances + basis : design matrix, array of spline bases columns for all components + penalty_matrices : list of penalty matrices, one for each smooth term + dim_basis : number of columns in the basis + k_variables : number of smooth components + col_names : created names for the basis columns + + There are additional attributes about the specification of the splines + and some attributes mainly for internal use. + + Notes + ----- + A constant in the spline basis function can be removed in two different + ways. + The first is by dropping one basis column and normalizing the + remaining columns. This is obtained by the default + ``include_intercept=False, constraints=None`` + The second option is by using the centering transform which is a linear + transformation of all basis functions. As a consequence of the + transformation, the B-spline basis functions do not have locally bounded + support anymore. This is obtained ``constraints='center'``. In this case + ``include_intercept`` will be automatically set to True to avoid + dropping an additional column. + """ + def __init__(self, x, df, degree, include_intercept=False, + constraints=None, variable_names=None, knot_kwds=None): + if isinstance(degree, int): + self.degrees = np.array([degree], dtype=int) + else: + self.degrees = degree + if isinstance(df, int): + self.dfs = np.array([df], dtype=int) + else: + self.dfs = df + self.knot_kwds = knot_kwds + # TODO: move attaching constraints to super call + self.constraints = constraints + if constraints == 'center': + include_intercept = True + + super().__init__( + x, + include_intercept=include_intercept, + variable_names=variable_names + ) + + def _make_smoothers_list(self): + smoothers = [] + for v in range(self.k_variables): + kwds = self.knot_kwds[v] if self.knot_kwds else {} + uv_smoother = UnivariateBSplines( + self.x[:, v], + df=self.dfs[v], degree=self.degrees[v], + include_intercept=self.include_intercept[v], + constraints=self.constraints, + variable_name=self.variable_names[v], **kwds) + smoothers.append(uv_smoother) + + return smoothers + + +class CubicSplines(AdditiveGamSmoother): + """additive smooth components using cubic splines as in Wood 2006. + + Note, these splines do NOT use the same spline basis as + ``Cubic Regression Splines``. + """ + def __init__(self, x, df, constraints='center', transform='domain', + variable_names=None): + self.dfs = df + self.constraints = constraints + self.transform = transform + super().__init__( + x, constraints=constraints, variable_names=variable_names + ) + + def _make_smoothers_list(self): + smoothers = [] + for v in range(self.k_variables): + uv_smoother = UnivariateCubicSplines( + self.x[:, v], df=self.dfs[v], + constraints=self.constraints, + transform=self.transform, + variable_name=self.variable_names[v]) + smoothers.append(uv_smoother) + + return smoothers + + +class CyclicCubicSplines(AdditiveGamSmoother): + """additive smooth components using cyclic cubic regression splines + + This spline basis is the same as in patsy. + + Parameters + ---------- + x : array_like, 1-D or 2-D + underlying explanatory variable for smooth terms. + If 2-dimensional, then observations should be in rows and + explanatory variables in columns. + df : int + numer of basis functions or degrees of freedom + constraints : {None, str, array} + Constraints are used to transform the basis functions to satisfy + those constraints. + variable_names : {list[str], None} + The names for the underlying explanatory variables, x used in for + creating the column and parameter names for the basis functions. + If ``x`` is a pandas object, then the names will be taken from it. + """ + def __init__(self, x, df, constraints=None, variable_names=None): + self.dfs = df + # TODO: move attaching constraints to super call + self.constraints = constraints + super().__init__(x, variable_names=variable_names) + + def _make_smoothers_list(self): + smoothers = [] + for v in range(self.k_variables): + uv_smoother = UnivariateCubicCyclicSplines( + self.x[:, v], + df=self.dfs[v], constraints=self.constraints, + variable_name=self.variable_names[v]) + smoothers.append(uv_smoother) + + return smoothers + +# class CubicRegressionSplines(BaseCubicSplines): +# # TODO: this class is still not tested +# +# def __init__(self, x, df=10): +# import warnings +# warnings.warn("This class is still not tested and it is probably" +# " not working properly. " +# "I suggest to use another smoother", Warning) +# +# super(CubicRegressionSplines, self).__init__(x, df) +# +# self.basis = dmatrix("cc(x, df=" + str(df) + ") - 1", {"x": x}) +# n_inner_knots = df - 2 + 1 # +n_constraints +# # TODO: ACcording to CubicRegressionSplines class this should be +# # n_inner_knots = df - 2 +# all_knots = _get_all_sorted_knots(x, n_inner_knots=n_inner_knots, +# inner_knots=None, +# lower_bound=None, upper_bound=None) +# +# b, d = self._get_b_and_d(all_knots) +# self.s = self._get_s(b, d) +# +# self.dim_basis = self.basis.shape[1] +# +# def _get_b_and_d(self, knots): +# +# h = knots[1:] - knots[:-1] +# n = knots.size - 1 +# +# # b and d are defined such that the penalty matrix is equivalent to: +# # s = d.T.dot(b^-1).dot(d) +# # reference in particular to pag 146 of Wood's book +# b = np.zeros((n, n)) # the b matrix on page 146 of Wood's book +# d = np.zeros((n, n)) # the d matrix on page 146 of Wood's book +# +# for i in range(n-2): +# d[i, i] = 1/h[i] +# d[i, i+1] = -1/h[i] - 1/h[i+1] +# d[i, i+2] = 1/h[i+1] +# +# b[i, i] = (h[i] + h[i+1])/3 +# +# for i in range(n-3): +# b[i, i+1] = h[i+1]/6 +# b[i+1, i] = h[i+1]/6 +# +# return b, d +# +# def _get_s(self, b, d): +# +# return d.T.dot(np.linalg.pinv(b)).dot(d) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/genmod/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/genmod/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..691559ca60fe92a39e770cdb5d16c42a4c5651e1 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/genmod/__init__.py @@ -0,0 +1,3 @@ +from statsmodels.tools._test_runner import PytestTester + +test = PytestTester() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/genmod/_tweedie_compound_poisson.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/genmod/_tweedie_compound_poisson.py new file mode 100644 index 0000000000000000000000000000000000000000..070415f5d8dd5dee0ae1b7cc8830f51f7f1f7bec --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/genmod/_tweedie_compound_poisson.py @@ -0,0 +1,96 @@ +""" +Private experimental module for miscellaneous Tweedie functions. + +References +---------- + +Dunn, Peter K. and Smyth, Gordon K. 2001. Tweedie family densities: methods of + evaluation. In Proceedings of the 16th International Workshop on + Statistical Modelling, Odense, Denmark, 2–6 July. + +Jørgensen, B., Demétrio, C.G.B., Kristensen, E., Banta, G.T., Petersen, H.C., + Delefosse, M.: Bias-corrected Pearson estimating functions for Taylor’s + power law applied to benthic macrofauna data. Stat. Probab. Lett. 81, + 749–758 (2011) + +Smyth G.K. and Jørgensen B. 2002. Fitting Tweedie's compound Poisson model to + insurance claims data: dispersion modelling. ASTIN Bulletin 32: 143–157 +""" + +from statsmodels.compat.scipy import apply_where + +import numpy as np +from scipy.special import gammaln + + +def _theta(mu, p): + return np.where(p == 1, np.log(mu), mu ** (1 - p) / (1 - p)) + + +def _alpha(p): + return (2 - p) / (1 - p) + + +def _logWj(y, j, p, phi): + alpha = _alpha(p) + logz = (-alpha * np.log(y) + alpha * np.log(p - 1) - (1 - alpha) * + np.log(phi) - np.log(2 - p)) + return (j * logz - gammaln(1 + j) - gammaln(-alpha * j)) + + +def kappa(mu, p): + return mu ** (2 - p) / (2 - p) + + +@np.vectorize +def _sumw(y, j_l, j_u, logWmax, p, phi): + j = np.arange(j_l, j_u + 1) + sumw = np.sum(np.exp(_logWj(y, j, p, phi) - logWmax)) + return sumw + + +def logW(y, p, phi): + alpha = _alpha(p) + jmax = y ** (2 - p) / ((2 - p) * phi) + logWmax = np.array((1 - alpha) * jmax) + tol = logWmax - 37 # Machine accuracy for 64 bit. + j = np.ceil(jmax) + while (_logWj(y, np.ceil(j), p, phi) > tol).any(): + j = np.where(_logWj(y, j, p, phi) > tol, j + 1, j) + j_u = j + j = np.floor(jmax) + j = np.where(j > 1, j, 1) + while (_logWj(y, j, p, phi) > tol).any() and (j > 1).any(): + j = np.where(_logWj(y, j, p, phi) > tol, j - 1, 1) + j_l = j + sumw = _sumw(y, j_l, j_u, logWmax, p, phi) + return logWmax + np.log(sumw) + + +def density_at_zero(y, mu, p, phi): + return np.exp(-(mu ** (2 - p)) / (phi * (2 - p))) + + +def density_otherwise(y, mu, p, phi): + theta = _theta(mu, p) + logd = logW(y, p, phi) - np.log(y) + (1 / phi * (y * theta - kappa(mu, p))) + return np.exp(logd) + + +def series_density(y, mu, p, phi): + density = apply_where( + np.array(y) > 0, (y, mu, p, phi), f1=density_otherwise, f2=density_at_zero + ) + return density + + +if __name__ == '__main__': + from scipy import stats + n = stats.poisson.rvs(.1, size=10000000) + y = stats.gamma.rvs(.1, scale=30000, size=10000000) + y = n * y + mu = stats.gamma.rvs(10, scale=30, size=10000000) + import time + t = time.time() + out = series_density(y=y, mu=mu, p=1.5, phi=20) + print(f'That took {time.time() - t} seconds') diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/genmod/api.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/genmod/api.py new file mode 100644 index 0000000000000000000000000000000000000000..ddf61d72fa0d82757e024910312c2be1cc53ba93 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/genmod/api.py @@ -0,0 +1,10 @@ +__all__ = [ + "GLM", "GEE", "OrdinalGEE", "NominalGEE", + "BinomialBayesMixedGLM", "PoissonBayesMixedGLM", + "families", "cov_struct" +] +from .generalized_linear_model import GLM +from .generalized_estimating_equations import GEE, OrdinalGEE, NominalGEE +from .bayes_mixed_glm import BinomialBayesMixedGLM, PoissonBayesMixedGLM +from . import families +from . import cov_struct diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/genmod/bayes_mixed_glm.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/genmod/bayes_mixed_glm.py new file mode 100644 index 0000000000000000000000000000000000000000..af8b5a4e6e09a1a5f1e202aaf6316b84372026b8 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/genmod/bayes_mixed_glm.py @@ -0,0 +1,1188 @@ +r""" +Bayesian inference for generalized linear mixed models. + +Currently only families without additional scale or shape parameters +are supported (binomial and Poisson). + +Two estimation approaches are supported: Laplace approximation +('maximum a posteriori'), and variational Bayes (mean field +approximation to the posterior distribution). + +All realizations of random effects are modeled to be mutually +independent in this implementation. + +The `exog_vc` matrix is the design matrix for the random effects. +Every column of `exog_vc` corresponds to an independent realization of +a random effect. These random effects have mean zero and an unknown +standard deviation. The standard deviation parameters are constrained +to be equal within subsets of the columns. When not using formulas, +these subsets are specified through the parameter `ident`. `ident` +must have the same length as the number of columns of `exog_vc`, and +two columns whose `ident` values are equal have the same standard +deviation. When formulas are used, the columns of `exog_vc` derived +from a common formula are constrained to have the same standard +deviation. + +In many applications, `exog_vc` will be sparse. A sparse matrix may +be passed when constructing a model class. If a dense matrix is +passed, it will be converted internally to a sparse matrix. There +currently is no way to avoid creating a temporary dense version of +`exog_vc` when using formulas. + +Model and parameterization +-------------------------- +The joint density of data and parameters factors as: + +.. math:: + + p(y | vc, fep) p(vc | vcp) p(vcp) p(fe) + +The terms :math:`p(vcp)` and :math:`p(fe)` are prior distributions +that are taken to be Gaussian (the :math:`vcp` parameters are log +standard deviations so the standard deviations have log-normal +distributions). The random effects distribution :math:`p(vc | vcp)` +is independent Gaussian (random effect realizations are independent +within and between values of the `ident` array). The model +:math:`p(y | vc, fep)` depends on the specific GLM being fit. +""" + +import numpy as np +from scipy.optimize import minimize +from scipy import sparse +import statsmodels.base.model as base +from statsmodels.iolib import summary2 +from statsmodels.genmod import families +import pandas as pd +import warnings +import patsy + +# Gauss-Legendre weights +glw = [ + [0.2955242247147529, -0.1488743389816312], + [0.2955242247147529, 0.1488743389816312], + [0.2692667193099963, -0.4333953941292472], + [0.2692667193099963, 0.4333953941292472], + [0.2190863625159820, -0.6794095682990244], + [0.2190863625159820, 0.6794095682990244], + [0.1494513491505806, -0.8650633666889845], + [0.1494513491505806, 0.8650633666889845], + [0.0666713443086881, -0.9739065285171717], + [0.0666713443086881, 0.9739065285171717], +] + +_init_doc = r""" + Generalized Linear Mixed Model with Bayesian estimation + + The class implements the Laplace approximation to the posterior + distribution (`fit_map`) and a variational Bayes approximation to + the posterior (`fit_vb`). See the two fit method docstrings for + more information about the fitting approaches. + + Parameters + ---------- + endog : array_like + Vector of response values. + exog : array_like + Array of covariates for the fixed effects part of the mean + structure. + exog_vc : array_like + Array of covariates for the random part of the model. A + scipy.sparse array may be provided, or else the passed + array will be converted to sparse internally. + ident : array_like + Array of integer labels showing which random terms (columns + of `exog_vc`) have a common variance. + vcp_p : float + Prior standard deviation for variance component parameters + (the prior standard deviation of log(s) is vcp_p, where s is + the standard deviation of a random effect). + fe_p : float + Prior standard deviation for fixed effects parameters. + family : statsmodels.genmod.families instance + The GLM family. + fep_names : list[str] + The names of the fixed effects parameters (corresponding to + columns of exog). If None, default names are constructed. + vcp_names : list[str] + The names of the variance component parameters (corresponding + to distinct labels in ident). If None, default names are + constructed. + vc_names : list[str] + The names of the random effect realizations. + + Returns + ------- + MixedGLMResults object + + Notes + ----- + There are three types of values in the posterior distribution: + fixed effects parameters (fep), corresponding to the columns of + `exog`, random effects realizations (vc), corresponding to the + columns of `exog_vc`, and the standard deviations of the random + effects realizations (vcp), corresponding to the unique integer + labels in `ident`. + + All random effects are modeled as being independent Gaussian + values (given the variance structure parameters). Every column of + `exog_vc` has a distinct realized random effect that is used to + form the linear predictors. The elements of `ident` determine the + distinct variance structure parameters. Two random effect + realizations that have the same value in `ident` have the same + variance. When fitting with a formula, `ident` is constructed + internally (each element of `vc_formulas` yields a distinct label + in `ident`). + + The random effect standard deviation parameters (`vcp`) have + log-normal prior distributions with mean 0 and standard deviation + `vcp_p`. + + Note that for some families, e.g. Binomial, the posterior mode may + be difficult to find numerically if `vcp_p` is set to too large of + a value. Setting `vcp_p` to 0.5 seems to work well. + + The prior for the fixed effects parameters is Gaussian with mean 0 + and standard deviation `fe_p`. It is recommended that quantitative + covariates be standardized. + + Examples + --------{example} + + + References + ---------- + Introduction to generalized linear mixed models: + https://stats.idre.ucla.edu/other/mult-pkg/introduction-to-generalized-linear-mixed-models + + SAS documentation: + https://support.sas.com/documentation/cdl/en/statug/63033/HTML/default/viewer.htm#statug_intromix_a0000000215.htm + + An assessment of estimation methods for generalized linear mixed + models with binary outcomes + https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3866838/ + """ + +# The code in the example should be identical to what appears in +# the test_doc_examples unit test +_logit_example = """ + A binomial (logistic) random effects model with random intercepts + for villages and random slopes for each year within each village: + + >>> random = {"a": '0 + C(Village)', "b": '0 + C(Village)*year_cen'} + >>> model = BinomialBayesMixedGLM.from_formula( + 'y ~ year_cen', random, data) + >>> result = model.fit_vb() +""" + +# The code in the example should be identical to what appears in +# the test_doc_examples unit test +_poisson_example = """ + A Poisson random effects model with random intercepts for villages + and random slopes for each year within each village: + + >>> random = {"a": '0 + C(Village)', "b": '0 + C(Village)*year_cen'} + >>> model = PoissonBayesMixedGLM.from_formula( + 'y ~ year_cen', random, data) + >>> result = model.fit_vb() +""" + + +class _BayesMixedGLM(base.Model): + def __init__(self, + endog, + exog, + exog_vc=None, + ident=None, + family=None, + vcp_p=1, + fe_p=2, + fep_names=None, + vcp_names=None, + vc_names=None, + **kwargs): + + if exog.ndim == 1: + if isinstance(exog, np.ndarray): + exog = exog[:, None] + else: + exog = pd.DataFrame(exog) + + if exog.ndim != 2: + msg = "'exog' must have one or two columns" + raise ValueError(msg) + + if exog_vc.ndim == 1: + if isinstance(exog_vc, np.ndarray): + exog_vc = exog_vc[:, None] + else: + exog_vc = pd.DataFrame(exog_vc) + + if exog_vc.ndim != 2: + msg = "'exog_vc' must have one or two columns" + raise ValueError(msg) + + ident = np.asarray(ident) + if ident.ndim != 1: + msg = "ident must be a one-dimensional array" + raise ValueError(msg) + + if len(ident) != exog_vc.shape[1]: + msg = "len(ident) should match the number of columns of exog_vc" + raise ValueError(msg) + + if not np.issubdtype(ident.dtype, np.integer): + msg = "ident must have an integer dtype" + raise ValueError(msg) + + # Get the fixed effects parameter names + if fep_names is None: + if hasattr(exog, "columns"): + fep_names = exog.columns.tolist() + else: + fep_names = ["FE_%d" % (k + 1) for k in range(exog.shape[1])] + + # Get the variance parameter names + if vcp_names is None: + vcp_names = ["VC_%d" % (k + 1) for k in range(int(max(ident)) + 1)] + else: + if len(vcp_names) != len(set(ident)): + msg = "The lengths of vcp_names and ident should be the same" + raise ValueError(msg) + + if not sparse.issparse(exog_vc): + exog_vc = sparse.csr_matrix(exog_vc) + + ident = ident.astype(int) + vcp_p = float(vcp_p) + fe_p = float(fe_p) + + # Number of fixed effects parameters + if exog is None: + k_fep = 0 + else: + k_fep = exog.shape[1] + + # Number of variance component structure parameters and + # variance component realizations. + if exog_vc is None: + k_vc = 0 + k_vcp = 0 + else: + k_vc = exog_vc.shape[1] + k_vcp = max(ident) + 1 + + # power might be better but not available in older scipy + exog_vc2 = exog_vc.multiply(exog_vc) + + super().__init__(endog, exog, **kwargs) + + self.exog_vc = exog_vc + self.exog_vc2 = exog_vc2 + self.ident = ident + self.family = family + self.k_fep = k_fep + self.k_vc = k_vc + self.k_vcp = k_vcp + self.fep_names = fep_names + self.vcp_names = vcp_names + self.vc_names = vc_names + self.fe_p = fe_p + self.vcp_p = vcp_p + self.names = fep_names + vcp_names + if vc_names is not None: + self.names += vc_names + + def _unpack(self, vec): + + ii = 0 + + # Fixed effects parameters + fep = vec[:ii + self.k_fep] + ii += self.k_fep + + # Variance component structure parameters (standard + # deviations). These are on the log scale. The standard + # deviation for random effect j is exp(vcp[ident[j]]). + vcp = vec[ii:ii + self.k_vcp] + ii += self.k_vcp + + # Random effect realizations + vc = vec[ii:] + + return fep, vcp, vc + + def logposterior(self, params): + """ + The overall log-density: log p(y, fe, vc, vcp). + + This differs by an additive constant from the log posterior + log p(fe, vc, vcp | y). + """ + + fep, vcp, vc = self._unpack(params) + + # Contributions from p(y | x, vc) + lp = 0 + if self.k_fep > 0: + lp += np.dot(self.exog, fep) + if self.k_vc > 0: + lp += self.exog_vc.dot(vc) + + mu = self.family.link.inverse(lp) + ll = self.family.loglike(self.endog, mu) + + if self.k_vc > 0: + + # Contributions from p(vc | vcp) + vcp0 = vcp[self.ident] + s = np.exp(vcp0) + ll -= 0.5 * np.sum(vc**2 / s**2) + np.sum(vcp0) + + # Contributions from p(vc) + ll -= 0.5 * np.sum(vcp**2 / self.vcp_p**2) + + # Contributions from p(fep) + if self.k_fep > 0: + ll -= 0.5 * np.sum(fep**2 / self.fe_p**2) + + return ll + + def logposterior_grad(self, params): + """ + The gradient of the log posterior. + """ + + fep, vcp, vc = self._unpack(params) + + lp = 0 + if self.k_fep > 0: + lp += np.dot(self.exog, fep) + if self.k_vc > 0: + lp += self.exog_vc.dot(vc) + + mu = self.family.link.inverse(lp) + + score_factor = (self.endog - mu) / self.family.link.deriv(mu) + score_factor /= self.family.variance(mu) + + te = [None, None, None] + + # Contributions from p(y | x, z, vc) + if self.k_fep > 0: + te[0] = np.dot(score_factor, self.exog) + if self.k_vc > 0: + te[2] = self.exog_vc.transpose().dot(score_factor) + + if self.k_vc > 0: + # Contributions from p(vc | vcp) + # vcp0 = vcp[self.ident] + # s = np.exp(vcp0) + # ll -= 0.5 * np.sum(vc**2 / s**2) + np.sum(vcp0) + vcp0 = vcp[self.ident] + s = np.exp(vcp0) + u = vc**2 / s**2 - 1 + te[1] = np.bincount(self.ident, weights=u) + te[2] -= vc / s**2 + + # Contributions from p(vcp) + # ll -= 0.5 * np.sum(vcp**2 / self.vcp_p**2) + te[1] -= vcp / self.vcp_p**2 + + # Contributions from p(fep) + if self.k_fep > 0: + te[0] -= fep / self.fe_p**2 + + te = [x for x in te if x is not None] + + return np.concatenate(te) + + def _get_start(self): + start_fep = np.zeros(self.k_fep) + start_vcp = np.ones(self.k_vcp) + start_vc = np.random.normal(size=self.k_vc) + start = np.concatenate((start_fep, start_vcp, start_vc)) + return start + + @classmethod + def from_formula(cls, + formula, + vc_formulas, + data, + family=None, + vcp_p=1, + fe_p=2): + """ + Fit a BayesMixedGLM using a formula. + + Parameters + ---------- + formula : str + Formula for the endog and fixed effects terms (use ~ to + separate dependent and independent expressions). + vc_formulas : dictionary + vc_formulas[name] is a one-sided formula that creates one + collection of random effects with a common variance + parameter. If using categorical (factor) variables to + produce variance components, note that generally `0 + ...` + should be used so that an intercept is not included. + data : data frame + The data to which the formulas are applied. + family : genmod.families instance + A GLM family. + vcp_p : float + The prior standard deviation for the logarithms of the standard + deviations of the random effects. + fe_p : float + The prior standard deviation for the fixed effects parameters. + """ + + ident = [] + exog_vc = [] + vcp_names = [] + j = 0 + for na, fml in vc_formulas.items(): + mat = patsy.dmatrix(fml, data, return_type='dataframe') + exog_vc.append(mat) + vcp_names.append(na) + ident.append(j * np.ones(mat.shape[1], dtype=np.int_)) + j += 1 + exog_vc = pd.concat(exog_vc, axis=1) + vc_names = exog_vc.columns.tolist() + + ident = np.concatenate(ident) + + model = super().from_formula( + formula, + data=data, + family=family, + subset=None, + exog_vc=exog_vc, + ident=ident, + vc_names=vc_names, + vcp_names=vcp_names, + fe_p=fe_p, + vcp_p=vcp_p) + + return model + + def fit(self, method="BFGS", minim_opts=None): + """ + fit is equivalent to fit_map. + + See fit_map for parameter information. + + Use `fit_vb` to fit the model using variational Bayes. + """ + self.fit_map(method, minim_opts) + + def fit_map(self, method="BFGS", minim_opts=None, scale_fe=False): + """ + Construct the Laplace approximation to the posterior distribution. + + Parameters + ---------- + method : str + Optimization method for finding the posterior mode. + minim_opts : dict + Options passed to scipy.minimize. + scale_fe : bool + If True, the columns of the fixed effects design matrix + are centered and scaled to unit variance before fitting + the model. The results are back-transformed so that the + results are presented on the original scale. + + Returns + ------- + BayesMixedGLMResults instance. + """ + + if scale_fe: + mn = self.exog.mean(0) + sc = self.exog.std(0) + self._exog_save = self.exog + self.exog = self.exog.copy() + ixs = np.flatnonzero(sc > 1e-8) + self.exog[:, ixs] -= mn[ixs] + self.exog[:, ixs] /= sc[ixs] + + def fun(params): + return -self.logposterior(params) + + def grad(params): + return -self.logposterior_grad(params) + + start = self._get_start() + + r = minimize(fun, start, method=method, jac=grad, options=minim_opts) + if not r.success: + msg = ("Laplace fitting did not converge, |gradient|=%.6f" % + np.sqrt(np.sum(r.jac**2))) + warnings.warn(msg) + + from statsmodels.tools.numdiff import approx_fprime + hess = approx_fprime(r.x, grad) + cov = np.linalg.inv(hess) + + params = r.x + + if scale_fe: + self.exog = self._exog_save + del self._exog_save + params[ixs] /= sc[ixs] + cov[ixs, :][:, ixs] /= np.outer(sc[ixs], sc[ixs]) + + return BayesMixedGLMResults(self, params, cov, optim_retvals=r) + + def predict(self, params, exog=None, linear=False): + """ + Return the fitted mean structure. + + Parameters + ---------- + params : array_like + The parameter vector, may be the full parameter vector, or may + be truncated to include only the mean parameters. + exog : array_like + The design matrix for the mean structure. If omitted, use the + model's design matrix. + linear : bool + If True, return the linear predictor without passing through the + link function. + + Returns + ------- + A 1-dimensional array of predicted values + """ + + if exog is None: + exog = self.exog + + q = exog.shape[1] + pr = np.dot(exog, params[0:q]) + + if not linear: + pr = self.family.link.inverse(pr) + + return pr + + +class _VariationalBayesMixedGLM: + """ + A mixin providing generic (not family-specific) methods for + variational Bayes mean field fitting. + """ + + # Integration range (from -rng to +rng). The integrals are with + # respect to a standard Gaussian distribution so (-5, 5) will be + # sufficient in many cases. + rng = 5 + + verbose = False + + # Returns the mean and variance of the linear predictor under the + # given distribution parameters. + def _lp_stats(self, fep_mean, fep_sd, vc_mean, vc_sd): + + tm = np.dot(self.exog, fep_mean) + tv = np.dot(self.exog**2, fep_sd**2) + tm += self.exog_vc.dot(vc_mean) + tv += self.exog_vc2.dot(vc_sd**2) + + return tm, tv + + def vb_elbo_base(self, h, tm, fep_mean, vcp_mean, vc_mean, fep_sd, vcp_sd, + vc_sd): + """ + Returns the evidence lower bound (ELBO) for the model. + + This function calculates the family-specific ELBO function + based on information provided from a subclass. + + Parameters + ---------- + h : function mapping 1d vector to 1d vector + The contribution of the model to the ELBO function can be + expressed as y_i*lp_i + Eh_i(z), where y_i and lp_i are + the response and linear predictor for observation i, and z + is a standard normal random variable. This formulation + can be achieved for any GLM with a canonical link + function. + """ + + # p(y | vc) contributions + iv = 0 + for w in glw: + z = self.rng * w[1] + iv += w[0] * h(z) * np.exp(-z**2 / 2) + iv /= np.sqrt(2 * np.pi) + iv *= self.rng + iv += self.endog * tm + iv = iv.sum() + + # p(vc | vcp) * p(vcp) * p(fep) contributions + iv += self._elbo_common(fep_mean, fep_sd, vcp_mean, vcp_sd, vc_mean, + vc_sd) + + r = (iv + np.sum(np.log(fep_sd)) + np.sum(np.log(vcp_sd)) + np.sum( + np.log(vc_sd))) + + return r + + def vb_elbo_grad_base(self, h, tm, tv, fep_mean, vcp_mean, vc_mean, fep_sd, + vcp_sd, vc_sd): + """ + Return the gradient of the ELBO function. + + See vb_elbo_base for parameters. + """ + + fep_mean_grad = 0. + fep_sd_grad = 0. + vcp_mean_grad = 0. + vcp_sd_grad = 0. + vc_mean_grad = 0. + vc_sd_grad = 0. + + # p(y | vc) contributions + for w in glw: + z = self.rng * w[1] + u = h(z) * np.exp(-z**2 / 2) / np.sqrt(2 * np.pi) + r = u / np.sqrt(tv) + fep_mean_grad += w[0] * np.dot(u, self.exog) + vc_mean_grad += w[0] * self.exog_vc.transpose().dot(u) + fep_sd_grad += w[0] * z * np.dot(r, self.exog**2 * fep_sd) + v = self.exog_vc2.multiply(vc_sd).transpose().dot(r) + v = np.squeeze(np.asarray(v)) + vc_sd_grad += w[0] * z * v + + fep_mean_grad *= self.rng + vc_mean_grad *= self.rng + fep_sd_grad *= self.rng + vc_sd_grad *= self.rng + fep_mean_grad += np.dot(self.endog, self.exog) + vc_mean_grad += self.exog_vc.transpose().dot(self.endog) + + (fep_mean_grad_i, fep_sd_grad_i, vcp_mean_grad_i, vcp_sd_grad_i, + vc_mean_grad_i, vc_sd_grad_i) = self._elbo_grad_common( + fep_mean, fep_sd, vcp_mean, vcp_sd, vc_mean, vc_sd) + + fep_mean_grad += fep_mean_grad_i + fep_sd_grad += fep_sd_grad_i + vcp_mean_grad += vcp_mean_grad_i + vcp_sd_grad += vcp_sd_grad_i + vc_mean_grad += vc_mean_grad_i + vc_sd_grad += vc_sd_grad_i + + fep_sd_grad += 1 / fep_sd + vcp_sd_grad += 1 / vcp_sd + vc_sd_grad += 1 / vc_sd + + mean_grad = np.concatenate((fep_mean_grad, vcp_mean_grad, + vc_mean_grad)) + sd_grad = np.concatenate((fep_sd_grad, vcp_sd_grad, vc_sd_grad)) + + if self.verbose: + print( + "|G|=%f" % np.sqrt(np.sum(mean_grad**2) + np.sum(sd_grad**2))) + + return mean_grad, sd_grad + + def fit_vb(self, + mean=None, + sd=None, + fit_method="BFGS", + minim_opts=None, + scale_fe=False, + verbose=False): + """ + Fit a model using the variational Bayes mean field approximation. + + Parameters + ---------- + mean : array_like + Starting value for VB mean vector + sd : array_like + Starting value for VB standard deviation vector + fit_method : str + Algorithm for scipy.minimize + minim_opts : dict + Options passed to scipy.minimize + scale_fe : bool + If true, the columns of the fixed effects design matrix + are centered and scaled to unit variance before fitting + the model. The results are back-transformed so that the + results are presented on the original scale. + verbose : bool + If True, print the gradient norm to the screen each time + it is calculated. + + Notes + ----- + The goal is to find a factored Gaussian approximation + q1*q2*... to the posterior distribution, approximately + minimizing the KL divergence from the factored approximation + to the actual posterior. The KL divergence, or ELBO function + has the form + + E* log p(y, fe, vcp, vc) - E* log q + + where E* is expectation with respect to the product of qj. + + References + ---------- + Blei, Kucukelbir, McAuliffe (2017). Variational Inference: A + review for Statisticians + https://arxiv.org/pdf/1601.00670.pdf + """ + + self.verbose = verbose + + if scale_fe: + mn = self.exog.mean(0) + sc = self.exog.std(0) + self._exog_save = self.exog + self.exog = self.exog.copy() + ixs = np.flatnonzero(sc > 1e-8) + self.exog[:, ixs] -= mn[ixs] + self.exog[:, ixs] /= sc[ixs] + + n = self.k_fep + self.k_vcp + self.k_vc + ml = self.k_fep + self.k_vcp + self.k_vc + if mean is None: + m = np.zeros(n) + else: + if len(mean) != ml: + raise ValueError( + "mean has incorrect length, %d != %d" % (len(mean), ml)) + m = mean.copy() + if sd is None: + s = -0.5 + 0.1 * np.random.normal(size=n) + else: + if len(sd) != ml: + raise ValueError( + "sd has incorrect length, %d != %d" % (len(sd), ml)) + + # s is parametrized on the log-scale internally when + # optimizing the ELBO function (this is transparent to the + # caller) + s = np.log(sd) + + # Do not allow the variance parameter starting mean values to + # be too small. + i1, i2 = self.k_fep, self.k_fep + self.k_vcp + m[i1:i2] = np.where(m[i1:i2] < -1, -1, m[i1:i2]) + + # Do not allow the posterior standard deviation starting values + # to be too small. + s = np.where(s < -1, -1, s) + + def elbo(x): + n = len(x) // 2 + return -self.vb_elbo(x[:n], np.exp(x[n:])) + + def elbo_grad(x): + n = len(x) // 2 + gm, gs = self.vb_elbo_grad(x[:n], np.exp(x[n:])) + gs *= np.exp(x[n:]) + return -np.concatenate((gm, gs)) + + start = np.concatenate((m, s)) + mm = minimize( + elbo, start, jac=elbo_grad, method=fit_method, options=minim_opts) + if not mm.success: + warnings.warn("VB fitting did not converge") + + n = len(mm.x) // 2 + params = mm.x[0:n] + va = np.exp(2 * mm.x[n:]) + + if scale_fe: + self.exog = self._exog_save + del self._exog_save + params[ixs] /= sc[ixs] + va[ixs] /= sc[ixs]**2 + + return BayesMixedGLMResults(self, params, va, mm) + + # Handle terms in the ELBO that are common to all models. + def _elbo_common(self, fep_mean, fep_sd, vcp_mean, vcp_sd, vc_mean, vc_sd): + + iv = 0 + + # p(vc | vcp) contributions + m = vcp_mean[self.ident] + s = vcp_sd[self.ident] + iv -= np.sum((vc_mean**2 + vc_sd**2) * np.exp(2 * (s**2 - m))) / 2 + iv -= np.sum(m) + + # p(vcp) contributions + iv -= 0.5 * (vcp_mean**2 + vcp_sd**2).sum() / self.vcp_p**2 + + # p(b) contributions + iv -= 0.5 * (fep_mean**2 + fep_sd**2).sum() / self.fe_p**2 + + return iv + + def _elbo_grad_common(self, fep_mean, fep_sd, vcp_mean, vcp_sd, vc_mean, + vc_sd): + + # p(vc | vcp) contributions + m = vcp_mean[self.ident] + s = vcp_sd[self.ident] + u = vc_mean**2 + vc_sd**2 + ve = np.exp(2 * (s**2 - m)) + dm = u * ve - 1 + ds = -2 * u * ve * s + vcp_mean_grad = np.bincount(self.ident, weights=dm) + vcp_sd_grad = np.bincount(self.ident, weights=ds) + + vc_mean_grad = -vc_mean.copy() * ve + vc_sd_grad = -vc_sd.copy() * ve + + # p(vcp) contributions + vcp_mean_grad -= vcp_mean / self.vcp_p**2 + vcp_sd_grad -= vcp_sd / self.vcp_p**2 + + # p(b) contributions + fep_mean_grad = -fep_mean.copy() / self.fe_p**2 + fep_sd_grad = -fep_sd.copy() / self.fe_p**2 + + return (fep_mean_grad, fep_sd_grad, vcp_mean_grad, vcp_sd_grad, + vc_mean_grad, vc_sd_grad) + + +class BayesMixedGLMResults: + """ + Class to hold results from a Bayesian estimation of a Mixed GLM model. + + Attributes + ---------- + fe_mean : array_like + Posterior mean of the fixed effects coefficients. + fe_sd : array_like + Posterior standard deviation of the fixed effects coefficients + vcp_mean : array_like + Posterior mean of the logged variance component standard + deviations. + vcp_sd : array_like + Posterior standard deviation of the logged variance component + standard deviations. + vc_mean : array_like + Posterior mean of the random coefficients + vc_sd : array_like + Posterior standard deviation of the random coefficients + """ + + def __init__(self, model, params, cov_params, optim_retvals=None): + + self.model = model + self.params = params + self._cov_params = cov_params + self.optim_retvals = optim_retvals + + self.fe_mean, self.vcp_mean, self.vc_mean = (model._unpack(params)) + + if cov_params.ndim == 2: + cp = np.diag(cov_params) + else: + cp = cov_params + self.fe_sd, self.vcp_sd, self.vc_sd = model._unpack(cp) + self.fe_sd = np.sqrt(self.fe_sd) + self.vcp_sd = np.sqrt(self.vcp_sd) + self.vc_sd = np.sqrt(self.vc_sd) + + def cov_params(self): + + if hasattr(self.model.data, "frame"): + # Return the covariance matrix as a dataframe or series + na = (self.model.fep_names + self.model.vcp_names + + self.model.vc_names) + if self._cov_params.ndim == 2: + return pd.DataFrame(self._cov_params, index=na, columns=na) + else: + return pd.Series(self._cov_params, index=na) + + # Return the covariance matrix as a ndarray + return self._cov_params + + def summary(self): + + df = pd.DataFrame() + m = self.model.k_fep + self.model.k_vcp + df["Type"] = (["M" for k in range(self.model.k_fep)] + + ["V" for k in range(self.model.k_vcp)]) + + df["Post. Mean"] = self.params[0:m] + + if self._cov_params.ndim == 2: + v = np.diag(self._cov_params)[0:m] + df["Post. SD"] = np.sqrt(v) + else: + df["Post. SD"] = np.sqrt(self._cov_params[0:m]) + + # Convert variance parameters to natural scale + df["SD"] = np.exp(df["Post. Mean"]) + df["SD (LB)"] = np.exp(df["Post. Mean"] - 2 * df["Post. SD"]) + df["SD (UB)"] = np.exp(df["Post. Mean"] + 2 * df["Post. SD"]) + df["SD"] = ["%.3f" % x for x in df.SD] + df["SD (LB)"] = ["%.3f" % x for x in df["SD (LB)"]] + df["SD (UB)"] = ["%.3f" % x for x in df["SD (UB)"]] + df.loc[df.index < self.model.k_fep, "SD"] = "" + df.loc[df.index < self.model.k_fep, "SD (LB)"] = "" + df.loc[df.index < self.model.k_fep, "SD (UB)"] = "" + + df.index = self.model.fep_names + self.model.vcp_names + + summ = summary2.Summary() + summ.add_title(self.model.family.__class__.__name__ + + " Mixed GLM Results") + summ.add_df(df) + + summ.add_text("Parameter types are mean structure (M) and " + "variance structure (V)") + summ.add_text("Variance parameters are modeled as log " + "standard deviations") + + return summ + + def random_effects(self, term=None): + """ + Posterior mean and standard deviation of random effects. + + Parameters + ---------- + term : int or None + If None, results for all random effects are returned. If + an integer, returns results for a given set of random + effects. The value of `term` refers to an element of the + `ident` vector, or to a position in the `vc_formulas` + list. + + Returns + ------- + Data frame of posterior means and posterior standard + deviations of random effects. + """ + + z = self.vc_mean + s = self.vc_sd + na = self.model.vc_names + + if term is not None: + termix = self.model.vcp_names.index(term) + ii = np.flatnonzero(self.model.ident == termix) + z = z[ii] + s = s[ii] + na = [na[i] for i in ii] + + x = pd.DataFrame({"Mean": z, "SD": s}) + + if na is not None: + x.index = na + + return x + + def predict(self, exog=None, linear=False): + """ + Return predicted values for the mean structure. + + Parameters + ---------- + exog : array_like + The design matrix for the mean structure. If None, + use the model's design matrix. + linear : bool + If True, returns the linear predictor, otherwise + transform the linear predictor using the link function. + + Returns + ------- + A one-dimensional array of fitted values. + """ + + return self.model.predict(self.params, exog, linear) + + +class BinomialBayesMixedGLM(_VariationalBayesMixedGLM, _BayesMixedGLM): + + __doc__ = _init_doc.format(example=_logit_example) + + def __init__(self, + endog, + exog, + exog_vc, + ident, + vcp_p=1, + fe_p=2, + fep_names=None, + vcp_names=None, + vc_names=None): + + super().__init__( + endog, + exog, + exog_vc=exog_vc, + ident=ident, + vcp_p=vcp_p, + fe_p=fe_p, + family=families.Binomial(), + fep_names=fep_names, + vcp_names=vcp_names, + vc_names=vc_names) + + if not np.all(np.unique(endog) == np.r_[0, 1]): + msg = "endog values must be 0 and 1, and not all identical" + raise ValueError(msg) + + @classmethod + def from_formula(cls, formula, vc_formulas, data, vcp_p=1, fe_p=2): + + fam = families.Binomial() + x = _BayesMixedGLM.from_formula( + formula, vc_formulas, data, family=fam, vcp_p=vcp_p, fe_p=fe_p) + + # Copy over to the intended class structure + mod = BinomialBayesMixedGLM( + x.endog, + x.exog, + exog_vc=x.exog_vc, + ident=x.ident, + vcp_p=x.vcp_p, + fe_p=x.fe_p, + fep_names=x.fep_names, + vcp_names=x.vcp_names, + vc_names=x.vc_names) + mod.data = x.data + + return mod + + def vb_elbo(self, vb_mean, vb_sd): + """ + Returns the evidence lower bound (ELBO) for the model. + """ + + fep_mean, vcp_mean, vc_mean = self._unpack(vb_mean) + fep_sd, vcp_sd, vc_sd = self._unpack(vb_sd) + tm, tv = self._lp_stats(fep_mean, fep_sd, vc_mean, vc_sd) + + def h(z): + return -np.log(1 + np.exp(tm + np.sqrt(tv) * z)) + + return self.vb_elbo_base(h, tm, fep_mean, vcp_mean, vc_mean, fep_sd, + vcp_sd, vc_sd) + + def vb_elbo_grad(self, vb_mean, vb_sd): + """ + Returns the gradient of the model's evidence lower bound (ELBO). + """ + + fep_mean, vcp_mean, vc_mean = self._unpack(vb_mean) + fep_sd, vcp_sd, vc_sd = self._unpack(vb_sd) + tm, tv = self._lp_stats(fep_mean, fep_sd, vc_mean, vc_sd) + + def h(z): + u = tm + np.sqrt(tv) * z + x = np.zeros_like(u) + ii = np.flatnonzero(u > 0) + uu = u[ii] + x[ii] = 1 / (1 + np.exp(-uu)) + ii = np.flatnonzero(u <= 0) + uu = u[ii] + x[ii] = np.exp(uu) / (1 + np.exp(uu)) + return -x + + return self.vb_elbo_grad_base(h, tm, tv, fep_mean, vcp_mean, vc_mean, + fep_sd, vcp_sd, vc_sd) + + +class PoissonBayesMixedGLM(_VariationalBayesMixedGLM, _BayesMixedGLM): + + __doc__ = _init_doc.format(example=_poisson_example) + + def __init__(self, + endog, + exog, + exog_vc, + ident, + vcp_p=1, + fe_p=2, + fep_names=None, + vcp_names=None, + vc_names=None): + + super().__init__( + endog=endog, + exog=exog, + exog_vc=exog_vc, + ident=ident, + vcp_p=vcp_p, + fe_p=fe_p, + family=families.Poisson(), + fep_names=fep_names, + vcp_names=vcp_names, + vc_names=vc_names) + + @classmethod + def from_formula(cls, + formula, + vc_formulas, + data, + vcp_p=1, + fe_p=2, + vcp_names=None, + vc_names=None): + + fam = families.Poisson() + x = _BayesMixedGLM.from_formula( + formula, + vc_formulas, + data, + family=fam, + vcp_p=vcp_p, + fe_p=fe_p) + + # Copy over to the intended class structure + mod = PoissonBayesMixedGLM( + endog=x.endog, + exog=x.exog, + exog_vc=x.exog_vc, + ident=x.ident, + vcp_p=x.vcp_p, + fe_p=x.fe_p, + fep_names=x.fep_names, + vcp_names=x.vcp_names, + vc_names=x.vc_names) + mod.data = x.data + + return mod + + def vb_elbo(self, vb_mean, vb_sd): + """ + Returns the evidence lower bound (ELBO) for the model. + """ + + fep_mean, vcp_mean, vc_mean = self._unpack(vb_mean) + fep_sd, vcp_sd, vc_sd = self._unpack(vb_sd) + tm, tv = self._lp_stats(fep_mean, fep_sd, vc_mean, vc_sd) + + def h(z): + return -np.exp(tm + np.sqrt(tv) * z) + + return self.vb_elbo_base(h, tm, fep_mean, vcp_mean, vc_mean, fep_sd, + vcp_sd, vc_sd) + + def vb_elbo_grad(self, vb_mean, vb_sd): + """ + Returns the gradient of the model's evidence lower bound (ELBO). + """ + + fep_mean, vcp_mean, vc_mean = self._unpack(vb_mean) + fep_sd, vcp_sd, vc_sd = self._unpack(vb_sd) + tm, tv = self._lp_stats(fep_mean, fep_sd, vc_mean, vc_sd) + + def h(z): + y = -np.exp(tm + np.sqrt(tv) * z) + return y + + return self.vb_elbo_grad_base(h, tm, tv, fep_mean, vcp_mean, vc_mean, + fep_sd, vcp_sd, vc_sd) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/genmod/cov_struct.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/genmod/cov_struct.py new file mode 100644 index 0000000000000000000000000000000000000000..3506ec46d60f20cd85498e65d32e13231169601f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/genmod/cov_struct.py @@ -0,0 +1,1562 @@ +""" +Covariance models and estimators for GEE. + +Some details for the covariance calculations can be found in the Stata +docs: + +http://www.stata.com/manuals13/xtxtgee.pdf +""" +from statsmodels.compat.pandas import Appender + +from collections import defaultdict +import warnings + +import numpy as np +import pandas as pd +from scipy import linalg as spl + +from statsmodels.stats.correlation_tools import cov_nearest +from statsmodels.tools.sm_exceptions import ( + ConvergenceWarning, + NotImplementedWarning, + OutputWarning, +) +from statsmodels.tools.validation import bool_like + + +class CovStruct: + """ + Base class for correlation and covariance structures. + + An implementation of this class takes the residuals from a + regression model that has been fit to grouped data, and uses + them to estimate the within-group dependence structure of the + random errors in the model. + + The current state of the covariance structure is represented + through the value of the `dep_params` attribute. + + The default state of a newly-created instance should always be + the identity correlation matrix. + """ + + def __init__(self, cov_nearest_method="clipped"): + + # Parameters describing the dependency structure + self.dep_params = None + + # Keep track of the number of times that the covariance was + # adjusted. + self.cov_adjust = [] + + # Method for projecting the covariance matrix if it is not + # PSD. + self.cov_nearest_method = cov_nearest_method + + def initialize(self, model): + """ + Called by GEE, used by implementations that need additional + setup prior to running `fit`. + + Parameters + ---------- + model : GEE class + A reference to the parent GEE class instance. + """ + self.model = model + + def update(self, params): + """ + Update the association parameter values based on the current + regression coefficients. + + Parameters + ---------- + params : array_like + Working values for the regression parameters. + """ + raise NotImplementedError + + def covariance_matrix(self, endog_expval, index): + """ + Returns the working covariance or correlation matrix for a + given cluster of data. + + Parameters + ---------- + endog_expval : array_like + The expected values of endog for the cluster for which the + covariance or correlation matrix will be returned + index : int + The index of the cluster for which the covariance or + correlation matrix will be returned + + Returns + ------- + M : matrix + The covariance or correlation matrix of endog + is_cor : bool + True if M is a correlation matrix, False if M is a + covariance matrix + """ + raise NotImplementedError + + def covariance_matrix_solve(self, expval, index, stdev, rhs): + """ + Solves matrix equations of the form `covmat * soln = rhs` and + returns the values of `soln`, where `covmat` is the covariance + matrix represented by this class. + + Parameters + ---------- + expval : array_like + The expected value of endog for each observed value in the + group. + index : int + The group index. + stdev : array_like + The standard deviation of endog for each observation in + the group. + rhs : list/tuple of array_like + A set of right-hand sides; each defines a matrix equation + to be solved. + + Returns + ------- + soln : list/tuple of array_like + The solutions to the matrix equations. + + Notes + ----- + Returns None if the solver fails. + + Some dependence structures do not use `expval` and/or `index` + to determine the correlation matrix. Some families + (e.g. binomial) do not use the `stdev` parameter when forming + the covariance matrix. + + If the covariance matrix is singular or not SPD, it is + projected to the nearest such matrix. These projection events + are recorded in the fit_history attribute of the GEE model. + + Systems of linear equations with the covariance matrix as the + left hand side (LHS) are solved for different right hand sides + (RHS); the LHS is only factorized once to save time. + + This is a default implementation, it can be reimplemented in + subclasses to optimize the linear algebra according to the + structure of the covariance matrix. + """ + + vmat, is_cor = self.covariance_matrix(expval, index) + if is_cor: + vmat *= np.outer(stdev, stdev) + + # Factor the covariance matrix. If the factorization fails, + # attempt to condition it into a factorizable matrix. + threshold = 1e-2 + success = False + cov_adjust = 0 + for itr in range(20): + try: + vco = spl.cho_factor(vmat) + success = True + break + except np.linalg.LinAlgError: + vmat = cov_nearest(vmat, method=self.cov_nearest_method, + threshold=threshold) + threshold *= 2 + cov_adjust += 1 + msg = "At least one covariance matrix was not PSD " + msg += "and required projection." + warnings.warn(msg) + + self.cov_adjust.append(cov_adjust) + + # Last resort if we still cannot factor the covariance matrix. + if not success: + warnings.warn( + "Unable to condition covariance matrix to an SPD " + "matrix using cov_nearest", ConvergenceWarning) + vmat = np.diag(np.diag(vmat)) + vco = spl.cho_factor(vmat) + + soln = [spl.cho_solve(vco, x) for x in rhs] + return soln + + def summary(self): + """ + Returns a text summary of the current estimate of the + dependence structure. + """ + raise NotImplementedError + + +class Independence(CovStruct): + """ + An independence working dependence structure. + """ + + @Appender(CovStruct.update.__doc__) + def update(self, params): + # Nothing to update + return + + @Appender(CovStruct.covariance_matrix.__doc__) + def covariance_matrix(self, expval, index): + dim = len(expval) + return np.eye(dim, dtype=np.float64), True + + @Appender(CovStruct.covariance_matrix_solve.__doc__) + def covariance_matrix_solve(self, expval, index, stdev, rhs): + v = stdev ** 2 + rslt = [] + for x in rhs: + if x.ndim == 1: + rslt.append(x / v) + else: + rslt.append(x / v[:, None]) + return rslt + + def summary(self): + return ("Observations within a cluster are modeled " + "as being independent.") + +class Unstructured(CovStruct): + """ + An unstructured dependence structure. + + To use the unstructured dependence structure, a `time` + argument must be provided when creating the GEE. The + time argument must be of integer dtype, and indicates + which position in a complete data vector is occupied + by each observed value. + """ + + def __init__(self, cov_nearest_method="clipped"): + + super().__init__(cov_nearest_method) + + def initialize(self, model): + + self.model = model + + import numbers + if not issubclass(self.model.time.dtype.type, numbers.Integral): + msg = "time must be provided and must have integer dtype" + raise ValueError(msg) + + q = self.model.time[:, 0].max() + 1 + + self.dep_params = np.eye(q) + + @Appender(CovStruct.covariance_matrix.__doc__) + def covariance_matrix(self, endog_expval, index): + + if hasattr(self.model, "time"): + time_li = self.model.time_li + ix = time_li[index][:, 0] + return self.dep_params[np.ix_(ix, ix)],True + + return self.dep_params, True + + @Appender(CovStruct.update.__doc__) + def update(self, params): + + endog = self.model.endog_li + nobs = self.model.nobs + varfunc = self.model.family.variance + cached_means = self.model.cached_means + has_weights = self.model.weights is not None + weights_li = self.model.weights + + time_li = self.model.time_li + q = self.model.time.max() + 1 + csum = np.zeros((q, q)) + wsum = 0. + cov = np.zeros((q, q)) + + scale = 0. + for i in range(self.model.num_group): + + # Get the Pearson residuals + expval, _ = cached_means[i] + stdev = np.sqrt(varfunc(expval)) + resid = (endog[i] - expval) / stdev + + ix = time_li[i][:, 0] + m = np.outer(resid, resid) + ssr = np.sum(np.diag(m)) + + w = weights_li[i] if has_weights else 1. + csum[np.ix_(ix, ix)] += w + wsum += w * len(ix) + cov[np.ix_(ix, ix)] += w * m + scale += w * ssr + ddof = self.model.ddof_scale + scale /= wsum * (nobs - ddof) / float(nobs) + cov /= (csum - ddof) + + sd = np.sqrt(np.diag(cov)) + cov /= np.outer(sd, sd) + + self.dep_params = cov + + def summary(self): + print("Estimated covariance structure:") + print(self.dep_params) + + +class Exchangeable(CovStruct): + """ + An exchangeable working dependence structure. + """ + + def __init__(self): + + super().__init__() + + # The correlation between any two values in the same cluster + self.dep_params = 0. + + @Appender(CovStruct.update.__doc__) + def update(self, params): + + endog = self.model.endog_li + + nobs = self.model.nobs + + varfunc = self.model.family.variance + + cached_means = self.model.cached_means + + has_weights = self.model.weights is not None + weights_li = self.model.weights + + residsq_sum, scale = 0, 0 + fsum1, fsum2, n_pairs = 0., 0., 0. + for i in range(self.model.num_group): + expval, _ = cached_means[i] + stdev = np.sqrt(varfunc(expval)) + resid = (endog[i] - expval) / stdev + f = weights_li[i] if has_weights else 1. + + ssr = np.sum(resid * resid) + scale += f * ssr + fsum1 += f * len(endog[i]) + + residsq_sum += f * (resid.sum() ** 2 - ssr) / 2 + ngrp = len(resid) + npr = 0.5 * ngrp * (ngrp - 1) + fsum2 += f * npr + n_pairs += npr + + ddof = self.model.ddof_scale + scale /= (fsum1 * (nobs - ddof) / float(nobs)) + residsq_sum /= scale + self.dep_params = residsq_sum / \ + (fsum2 * (n_pairs - ddof) / float(n_pairs)) + + @Appender(CovStruct.covariance_matrix.__doc__) + def covariance_matrix(self, expval, index): + dim = len(expval) + dp = self.dep_params * np.ones((dim, dim), dtype=np.float64) + np.fill_diagonal(dp, 1) + return dp, True + + @Appender(CovStruct.covariance_matrix_solve.__doc__) + def covariance_matrix_solve(self, expval, index, stdev, rhs): + + k = len(expval) + c = self.dep_params / (1. - self.dep_params) + c /= 1. + self.dep_params * (k - 1) + + rslt = [] + for x in rhs: + if x.ndim == 1: + x1 = x / stdev + y = x1 / (1. - self.dep_params) + y -= c * sum(x1) + y /= stdev + else: + x1 = x / stdev[:, None] + y = x1 / (1. - self.dep_params) + y -= c * x1.sum(0) + y /= stdev[:, None] + rslt.append(y) + + return rslt + + def summary(self): + return ("The correlation between two observations in the " + + "same cluster is %.3f" % self.dep_params) + + +class Nested(CovStruct): + """ + A nested working dependence structure. + + A nested working dependence structure captures unique variance + associated with each level in a hierarchy of partitions of the + cases. For each level of the hierarchy, there is a set of iid + random effects with mean zero, and with variance that is specific + to the level. These variance parameters are estimated from the + data using the method of moments. + + The top level of the hierarchy is always defined by the required + `groups` argument to GEE. + + The `dep_data` argument used to create the GEE defines the + remaining levels of the hierarchy. it should be either an array, + or if using the formula interface, a string that contains a + formula. If an array, it should contain a `n_obs x k` matrix of + labels, corresponding to the k levels of partitioning that are + nested under the top-level `groups` of the GEE instance. These + subgroups should be nested from left to right, so that two + observations with the same label for column j of `dep_data` should + also have the same label for all columns j' < j (this only applies + to observations in the same top-level cluster given by the + `groups` argument to GEE). + + If `dep_data` is a formula, it should usually be of the form `0 + + a + b + ...`, where `a`, `b`, etc. contain labels defining group + membership. The `0 + ` should be included to prevent creation of + an intercept. The variable values are interpreted as labels for + group membership, but the variables should not be explicitly coded + as categorical, i.e. use `0 + a` not `0 + C(a)`. + + Notes + ----- + The calculations for the nested structure involve all pairs of + observations within the top level `group` passed to GEE. Large + group sizes will result in slow iterations. + """ + + def initialize(self, model): + """ + Called on the first call to update + + `ilabels` is a list of n_i x n_i matrices containing integer + labels that correspond to specific correlation parameters. + Two elements of ilabels[i] with the same label share identical + variance components. + + `designx` is a matrix, with each row containing dummy + variables indicating which variance components are associated + with the corresponding element of QY. + """ + + super().initialize(model) + + if self.model.weights is not None: + warnings.warn("weights not implemented for nested cov_struct, " + "using unweighted covariance estimate", + NotImplementedWarning) + + # A bit of processing of the nest data + id_matrix = np.asarray(self.model.dep_data) + if id_matrix.ndim == 1: + id_matrix = id_matrix[:, None] + self.id_matrix = id_matrix + + endog = self.model.endog_li + designx, ilabels = [], [] + + # The number of layers of nesting + n_nest = self.id_matrix.shape[1] + + for i in range(self.model.num_group): + ngrp = len(endog[i]) + glab = self.model.group_labels[i] + rix = self.model.group_indices[glab] + + # Determine the number of common variance components + # shared by each pair of observations. + ix1, ix2 = np.tril_indices(ngrp, -1) + ncm = (self.id_matrix[rix[ix1], :] == + self.id_matrix[rix[ix2], :]).sum(1) + + # This is used to construct the working correlation + # matrix. + ilabel = np.zeros((ngrp, ngrp), dtype=np.int32) + ilabel[(ix1, ix2)] = ncm + 1 + ilabel[(ix2, ix1)] = ncm + 1 + ilabels.append(ilabel) + + # This is used to estimate the variance components. + dsx = np.zeros((len(ix1), n_nest + 1), dtype=np.float64) + dsx[:, 0] = 1 + for k in np.unique(ncm): + ii = np.flatnonzero(ncm == k) + dsx[ii, 1:k + 1] = 1 + designx.append(dsx) + + self.designx = np.concatenate(designx, axis=0) + self.ilabels = ilabels + + svd = np.linalg.svd(self.designx, 0) + self.designx_u = svd[0] + self.designx_s = svd[1] + self.designx_v = svd[2].T + + @Appender(CovStruct.update.__doc__) + def update(self, params): + + endog = self.model.endog_li + + nobs = self.model.nobs + dim = len(params) + + if self.designx is None: + self._compute_design(self.model) + + cached_means = self.model.cached_means + + varfunc = self.model.family.variance + + dvmat = [] + scale = 0. + for i in range(self.model.num_group): + + expval, _ = cached_means[i] + + stdev = np.sqrt(varfunc(expval)) + resid = (endog[i] - expval) / stdev + + ix1, ix2 = np.tril_indices(len(resid), -1) + dvmat.append(resid[ix1] * resid[ix2]) + + scale += np.sum(resid ** 2) + + dvmat = np.concatenate(dvmat) + scale /= (nobs - dim) + + # Use least squares regression to estimate the variance + # components + vcomp_coeff = np.dot(self.designx_v, np.dot(self.designx_u.T, + dvmat) / self.designx_s) + + self.vcomp_coeff = np.clip(vcomp_coeff, 0, np.inf) + self.scale = scale + + self.dep_params = self.vcomp_coeff.copy() + + @Appender(CovStruct.covariance_matrix.__doc__) + def covariance_matrix(self, expval, index): + + dim = len(expval) + + # First iteration + if self.dep_params is None: + return np.eye(dim, dtype=np.float64), True + + ilabel = self.ilabels[index] + + c = np.r_[self.scale, np.cumsum(self.vcomp_coeff)] + vmat = c[ilabel] + vmat /= self.scale + return vmat, True + + def summary(self): + """ + Returns a summary string describing the state of the + dependence structure. + """ + + dep_names = ["Groups"] + if hasattr(self.model, "_dep_data_names"): + dep_names.extend(self.model._dep_data_names) + else: + dep_names.extend(["Component %d:" % (k + 1) for k in range(len(self.vcomp_coeff) - 1)]) + if hasattr(self.model, "_groups_name"): + dep_names[0] = self.model._groups_name + dep_names.append("Residual") + + vc = self.vcomp_coeff.tolist() + vc.append(self.scale - np.sum(vc)) + + smry = pd.DataFrame({"Variance": vc}, index=dep_names) + + return smry + + +class Stationary(CovStruct): + """ + A stationary covariance structure. + + The correlation between two observations is an arbitrary function + of the distance between them. Distances up to a given maximum + value are included in the covariance model. + + Parameters + ---------- + max_lag : float + The largest distance that is included in the covariance model. + grid : bool + If True, the index positions in the data (after dropping missing + values) are used to define distances, and the `time` variable is + ignored. + """ + + def __init__(self, max_lag=1, grid=None): + + super().__init__() + grid = bool_like(grid, "grid", optional=True) + if grid is None: + warnings.warn( + "grid=True will become default in a future version", + FutureWarning + ) + + self.max_lag = max_lag + self.grid = bool(grid) + self.dep_params = np.zeros(max_lag + 1) + + def initialize(self, model): + + super().initialize(model) + + # Time used as an index needs to be integer type. + if not self.grid: + time = self.model.time[:, 0].astype(np.int32) + self.time = self.model.cluster_list(time) + + @Appender(CovStruct.update.__doc__) + def update(self, params): + + if self.grid: + self.update_grid(params) + else: + self.update_nogrid(params) + + def update_grid(self, params): + + endog = self.model.endog_li + cached_means = self.model.cached_means + varfunc = self.model.family.variance + + dep_params = np.zeros(self.max_lag + 1) + for i in range(self.model.num_group): + + expval, _ = cached_means[i] + stdev = np.sqrt(varfunc(expval)) + resid = (endog[i] - expval) / stdev + + dep_params[0] += np.sum(resid * resid) / len(resid) + for j in range(1, self.max_lag + 1): + v = resid[j:] + dep_params[j] += np.sum(resid[0:-j] * v) / len(v) + + dep_params /= dep_params[0] + self.dep_params = dep_params + + def update_nogrid(self, params): + + endog = self.model.endog_li + cached_means = self.model.cached_means + varfunc = self.model.family.variance + + dep_params = np.zeros(self.max_lag + 1) + dn = np.zeros(self.max_lag + 1) + resid_ssq = 0 + resid_ssq_n = 0 + for i in range(self.model.num_group): + + expval, _ = cached_means[i] + stdev = np.sqrt(varfunc(expval)) + resid = (endog[i] - expval) / stdev + + j1, j2 = np.tril_indices(len(expval), -1) + dx = np.abs(self.time[i][j1] - self.time[i][j2]) + ii = np.flatnonzero(dx <= self.max_lag) + j1 = j1[ii] + j2 = j2[ii] + dx = dx[ii] + + vs = np.bincount(dx, weights=resid[j1] * resid[j2], + minlength=self.max_lag + 1) + vd = np.bincount(dx, minlength=self.max_lag + 1) + + resid_ssq += np.sum(resid**2) + resid_ssq_n += len(resid) + + ii = np.flatnonzero(vd > 0) + if len(ii) > 0: + dn[ii] += 1 + dep_params[ii] += vs[ii] / vd[ii] + + i0 = np.flatnonzero(dn > 0) + dep_params[i0] /= dn[i0] + resid_msq = resid_ssq / resid_ssq_n + dep_params /= resid_msq + self.dep_params = dep_params + + @Appender(CovStruct.covariance_matrix.__doc__) + def covariance_matrix(self, endog_expval, index): + + if self.grid: + return self.covariance_matrix_grid(endog_expval, index) + + j1, j2 = np.tril_indices(len(endog_expval), -1) + dx = np.abs(self.time[index][j1] - self.time[index][j2]) + ii = np.flatnonzero(dx <= self.max_lag) + j1 = j1[ii] + j2 = j2[ii] + dx = dx[ii] + + cmat = np.eye(len(endog_expval)) + cmat[j1, j2] = self.dep_params[dx] + cmat[j2, j1] = self.dep_params[dx] + + return cmat, True + + def covariance_matrix_grid(self, endog_expval, index): + + from scipy.linalg import toeplitz + r = np.zeros(len(endog_expval)) + r[0] = 1 + r[1:self.max_lag + 1] = self.dep_params[1:] + return toeplitz(r), True + + @Appender(CovStruct.covariance_matrix_solve.__doc__) + def covariance_matrix_solve(self, expval, index, stdev, rhs): + + if not self.grid: + return super().covariance_matrix_solve( + expval, index, stdev, rhs) + + from statsmodels.tools.linalg import stationary_solve + r = np.zeros(len(expval)) + r[0:self.max_lag] = self.dep_params[1:] + + rslt = [] + for x in rhs: + if x.ndim == 1: + y = x / stdev + rslt.append(stationary_solve(r, y) / stdev) + else: + y = x / stdev[:, None] + rslt.append(stationary_solve(r, y) / stdev[:, None]) + + return rslt + + def summary(self): + + lag = np.arange(self.max_lag + 1) + return pd.DataFrame({"Lag": lag, "Cov": self.dep_params}) + + +class Autoregressive(CovStruct): + """ + A first-order autoregressive working dependence structure. + + The dependence is defined in terms of the `time` component of the + parent GEE class, which defaults to the index position of each + value within its cluster, based on the order of values in the + input data set. Time represents a potentially multidimensional + index from which distances between pairs of observations can be + determined. + + The correlation between two observations in the same cluster is + dep_params^distance, where `dep_params` contains the (scalar) + autocorrelation parameter to be estimated, and `distance` is the + distance between the two observations, calculated from their + corresponding time values. `time` is stored as an n_obs x k + matrix, where `k` represents the number of dimensions in the time + index. + + The autocorrelation parameter is estimated using weighted + nonlinear least squares, regressing each value within a cluster on + each preceding value in the same cluster. + + Parameters + ---------- + dist_func : function from R^k x R^k to R^+, optional + A function that computes the distance between the two + observations based on their `time` values. + + References + ---------- + B Rosner, A Munoz. Autoregressive modeling for the analysis of + longitudinal data with unequally spaced examinations. Statistics + in medicine. Vol 7, 59-71, 1988. + """ + + def __init__(self, dist_func=None, grid=None): + + super().__init__() + grid = bool_like(grid, "grid", optional=True) + # The function for determining distances based on time + if dist_func is None: + self.dist_func = lambda x, y: np.abs(x - y).sum() + else: + self.dist_func = dist_func + + if grid is None: + warnings.warn( + "grid=True will become default in a future version", + FutureWarning + ) + self.grid = bool(grid) + if not self.grid: + self.designx = None + + # The autocorrelation parameter + self.dep_params = 0. + + @Appender(CovStruct.update.__doc__) + def update(self, params): + + if self.model.weights is not None: + warnings.warn("weights not implemented for autoregressive " + "cov_struct, using unweighted covariance estimate", + NotImplementedWarning) + + if self.grid: + self._update_grid(params) + else: + self._update_nogrid(params) + + def _update_grid(self, params): + + cached_means = self.model.cached_means + scale = self.model.estimate_scale() + varfunc = self.model.family.variance + endog = self.model.endog_li + + lag0, lag1 = 0.0, 0.0 + for i in range(self.model.num_group): + + expval, _ = cached_means[i] + stdev = np.sqrt(scale * varfunc(expval)) + resid = (endog[i] - expval) / stdev + + n = len(resid) + if n > 1: + lag1 += np.sum(resid[0:-1] * resid[1:]) / (n - 1) + lag0 += np.sum(resid**2) / n + + self.dep_params = lag1 / lag0 + + def _update_nogrid(self, params): + + endog = self.model.endog_li + time = self.model.time_li + + # Only need to compute this once + if self.designx is not None: + designx = self.designx + else: + designx = [] + for i in range(self.model.num_group): + + ngrp = len(endog[i]) + if ngrp == 0: + continue + + # Loop over pairs of observations within a cluster + for j1 in range(ngrp): + for j2 in range(j1): + designx.append(self.dist_func(time[i][j1, :], + time[i][j2, :])) + + designx = np.array(designx) + self.designx = designx + + scale = self.model.estimate_scale() + varfunc = self.model.family.variance + cached_means = self.model.cached_means + + # Weights + var = 1. - self.dep_params ** (2 * designx) + var /= 1. - self.dep_params ** 2 + wts = 1. / var + wts /= wts.sum() + + residmat = [] + for i in range(self.model.num_group): + + expval, _ = cached_means[i] + stdev = np.sqrt(scale * varfunc(expval)) + resid = (endog[i] - expval) / stdev + + ngrp = len(resid) + for j1 in range(ngrp): + for j2 in range(j1): + residmat.append([resid[j1], resid[j2]]) + + residmat = np.array(residmat) + + # Need to minimize this + def fitfunc(a): + dif = residmat[:, 0] - (a ** designx) * residmat[:, 1] + return np.dot(dif ** 2, wts) + + # Left bracket point + b_lft, f_lft = 0., fitfunc(0.) + + # Center bracket point + b_ctr, f_ctr = 0.5, fitfunc(0.5) + while f_ctr > f_lft: + b_ctr /= 2 + f_ctr = fitfunc(b_ctr) + if b_ctr < 1e-8: + self.dep_params = 0 + return + + # Right bracket point + b_rgt, f_rgt = 0.75, fitfunc(0.75) + while f_rgt < f_ctr: + b_rgt = b_rgt + (1. - b_rgt) / 2 + f_rgt = fitfunc(b_rgt) + if b_rgt > 1. - 1e-6: + raise ValueError( + "Autoregressive: unable to find right bracket") + + from scipy.optimize import brent + self.dep_params = brent(fitfunc, brack=[b_lft, b_ctr, b_rgt]) + + @Appender(CovStruct.covariance_matrix.__doc__) + def covariance_matrix(self, endog_expval, index): + ngrp = len(endog_expval) + if self.dep_params == 0: + return np.eye(ngrp, dtype=np.float64), True + idx = np.arange(ngrp) + cmat = self.dep_params ** np.abs(idx[:, None] - idx[None, :]) + return cmat, True + + @Appender(CovStruct.covariance_matrix_solve.__doc__) + def covariance_matrix_solve(self, expval, index, stdev, rhs): + # The inverse of an AR(1) covariance matrix is tri-diagonal. + + k = len(expval) + r = self.dep_params + soln = [] + + # RHS has 1 row + if k == 1: + return [x / stdev ** 2 for x in rhs] + + # RHS has 2 rows + if k == 2: + mat = np.array([[1, -r], [-r, 1]]) + mat /= (1. - r ** 2) + for x in rhs: + if x.ndim == 1: + x1 = x / stdev + else: + x1 = x / stdev[:, None] + x1 = np.dot(mat, x1) + if x.ndim == 1: + x1 /= stdev + else: + x1 /= stdev[:, None] + soln.append(x1) + return soln + + # RHS has >= 3 rows: values c0, c1, c2 defined below give + # the inverse. c0 is on the diagonal, except for the first + # and last position. c1 is on the first and last position of + # the diagonal. c2 is on the sub/super diagonal. + c0 = (1. + r ** 2) / (1. - r ** 2) + c1 = 1. / (1. - r ** 2) + c2 = -r / (1. - r ** 2) + soln = [] + for x in rhs: + flatten = False + if x.ndim == 1: + x = x[:, None] + flatten = True + x1 = x / stdev[:, None] + + z0 = np.zeros((1, x1.shape[1])) + rhs1 = np.concatenate((x1[1:, :], z0), axis=0) + rhs2 = np.concatenate((z0, x1[0:-1, :]), axis=0) + + y = c0 * x1 + c2 * rhs1 + c2 * rhs2 + y[0, :] = c1 * x1[0, :] + c2 * x1[1, :] + y[-1, :] = c1 * x1[-1, :] + c2 * x1[-2, :] + + y /= stdev[:, None] + + if flatten: + y = np.squeeze(y) + + soln.append(y) + + return soln + + def summary(self): + + return ("Autoregressive(1) dependence parameter: %.3f\n" % + self.dep_params) + + +class CategoricalCovStruct(CovStruct): + """ + Parent class for covariance structure for categorical data models. + + Attributes + ---------- + nlevel : int + The number of distinct levels for the outcome variable. + ibd : list + A list whose i^th element ibd[i] is an array whose rows + contain integer pairs (a,b), where endog_li[i][a:b] is the + subvector of binary indicators derived from the same ordinal + value. + """ + + def initialize(self, model): + + super().initialize(model) + + self.nlevel = len(model.endog_values) + self._ncut = self.nlevel - 1 + + from numpy.lib.stride_tricks import as_strided + b = np.dtype(np.int64).itemsize + + ibd = [] + for v in model.endog_li: + jj = np.arange(0, len(v) + 1, self._ncut, dtype=np.int64) + jj = as_strided(jj, shape=(len(jj) - 1, 2), strides=(b, b)) + ibd.append(jj) + + self.ibd = ibd + + +class GlobalOddsRatio(CategoricalCovStruct): + """ + Estimate the global odds ratio for a GEE with ordinal or nominal + data. + + References + ---------- + PJ Heagerty and S Zeger. "Marginal Regression Models for Clustered + Ordinal Measurements". Journal of the American Statistical + Association Vol. 91, Issue 435 (1996). + + Thomas Lumley. Generalized Estimating Equations for Ordinal Data: + A Note on Working Correlation Structures. Biometrics Vol. 52, + No. 1 (Mar., 1996), pp. 354-361 + http://www.jstor.org/stable/2533173 + + Notes + ----- + The following data structures are calculated in the class: + + 'ibd' is a list whose i^th element ibd[i] is a sequence of integer + pairs (a,b), where endog_li[i][a:b] is the subvector of binary + indicators derived from the same ordinal value. + + `cpp` is a dictionary where cpp[group] is a map from cut-point + pairs (c,c') to the indices of all between-subject pairs derived + from the given cut points. + """ + + def __init__(self, endog_type): + super().__init__() + self.endog_type = endog_type + self.dep_params = 0. + + def initialize(self, model): + + super().initialize(model) + + if self.model.weights is not None: + warnings.warn("weights not implemented for GlobalOddsRatio " + "cov_struct, using unweighted covariance estimate", + NotImplementedWarning) + + # Need to restrict to between-subject pairs + cpp = [] + for v in model.endog_li: + + # Number of subjects in this group + m = int(len(v) / self._ncut) + i1, i2 = np.tril_indices(m, -1) + + cpp1 = {} + for k1 in range(self._ncut): + for k2 in range(k1 + 1): + jj = np.zeros((len(i1), 2), dtype=np.int64) + jj[:, 0] = i1 * self._ncut + k1 + jj[:, 1] = i2 * self._ncut + k2 + cpp1[(k2, k1)] = jj + + cpp.append(cpp1) + + self.cpp = cpp + + # Initialize the dependence parameters + self.crude_or = self.observed_crude_oddsratio() + if self.model.update_dep: + self.dep_params = self.crude_or + + def pooled_odds_ratio(self, tables): + """ + Returns the pooled odds ratio for a list of 2x2 tables. + + The pooled odds ratio is the inverse variance weighted average + of the sample odds ratios of the tables. + """ + + if len(tables) == 0: + return 1. + + # Get the sampled odds ratios and variances + log_oddsratio, var = [], [] + for table in tables: + lor = np.log(table[1, 1]) + np.log(table[0, 0]) -\ + np.log(table[0, 1]) - np.log(table[1, 0]) + log_oddsratio.append(lor) + var.append((1 / table.astype(np.float64)).sum()) + + # Calculate the inverse variance weighted average + wts = [1 / v for v in var] + wtsum = sum(wts) + wts = [w / wtsum for w in wts] + log_pooled_or = sum([w * e for w, e in zip(wts, log_oddsratio)]) + + return np.exp(log_pooled_or) + + @Appender(CovStruct.covariance_matrix.__doc__) + def covariance_matrix(self, expected_value, index): + + vmat = self.get_eyy(expected_value, index) + vmat -= np.outer(expected_value, expected_value) + return vmat, False + + def observed_crude_oddsratio(self): + """ + To obtain the crude (global) odds ratio, first pool all binary + indicators corresponding to a given pair of cut points (c,c'), + then calculate the odds ratio for this 2x2 table. The crude + odds ratio is the inverse variance weighted average of these + odds ratios. Since the covariate effects are ignored, this OR + will generally be greater than the stratified OR. + """ + + cpp = self.cpp + endog = self.model.endog_li + + # Storage for the contingency tables for each (c,c') + tables = {} + for ii in cpp[0].keys(): + tables[ii] = np.zeros((2, 2), dtype=np.float64) + + # Get the observed crude OR + for i in range(len(endog)): + + # The observed joint values for the current cluster + yvec = endog[i] + endog_11 = np.outer(yvec, yvec) + endog_10 = np.outer(yvec, 1. - yvec) + endog_01 = np.outer(1. - yvec, yvec) + endog_00 = np.outer(1. - yvec, 1. - yvec) + + cpp1 = cpp[i] + for ky in cpp1.keys(): + ix = cpp1[ky] + tables[ky][1, 1] += endog_11[ix[:, 0], ix[:, 1]].sum() + tables[ky][1, 0] += endog_10[ix[:, 0], ix[:, 1]].sum() + tables[ky][0, 1] += endog_01[ix[:, 0], ix[:, 1]].sum() + tables[ky][0, 0] += endog_00[ix[:, 0], ix[:, 1]].sum() + + return self.pooled_odds_ratio(list(tables.values())) + + def get_eyy(self, endog_expval, index): + """ + Returns a matrix V such that V[i,j] is the joint probability + that endog[i] = 1 and endog[j] = 1, based on the marginal + probabilities of endog and the global odds ratio `current_or`. + """ + + current_or = self.dep_params + ibd = self.ibd[index] + + # The between-observation joint probabilities + if current_or == 1.0: + vmat = np.outer(endog_expval, endog_expval) + else: + psum = endog_expval[:, None] + endog_expval[None, :] + pprod = endog_expval[:, None] * endog_expval[None, :] + pfac = np.sqrt((1. + psum * (current_or - 1.)) ** 2 + + 4 * current_or * (1. - current_or) * pprod) + vmat = 1. + psum * (current_or - 1.) - pfac + vmat /= 2. * (current_or - 1) + + # Fix E[YY'] for elements that belong to same observation + for bdl in ibd: + evy = endog_expval[bdl[0]:bdl[1]] + if self.endog_type == "ordinal": + vmat[bdl[0]:bdl[1], bdl[0]:bdl[1]] =\ + np.minimum.outer(evy, evy) + else: + vmat[bdl[0]:bdl[1], bdl[0]:bdl[1]] = np.diag(evy) + + return vmat + + @Appender(CovStruct.update.__doc__) + def update(self, params): + """ + Update the global odds ratio based on the current value of + params. + """ + + cpp = self.cpp + cached_means = self.model.cached_means + + # This will happen if all the clusters have only + # one observation + if len(cpp[0]) == 0: + return + + tables = {} + for ii in cpp[0]: + tables[ii] = np.zeros((2, 2), dtype=np.float64) + + for i in range(self.model.num_group): + + endog_expval, _ = cached_means[i] + + emat_11 = self.get_eyy(endog_expval, i) + emat_10 = endog_expval[:, None] - emat_11 + emat_01 = -emat_11 + endog_expval + emat_00 = 1. - (emat_11 + emat_10 + emat_01) + + cpp1 = cpp[i] + for ky in cpp1.keys(): + ix = cpp1[ky] + tables[ky][1, 1] += emat_11[ix[:, 0], ix[:, 1]].sum() + tables[ky][1, 0] += emat_10[ix[:, 0], ix[:, 1]].sum() + tables[ky][0, 1] += emat_01[ix[:, 0], ix[:, 1]].sum() + tables[ky][0, 0] += emat_00[ix[:, 0], ix[:, 1]].sum() + + cor_expval = self.pooled_odds_ratio(list(tables.values())) + + self.dep_params *= self.crude_or / cor_expval + if not np.isfinite(self.dep_params): + self.dep_params = 1. + warnings.warn("dep_params became inf, resetting to 1", + ConvergenceWarning) + + def summary(self): + return "Global odds ratio: %.3f\n" % self.dep_params + + +class OrdinalIndependence(CategoricalCovStruct): + """ + An independence covariance structure for ordinal models. + + The working covariance between indicators derived from different + observations is zero. The working covariance between indicators + derived form a common observation is determined from their current + mean values. + + There are no parameters to estimate in this covariance structure. + """ + + def covariance_matrix(self, expected_value, index): + + ibd = self.ibd[index] + n = len(expected_value) + vmat = np.zeros((n, n)) + + for bdl in ibd: + ev = expected_value[bdl[0]:bdl[1]] + vmat[bdl[0]:bdl[1], bdl[0]:bdl[1]] =\ + np.minimum.outer(ev, ev) - np.outer(ev, ev) + + return vmat, False + + # Nothing to update + def update(self, params): + pass + + +class NominalIndependence(CategoricalCovStruct): + """ + An independence covariance structure for nominal models. + + The working covariance between indicators derived from different + observations is zero. The working covariance between indicators + derived form a common observation is determined from their current + mean values. + + There are no parameters to estimate in this covariance structure. + """ + + def covariance_matrix(self, expected_value, index): + + ibd = self.ibd[index] + n = len(expected_value) + vmat = np.zeros((n, n)) + + for bdl in ibd: + ev = expected_value[bdl[0]:bdl[1]] + vmat[bdl[0]:bdl[1], bdl[0]:bdl[1]] =\ + np.diag(ev) - np.outer(ev, ev) + + return vmat, False + + # Nothing to update + def update(self, params): + pass + + +class Equivalence(CovStruct): + """ + A covariance structure defined in terms of equivalence classes. + + An 'equivalence class' is a set of pairs of observations such that + the covariance of every pair within the equivalence class has a + common value. + + Parameters + ---------- + pairs : dict-like + A dictionary of dictionaries, where `pairs[group][label]` + provides the indices of all pairs of observations in the group + that have the same covariance value. Specifically, + `pairs[group][label]` is a tuple `(j1, j2)`, where `j1` and `j2` + are integer arrays of the same length. `j1[i], j2[i]` is one + index pair that belongs to the `label` equivalence class. Only + one triangle of each covariance matrix should be included. + Positions where j1 and j2 have the same value are variance + parameters. + labels : array_like + An array of labels such that every distinct pair of labels + defines an equivalence class. Either `labels` or `pairs` must + be provided. When the two labels in a pair are equal two + equivalence classes are defined: one for the diagonal elements + (corresponding to variances) and one for the off-diagonal + elements (corresponding to covariances). + return_cov : bool + If True, `covariance_matrix` returns an estimate of the + covariance matrix, otherwise returns an estimate of the + correlation matrix. + + Notes + ----- + Using `labels` to define the class is much easier than using + `pairs`, but is less general. + + Any pair of values not contained in `pairs` will be assigned zero + covariance. + + The index values in `pairs` are row indices into the `exog` + matrix. They are not updated if missing data are present. When + using this covariance structure, missing data should be removed + before constructing the model. + + If using `labels`, after a model is defined using the covariance + structure it is possible to remove a label pair from the second + level of the `pairs` dictionary to force the corresponding + covariance to be zero. + + Examples + -------- + The following sets up the `pairs` dictionary for a model with two + groups, equal variance for all observations, and constant + covariance for all pairs of observations within each group. + + >> pairs = {0: {}, 1: {}} + >> pairs[0][0] = (np.r_[0, 1, 2], np.r_[0, 1, 2]) + >> pairs[0][1] = np.tril_indices(3, -1) + >> pairs[1][0] = (np.r_[3, 4, 5], np.r_[3, 4, 5]) + >> pairs[1][2] = 3 + np.tril_indices(3, -1) + """ + + def __init__(self, pairs=None, labels=None, return_cov=False): + + super().__init__() + + if (pairs is None) and (labels is None): + raise ValueError( + "Equivalence cov_struct requires either `pairs` or `labels`") + + if (pairs is not None) and (labels is not None): + raise ValueError( + "Equivalence cov_struct accepts only one of `pairs` " + "and `labels`") + + if pairs is not None: + import copy + self.pairs = copy.deepcopy(pairs) + + if labels is not None: + self.labels = np.asarray(labels) + + self.return_cov = return_cov + + def _make_pairs(self, i, j): + """ + Create arrays containing all unique ordered pairs of i, j. + + The arrays i and j must be one-dimensional containing non-negative + integers. + """ + + mat = np.zeros((len(i) * len(j), 2), dtype=np.int32) + + # Create the pairs and order them + f = np.ones(len(j)) + mat[:, 0] = np.kron(f, i).astype(np.int32) + f = np.ones(len(i)) + mat[:, 1] = np.kron(j, f).astype(np.int32) + mat.sort(1) + + # Remove repeated rows + try: + dtype = np.dtype((np.void, mat.dtype.itemsize * mat.shape[1])) + bmat = np.ascontiguousarray(mat).view(dtype) + _, idx = np.unique(bmat, return_index=True) + except TypeError: + # workaround for old numpy that cannot call unique with complex + # dtypes + rs = np.random.RandomState(4234) + bmat = np.dot(mat, rs.uniform(size=mat.shape[1])) + _, idx = np.unique(bmat, return_index=True) + mat = mat[idx, :] + + return mat[:, 0], mat[:, 1] + + def _pairs_from_labels(self): + + from collections import defaultdict + pairs = defaultdict(lambda: defaultdict(lambda: None)) + + model = self.model + + df = pd.DataFrame({"labels": self.labels, "groups": model.groups}) + gb = df.groupby(["groups", "labels"]) + + ulabels = np.unique(self.labels) + + for g_ix, g_lb in enumerate(model.group_labels): + + # Loop over label pairs + for lx1 in range(len(ulabels)): + for lx2 in range(lx1 + 1): + + lb1 = ulabels[lx1] + lb2 = ulabels[lx2] + + try: + i1 = gb.groups[(g_lb, lb1)] + i2 = gb.groups[(g_lb, lb2)] + except KeyError: + continue + + i1, i2 = self._make_pairs(i1, i2) + + clabel = str(lb1) + "/" + str(lb2) + + # Variance parameters belong in their own equiv class. + jj = np.flatnonzero(i1 == i2) + if len(jj) > 0: + clabelv = clabel + "/v" + pairs[g_lb][clabelv] = (i1[jj], i2[jj]) + + # Covariance parameters + jj = np.flatnonzero(i1 != i2) + if len(jj) > 0: + i1 = i1[jj] + i2 = i2[jj] + pairs[g_lb][clabel] = (i1, i2) + + self.pairs = pairs + + def initialize(self, model): + + super().initialize(model) + + if self.model.weights is not None: + warnings.warn("weights not implemented for equalence cov_struct, " + "using unweighted covariance estimate", + NotImplementedWarning) + + if not hasattr(self, 'pairs'): + self._pairs_from_labels() + + # Initialize so that any equivalence class containing a + # variance parameter has value 1. + self.dep_params = defaultdict(float) + self._var_classes = set() + for gp in self.model.group_labels: + for lb in self.pairs[gp]: + j1, j2 = self.pairs[gp][lb] + if np.any(j1 == j2): + if not np.all(j1 == j2): + warnings.warn( + "equivalence class contains both variance " + "and covariance parameters", OutputWarning) + self._var_classes.add(lb) + self.dep_params[lb] = 1 + + # Need to start indexing at 0 within each group. + # rx maps olds indices to new indices + rx = -1 * np.ones(len(self.model.endog), dtype=np.int32) + for g_ix, g_lb in enumerate(self.model.group_labels): + ii = self.model.group_indices[g_lb] + rx[ii] = np.arange(len(ii), dtype=np.int32) + + # Reindex + for gp in self.model.group_labels: + for lb in self.pairs[gp].keys(): + a, b = self.pairs[gp][lb] + self.pairs[gp][lb] = (rx[a], rx[b]) + + @Appender(CovStruct.update.__doc__) + def update(self, params): + + endog = self.model.endog_li + varfunc = self.model.family.variance + cached_means = self.model.cached_means + dep_params = defaultdict(lambda: [0., 0., 0.]) + n_pairs = defaultdict(int) + dim = len(params) + + for k, gp in enumerate(self.model.group_labels): + expval, _ = cached_means[k] + stdev = np.sqrt(varfunc(expval)) + resid = (endog[k] - expval) / stdev + for lb in self.pairs[gp].keys(): + if (not self.return_cov) and lb in self._var_classes: + continue + jj = self.pairs[gp][lb] + dep_params[lb][0] += np.sum(resid[jj[0]] * resid[jj[1]]) + if not self.return_cov: + dep_params[lb][1] += np.sum(resid[jj[0]] ** 2) + dep_params[lb][2] += np.sum(resid[jj[1]] ** 2) + n_pairs[lb] += len(jj[0]) + + if self.return_cov: + for lb in dep_params.keys(): + dep_params[lb] = dep_params[lb][0] / (n_pairs[lb] - dim) + else: + for lb in dep_params.keys(): + den = np.sqrt(dep_params[lb][1] * dep_params[lb][2]) + dep_params[lb] = dep_params[lb][0] / den + for lb in self._var_classes: + dep_params[lb] = 1. + + self.dep_params = dep_params + self.n_pairs = n_pairs + + @Appender(CovStruct.covariance_matrix.__doc__) + def covariance_matrix(self, expval, index): + dim = len(expval) + cmat = np.zeros((dim, dim)) + g_lb = self.model.group_labels[index] + + for lb in self.pairs[g_lb].keys(): + j1, j2 = self.pairs[g_lb][lb] + cmat[j1, j2] = self.dep_params[lb] + + cmat = cmat + cmat.T + np.fill_diagonal(cmat, cmat.diagonal() / 2) + + return cmat, not self.return_cov diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/genmod/generalized_estimating_equations.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/genmod/generalized_estimating_equations.py new file mode 100644 index 0000000000000000000000000000000000000000..bd78b4d557215e0a82e65b292af410c411ac2055 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/genmod/generalized_estimating_equations.py @@ -0,0 +1,3223 @@ +""" +Procedures for fitting marginal regression models to dependent data +using Generalized Estimating Equations. + +References +---------- +KY Liang and S Zeger. "Longitudinal data analysis using +generalized linear models". Biometrika (1986) 73 (1): 13-22. + +S Zeger and KY Liang. "Longitudinal Data Analysis for Discrete and +Continuous Outcomes". Biometrics Vol. 42, No. 1 (Mar., 1986), +pp. 121-130 + +A Rotnitzky and NP Jewell (1990). "Hypothesis testing of regression +parameters in semiparametric generalized linear models for cluster +correlated data", Biometrika, 77, 485-497. + +Xu Guo and Wei Pan (2002). "Small sample performance of the score +test in GEE". +http://www.sph.umn.edu/faculty1/wp-content/uploads/2012/11/rr2002-013.pdf + +LA Mancl LA, TA DeRouen (2001). A covariance estimator for GEE with +improved small-sample properties. Biometrics. 2001 Mar;57(1):126-34. +""" +from statsmodels.compat.python import lzip +from statsmodels.compat.pandas import Appender + +import numpy as np +from scipy import stats +import pandas as pd +import patsy +from collections import defaultdict +from statsmodels.tools.decorators import cache_readonly +import statsmodels.base.model as base +# used for wrapper: +import statsmodels.regression.linear_model as lm +import statsmodels.base.wrapper as wrap + +from statsmodels.genmod import families +from statsmodels.genmod.generalized_linear_model import GLM, GLMResults +from statsmodels.genmod import cov_struct as cov_structs + +import statsmodels.genmod.families.varfuncs as varfuncs +from statsmodels.genmod.families.links import Link + +from statsmodels.tools.sm_exceptions import (ConvergenceWarning, + DomainWarning, + IterationLimitWarning, + ValueWarning) +import warnings + +from statsmodels.graphics._regressionplots_doc import ( + _plot_added_variable_doc, + _plot_partial_residuals_doc, + _plot_ceres_residuals_doc) +from statsmodels.discrete.discrete_margins import ( + _get_margeff_exog, _check_margeff_args, _effects_at, margeff_cov_with_se, + _check_at_is_all, _transform_names, _check_discrete_args, + _get_dummy_index, _get_count_index) + + +class ParameterConstraint: + """ + A class for managing linear equality constraints for a parameter + vector. + """ + + def __init__(self, lhs, rhs, exog): + """ + Parameters + ---------- + lhs : ndarray + A q x p matrix which is the left hand side of the + constraint lhs * param = rhs. The number of constraints is + q >= 1 and p is the dimension of the parameter vector. + rhs : ndarray + A 1-dimensional vector of length q which is the right hand + side of the constraint equation. + exog : ndarray + The n x p exognenous data for the full model. + """ + + # In case a row or column vector is passed (patsy linear + # constraints passes a column vector). + rhs = np.atleast_1d(rhs.squeeze()) + + if rhs.ndim > 1: + raise ValueError("The right hand side of the constraint " + "must be a vector.") + + if len(rhs) != lhs.shape[0]: + raise ValueError("The number of rows of the left hand " + "side constraint matrix L must equal " + "the length of the right hand side " + "constraint vector R.") + + self.lhs = lhs + self.rhs = rhs + + # The columns of lhs0 are an orthogonal basis for the + # orthogonal complement to row(lhs), the columns of lhs1 are + # an orthogonal basis for row(lhs). The columns of lhsf = + # [lhs0, lhs1] are mutually orthogonal. + lhs_u, lhs_s, lhs_vt = np.linalg.svd(lhs.T, full_matrices=1) + self.lhs0 = lhs_u[:, len(lhs_s):] + self.lhs1 = lhs_u[:, 0:len(lhs_s)] + self.lhsf = np.hstack((self.lhs0, self.lhs1)) + + # param0 is one solution to the underdetermined system + # L * param = R. + self.param0 = np.dot(self.lhs1, np.dot(lhs_vt, self.rhs) / + lhs_s) + + self._offset_increment = np.dot(exog, self.param0) + + self.orig_exog = exog + self.exog_fulltrans = np.dot(exog, self.lhsf) + + def offset_increment(self): + """ + Returns a vector that should be added to the offset vector to + accommodate the constraint. + + Parameters + ---------- + exog : array_like + The exogeneous data for the model. + """ + + return self._offset_increment + + def reduced_exog(self): + """ + Returns a linearly transformed exog matrix whose columns span + the constrained model space. + + Parameters + ---------- + exog : array_like + The exogeneous data for the model. + """ + return self.exog_fulltrans[:, 0:self.lhs0.shape[1]] + + def restore_exog(self): + """ + Returns the full exog matrix before it was reduced to + satisfy the constraint. + """ + return self.orig_exog + + def unpack_param(self, params): + """ + Converts the parameter vector `params` from reduced to full + coordinates. + """ + + return self.param0 + np.dot(self.lhs0, params) + + def unpack_cov(self, bcov): + """ + Converts the covariance matrix `bcov` from reduced to full + coordinates. + """ + + return np.dot(self.lhs0, np.dot(bcov, self.lhs0.T)) + + +_gee_init_doc = """ + Marginal regression model fit using Generalized Estimating Equations. + + GEE can be used to fit Generalized Linear Models (GLMs) when the + data have a grouped structure, and the observations are possibly + correlated within groups but not between groups. + + Parameters + ---------- + endog : array_like + 1d array of endogenous values (i.e. responses, outcomes, + dependent variables, or 'Y' values). + exog : array_like + 2d array of exogeneous values (i.e. covariates, predictors, + independent variables, regressors, or 'X' values). A `nobs x + k` array where `nobs` is the number of observations and `k` is + the number of regressors. An intercept is not included by + default and should be added by the user. See + `statsmodels.tools.add_constant`. + groups : array_like + A 1d array of length `nobs` containing the group labels. + time : array_like + A 2d array of time (or other index) values, used by some + dependence structures to define similarity relationships among + observations within a cluster. + family : family class instance +%(family_doc)s + cov_struct : CovStruct class instance + The default is Independence. To specify an exchangeable + structure use cov_struct = Exchangeable(). See + statsmodels.genmod.cov_struct.CovStruct for more + information. + offset : array_like + An offset to be included in the fit. If provided, must be + an array whose length is the number of rows in exog. + dep_data : array_like + Additional data passed to the dependence structure. + constraint : (ndarray, ndarray) + If provided, the constraint is a tuple (L, R) such that the + model parameters are estimated under the constraint L * + param = R, where L is a q x p matrix and R is a + q-dimensional vector. If constraint is provided, a score + test is performed to compare the constrained model to the + unconstrained model. + update_dep : bool + If true, the dependence parameters are optimized, otherwise + they are held fixed at their starting values. + weights : array_like + An array of case weights to use in the analysis. + %(extra_params)s + + See Also + -------- + statsmodels.genmod.families.family + :ref:`families` + :ref:`links` + + Notes + ----- + Only the following combinations make sense for family and link :: + + + ident log logit probit cloglog pow opow nbinom loglog logc + Gaussian | x x x + inv Gaussian | x x x + binomial | x x x x x x x x x + Poisson | x x x + neg binomial | x x x x + gamma | x x x + + Not all of these link functions are currently available. + + Endog and exog are references so that if the data they refer + to are already arrays and these arrays are changed, endog and + exog will change. + + The "robust" covariance type is the standard "sandwich estimator" + (e.g. Liang and Zeger (1986)). It is the default here and in most + other packages. The "naive" estimator gives smaller standard + errors, but is only correct if the working correlation structure + is correctly specified. The "bias reduced" estimator of Mancl and + DeRouen (Biometrics, 2001) reduces the downward bias of the robust + estimator. + + The robust covariance provided here follows Liang and Zeger (1986) + and agrees with R's gee implementation. To obtain the robust + standard errors reported in Stata, multiply by sqrt(N / (N - g)), + where N is the total sample size, and g is the average group size. + %(notes)s + Examples + -------- + %(example)s +""" + +_gee_nointercept = """ + The nominal and ordinal GEE models should not have an intercept + (either implicit or explicit). Use "0 + " in a formula to + suppress the intercept. +""" + +_gee_family_doc = """\ + The default is Gaussian. To specify the binomial + distribution use `family=sm.families.Binomial()`. Each family + can take a link instance as an argument. See + statsmodels.genmod.families.family for more information.""" + +_gee_ordinal_family_doc = """\ + The only family supported is `Binomial`. The default `Logit` + link may be replaced with `probit` if desired.""" + +_gee_nominal_family_doc = """\ + The default value `None` uses a multinomial logit family + specifically designed for use with GEE. Setting this + argument to a non-default value is not currently supported.""" + +_gee_fit_doc = """ + Fits a marginal regression model using generalized estimating + equations (GEE). + + Parameters + ---------- + maxiter : int + The maximum number of iterations + ctol : float + The convergence criterion for stopping the Gauss-Seidel + iterations + start_params : array_like + A vector of starting values for the regression + coefficients. If None, a default is chosen. + params_niter : int + The number of Gauss-Seidel updates of the mean structure + parameters that take place prior to each update of the + dependence structure. + first_dep_update : int + No dependence structure updates occur before this + iteration number. + cov_type : str + One of "robust", "naive", or "bias_reduced". + ddof_scale : scalar or None + The scale parameter is estimated as the sum of squared + Pearson residuals divided by `N - ddof_scale`, where N + is the total sample size. If `ddof_scale` is None, the + number of covariates (including an intercept if present) + is used. + scaling_factor : scalar + The estimated covariance of the parameter estimates is + scaled by this value. Default is 1, Stata uses N / (N - g), + where N is the total sample size and g is the average group + size. + scale : str or float, optional + `scale` can be None, 'X2', or a float + If a float, its value is used as the scale parameter. + The default value is None, which uses `X2` (Pearson's + chi-square) for Gamma, Gaussian, and Inverse Gaussian. + The default is 1 for the Binomial and Poisson families. + + Returns + ------- + An instance of the GEEResults class or subclass + + Notes + ----- + If convergence difficulties occur, increase the values of + `first_dep_update` and/or `params_niter`. Setting + `first_dep_update` to a greater value (e.g. ~10-20) causes the + algorithm to move close to the GLM solution before attempting + to identify the dependence structure. + + For the Gaussian family, there is no benefit to setting + `params_niter` to a value greater than 1, since the mean + structure parameters converge in one step. +""" + +_gee_results_doc = """ + Attributes + ---------- + + cov_params_default : ndarray + default covariance of the parameter estimates. Is chosen among one + of the following three based on `cov_type` + cov_robust : ndarray + covariance of the parameter estimates that is robust + cov_naive : ndarray + covariance of the parameter estimates that is not robust to + correlation or variance misspecification + cov_robust_bc : ndarray + covariance of the parameter estimates that is robust and bias + reduced + converged : bool + indicator for convergence of the optimization. + True if the norm of the score is smaller than a threshold + cov_type : str + string indicating whether a "robust", "naive" or "bias_reduced" + covariance is used as default + fit_history : dict + Contains information about the iterations. + fittedvalues : ndarray + Linear predicted values for the fitted model. + dot(exog, params) + model : class instance + Pointer to GEE model instance that called `fit`. + normalized_cov_params : ndarray + See GEE docstring + params : ndarray + The coefficients of the fitted model. Note that + interpretation of the coefficients often depends on the + distribution family and the data. + scale : float + The estimate of the scale / dispersion for the model fit. + See GEE.fit for more information. + score_norm : float + norm of the score at the end of the iterative estimation. + bse : ndarray + The standard errors of the fitted GEE parameters. +""" + +_gee_example = """ + Logistic regression with autoregressive working dependence: + + >>> import statsmodels.api as sm + >>> family = sm.families.Binomial() + >>> va = sm.cov_struct.Autoregressive() + >>> model = sm.GEE(endog, exog, group, family=family, cov_struct=va) + >>> result = model.fit() + >>> print(result.summary()) + + Use formulas to fit a Poisson GLM with independent working + dependence: + + >>> import statsmodels.api as sm + >>> fam = sm.families.Poisson() + >>> ind = sm.cov_struct.Independence() + >>> model = sm.GEE.from_formula("y ~ age + trt + base", "subject", + data, cov_struct=ind, family=fam) + >>> result = model.fit() + >>> print(result.summary()) + + Equivalent, using the formula API: + + >>> import statsmodels.api as sm + >>> import statsmodels.formula.api as smf + >>> fam = sm.families.Poisson() + >>> ind = sm.cov_struct.Independence() + >>> model = smf.gee("y ~ age + trt + base", "subject", + data, cov_struct=ind, family=fam) + >>> result = model.fit() + >>> print(result.summary()) +""" + +_gee_ordinal_example = """ + Fit an ordinal regression model using GEE, with "global + odds ratio" dependence: + + >>> import statsmodels.api as sm + >>> gor = sm.cov_struct.GlobalOddsRatio("ordinal") + >>> model = sm.OrdinalGEE(endog, exog, groups, cov_struct=gor) + >>> result = model.fit() + >>> print(result.summary()) + + Using formulas: + + >>> import statsmodels.formula.api as smf + >>> model = smf.ordinal_gee("y ~ 0 + x1 + x2", groups, data, + cov_struct=gor) + >>> result = model.fit() + >>> print(result.summary()) +""" + +_gee_nominal_example = """ + Fit a nominal regression model using GEE: + + >>> import statsmodels.api as sm + >>> import statsmodels.formula.api as smf + >>> gor = sm.cov_struct.GlobalOddsRatio("nominal") + >>> model = sm.NominalGEE(endog, exog, groups, cov_struct=gor) + >>> result = model.fit() + >>> print(result.summary()) + + Using formulas: + + >>> import statsmodels.api as sm + >>> model = sm.NominalGEE.from_formula("y ~ 0 + x1 + x2", groups, + data, cov_struct=gor) + >>> result = model.fit() + >>> print(result.summary()) + + Using the formula API: + + >>> import statsmodels.formula.api as smf + >>> model = smf.nominal_gee("y ~ 0 + x1 + x2", groups, data, + cov_struct=gor) + >>> result = model.fit() + >>> print(result.summary()) +""" + + +def _check_args(endog, exog, groups, time, offset, exposure): + + if endog.size != exog.shape[0]: + raise ValueError("Leading dimension of 'exog' should match " + "length of 'endog'") + + if groups.size != endog.size: + raise ValueError("'groups' and 'endog' should have the same size") + + if time is not None and (time.size != endog.size): + raise ValueError("'time' and 'endog' should have the same size") + + if offset is not None and (offset.size != endog.size): + raise ValueError("'offset and 'endog' should have the same size") + + if exposure is not None and (exposure.size != endog.size): + raise ValueError("'exposure' and 'endog' should have the same size") + + +class GEE(GLM): + + __doc__ = ( + " Marginal Regression Model using Generalized Estimating " + "Equations.\n" + _gee_init_doc % + {'extra_params': base._missing_param_doc, + 'family_doc': _gee_family_doc, + 'example': _gee_example, + 'notes': ""}) + + cached_means = None + + def __init__(self, endog, exog, groups, time=None, family=None, + cov_struct=None, missing='none', offset=None, + exposure=None, dep_data=None, constraint=None, + update_dep=True, weights=None, **kwargs): + + if type(self) is GEE: + self._check_kwargs(kwargs) + if family is not None: + if not isinstance(family.link, tuple(family.safe_links)): + msg = ("The {0} link function does not respect the " + "domain of the {1} family.") + warnings.warn(msg.format(family.link.__class__.__name__, + family.__class__.__name__), + DomainWarning) + + groups = np.asarray(groups) # in case groups is pandas + + if "missing_idx" in kwargs and kwargs["missing_idx"] is not None: + # If here, we are entering from super.from_formula; missing + # has already been dropped from endog and exog, but not from + # the other variables. + ii = ~kwargs["missing_idx"] + groups = groups[ii] + if time is not None: + time = time[ii] + if offset is not None: + offset = offset[ii] + if exposure is not None: + exposure = exposure[ii] + del kwargs["missing_idx"] + + self.missing = missing + self.dep_data = dep_data + self.constraint = constraint + self.update_dep = update_dep + + self._fit_history = defaultdict(list) + + # Pass groups, time, offset, and dep_data so they are + # processed for missing data along with endog and exog. + # Calling super creates self.exog, self.endog, etc. as + # ndarrays and the original exog, endog, etc. are + # self.data.endog, etc. + super().__init__(endog, exog, groups=groups, + time=time, offset=offset, + exposure=exposure, weights=weights, + dep_data=dep_data, missing=missing, + family=family, **kwargs) + + _check_args( + self.endog, + self.exog, + self.groups, + self.time, + getattr(self, "offset", None), + getattr(self, "exposure", None), + ) + + self._init_keys.extend(["update_dep", "constraint", "family", + "cov_struct"]) + # remove keys added by super that are not supported + try: + self._init_keys.remove("freq_weights") + self._init_keys.remove("var_weights") + except ValueError: + pass + + # Handle the family argument + if family is None: + family = families.Gaussian() + else: + if not issubclass(family.__class__, families.Family): + raise ValueError("GEE: `family` must be a genmod " + "family instance") + self.family = family + + # Handle the cov_struct argument + if cov_struct is None: + cov_struct = cov_structs.Independence() + else: + if not issubclass(cov_struct.__class__, cov_structs.CovStruct): + raise ValueError("GEE: `cov_struct` must be a genmod " + "cov_struct instance") + + self.cov_struct = cov_struct + + # Handle the constraint + self.constraint = None + if constraint is not None: + if len(constraint) != 2: + raise ValueError("GEE: `constraint` must be a 2-tuple.") + if constraint[0].shape[1] != self.exog.shape[1]: + raise ValueError( + "GEE: the left hand side of the constraint must have " + "the same number of columns as the exog matrix.") + self.constraint = ParameterConstraint(constraint[0], + constraint[1], + self.exog) + + if self._offset_exposure is not None: + self._offset_exposure += self.constraint.offset_increment() + else: + self._offset_exposure = ( + self.constraint.offset_increment().copy()) + self.exog = self.constraint.reduced_exog() + + # Create list of row indices for each group + group_labels, ix = np.unique(self.groups, return_inverse=True) + se = pd.Series(index=np.arange(len(ix)), dtype="int") + gb = se.groupby(ix).groups + dk = [(lb, np.asarray(gb[k])) for k, lb in enumerate(group_labels)] + self.group_indices = dict(dk) + self.group_labels = group_labels + + # Convert the data to the internal representation, which is a + # list of arrays, corresponding to the groups. + self.endog_li = self.cluster_list(self.endog) + self.exog_li = self.cluster_list(self.exog) + + if self.weights is not None: + self.weights_li = self.cluster_list(self.weights) + + self.num_group = len(self.endog_li) + + # Time defaults to a 1d grid with equal spacing + if self.time is not None: + if self.time.ndim == 1: + self.time = self.time[:, None] + self.time_li = self.cluster_list(self.time) + else: + self.time_li = \ + [np.arange(len(y), dtype=np.float64)[:, None] + for y in self.endog_li] + self.time = np.concatenate(self.time_li) + + if (self._offset_exposure is None or + (np.isscalar(self._offset_exposure) and + self._offset_exposure == 0.)): + self.offset_li = None + else: + self.offset_li = self.cluster_list(self._offset_exposure) + if constraint is not None: + self.constraint.exog_fulltrans_li = \ + self.cluster_list(self.constraint.exog_fulltrans) + + self.family = family + + self.cov_struct.initialize(self) + + # Total sample size + group_ns = [len(y) for y in self.endog_li] + self.nobs = sum(group_ns) + # The following are column based, not on rank see #1928 + self.df_model = self.exog.shape[1] - 1 # assumes constant + self.df_resid = self.nobs - self.exog.shape[1] + + # Skip the covariance updates if all groups have a single + # observation (reduces to fitting a GLM). + maxgroup = max([len(x) for x in self.endog_li]) + if maxgroup == 1: + self.update_dep = False + + # Override to allow groups and time to be passed as variable + # names. + @classmethod + def from_formula(cls, formula, groups, data, subset=None, + time=None, offset=None, exposure=None, + *args, **kwargs): + """ + Create a GEE model instance from a formula and dataframe. + + Parameters + ---------- + formula : str or generic Formula object + The formula specifying the model + groups : array_like or string + Array of grouping labels. If a string, this is the name + of a variable in `data` that contains the grouping labels. + data : array_like + The data for the model. + subset : array_like + An array-like object of booleans, integers, or index + values that indicate the subset of the data to used when + fitting the model. + time : array_like or string + The time values, used for dependence structures involving + distances between observations. If a string, this is the + name of a variable in `data` that contains the time + values. + offset : array_like or string + The offset values, added to the linear predictor. If a + string, this is the name of a variable in `data` that + contains the offset values. + exposure : array_like or string + The exposure values, only used if the link function is the + logarithm function, in which case the log of `exposure` + is added to the offset (if any). If a string, this is the + name of a variable in `data` that contains the offset + values. + {missing_param_doc} + args : extra arguments + These are passed to the model + kwargs : extra keyword arguments + These are passed to the model with two exceptions. `dep_data` + is processed as described below. The ``eval_env`` keyword is + passed to patsy. It can be either a + :class:`patsy:patsy.EvalEnvironment` object or an integer + indicating the depth of the namespace to use. For example, the + default ``eval_env=0`` uses the calling namespace. + If you wish to use a "clean" environment set ``eval_env=-1``. + + Optional arguments + ------------------ + dep_data : str or array_like + Data used for estimating the dependence structure. See + specific dependence structure classes (e.g. Nested) for + details. If `dep_data` is a string, it is interpreted as + a formula that is applied to `data`. If it is an array, it + must be an array of strings corresponding to column names in + `data`. Otherwise it must be an array-like with the same + number of rows as data. + + Returns + ------- + model : GEE model instance + + Notes + ----- + `data` must define __getitem__ with the keys in the formula + terms args and kwargs are passed on to the model + instantiation. E.g., a numpy structured or rec array, a + dictionary, or a pandas DataFrame. + """.format(missing_param_doc=base._missing_param_doc) + + groups_name = "Groups" + if isinstance(groups, str): + groups_name = groups + groups = data[groups] + + if isinstance(time, str): + time = data[time] + + if isinstance(offset, str): + offset = data[offset] + + if isinstance(exposure, str): + exposure = data[exposure] + + dep_data = kwargs.get("dep_data") + dep_data_names = None + if dep_data is not None: + if isinstance(dep_data, str): + dep_data = patsy.dmatrix(dep_data, data, + return_type='dataframe') + dep_data_names = dep_data.columns.tolist() + else: + dep_data_names = list(dep_data) + dep_data = data[dep_data] + kwargs["dep_data"] = np.asarray(dep_data) + + family = None + if "family" in kwargs: + family = kwargs["family"] + del kwargs["family"] + + model = super().from_formula(formula, data=data, subset=subset, + groups=groups, time=time, + offset=offset, + exposure=exposure, + family=family, + *args, **kwargs) + + if dep_data_names is not None: + model._dep_data_names = dep_data_names + model._groups_name = groups_name + + return model + + def cluster_list(self, array): + """ + Returns `array` split into subarrays corresponding to the + cluster structure. + """ + + if array.ndim == 1: + return [np.array(array[self.group_indices[k]]) + for k in self.group_labels] + else: + return [np.array(array[self.group_indices[k], :]) + for k in self.group_labels] + + def compare_score_test(self, submodel): + """ + Perform a score test for the given submodel against this model. + + Parameters + ---------- + submodel : GEEResults instance + A fitted GEE model that is a submodel of this model. + + Returns + ------- + A dictionary with keys "statistic", "p-value", and "df", + containing the score test statistic, its chi^2 p-value, + and the degrees of freedom used to compute the p-value. + + Notes + ----- + The score test can be performed without calling 'fit' on the + larger model. The provided submodel must be obtained from a + fitted GEE. + + This method performs the same score test as can be obtained by + fitting the GEE with a linear constraint and calling `score_test` + on the results. + + References + ---------- + Xu Guo and Wei Pan (2002). "Small sample performance of the score + test in GEE". + http://www.sph.umn.edu/faculty1/wp-content/uploads/2012/11/rr2002-013.pdf + """ + + # Since the model has not been fit, its scaletype has not been + # set. So give it the scaletype of the submodel. + self.scaletype = submodel.model.scaletype + + # Check consistency between model and submodel (not a comprehensive + # check) + submod = submodel.model + if self.exog.shape[0] != submod.exog.shape[0]: + msg = "Model and submodel have different numbers of cases." + raise ValueError(msg) + if self.exog.shape[1] == submod.exog.shape[1]: + msg = "Model and submodel have the same number of variables" + warnings.warn(msg) + if not isinstance(self.family, type(submod.family)): + msg = "Model and submodel have different GLM families." + warnings.warn(msg) + if not isinstance(self.cov_struct, type(submod.cov_struct)): + warnings.warn("Model and submodel have different GEE covariance " + "structures.") + if not np.equal(self.weights, submod.weights).all(): + msg = "Model and submodel should have the same weights." + warnings.warn(msg) + + # Get the positions of the submodel variables in the + # parent model + qm, qc = _score_test_submodel(self, submodel.model) + if qm is None: + msg = "The provided model is not a submodel." + raise ValueError(msg) + + # Embed the submodel params into a params vector for the + # parent model + params_ex = np.dot(qm, submodel.params) + + # Attempt to preserve the state of the parent model + cov_struct_save = self.cov_struct + import copy + cached_means_save = copy.deepcopy(self.cached_means) + + # Get the score vector of the submodel params in + # the parent model + self.cov_struct = submodel.cov_struct + self.update_cached_means(params_ex) + _, score = self._update_mean_params() + if score is None: + msg = "Singular matrix encountered in GEE score test" + warnings.warn(msg, ConvergenceWarning) + return None + + if not hasattr(self, "ddof_scale"): + self.ddof_scale = self.exog.shape[1] + + if not hasattr(self, "scaling_factor"): + self.scaling_factor = 1 + + _, ncov1, cmat = self._covmat() + score2 = np.dot(qc.T, score) + + try: + amat = np.linalg.inv(ncov1) + except np.linalg.LinAlgError: + amat = np.linalg.pinv(ncov1) + + bmat_11 = np.dot(qm.T, np.dot(cmat, qm)) + bmat_22 = np.dot(qc.T, np.dot(cmat, qc)) + bmat_12 = np.dot(qm.T, np.dot(cmat, qc)) + + amat_11 = np.dot(qm.T, np.dot(amat, qm)) + amat_12 = np.dot(qm.T, np.dot(amat, qc)) + + try: + ab = np.linalg.solve(amat_11, bmat_12) + except np.linalg.LinAlgError: + ab = np.dot(np.linalg.pinv(amat_11), bmat_12) + + score_cov = bmat_22 - np.dot(amat_12.T, ab) + + try: + aa = np.linalg.solve(amat_11, amat_12) + except np.linalg.LinAlgError: + aa = np.dot(np.linalg.pinv(amat_11), amat_12) + + score_cov -= np.dot(bmat_12.T, aa) + + try: + ab = np.linalg.solve(amat_11, bmat_11) + except np.linalg.LinAlgError: + ab = np.dot(np.linalg.pinv(amat_11), bmat_11) + + try: + aa = np.linalg.solve(amat_11, amat_12) + except np.linalg.LinAlgError: + aa = np.dot(np.linalg.pinv(amat_11), amat_12) + + score_cov += np.dot(amat_12.T, np.dot(ab, aa)) + + # Attempt to restore state + self.cov_struct = cov_struct_save + self.cached_means = cached_means_save + + from scipy.stats.distributions import chi2 + try: + sc2 = np.linalg.solve(score_cov, score2) + except np.linalg.LinAlgError: + sc2 = np.dot(np.linalg.pinv(score_cov), score2) + score_statistic = np.dot(score2, sc2) + score_df = len(score2) + score_pvalue = 1 - chi2.cdf(score_statistic, score_df) + return {"statistic": score_statistic, + "df": score_df, + "p-value": score_pvalue} + + def estimate_scale(self): + """ + Estimate the dispersion/scale. + """ + + if self.scaletype is None: + if isinstance(self.family, (families.Binomial, families.Poisson, + families.NegativeBinomial, + _Multinomial)): + return 1. + elif isinstance(self.scaletype, float): + return np.array(self.scaletype) + + endog = self.endog_li + cached_means = self.cached_means + nobs = self.nobs + varfunc = self.family.variance + + scale = 0. + fsum = 0. + for i in range(self.num_group): + + if len(endog[i]) == 0: + continue + + expval, _ = cached_means[i] + sdev = np.sqrt(varfunc(expval)) + resid = (endog[i] - expval) / sdev + + if self.weights is not None: + f = self.weights_li[i] + scale += np.sum(f * (resid ** 2)) + fsum += f.sum() + else: + scale += np.sum(resid ** 2) + fsum += len(resid) + + scale /= (fsum * (nobs - self.ddof_scale) / float(nobs)) + + return scale + + def mean_deriv(self, exog, lin_pred): + """ + Derivative of the expected endog with respect to the parameters. + + Parameters + ---------- + exog : array_like + The exogeneous data at which the derivative is computed. + lin_pred : array_like + The values of the linear predictor. + + Returns + ------- + The value of the derivative of the expected endog with respect + to the parameter vector. + + Notes + ----- + If there is an offset or exposure, it should be added to + `lin_pred` prior to calling this function. + """ + + idl = self.family.link.inverse_deriv(lin_pred) + dmat = exog * idl[:, None] + return dmat + + def mean_deriv_exog(self, exog, params, offset_exposure=None): + """ + Derivative of the expected endog with respect to exog. + + Parameters + ---------- + exog : array_like + Values of the independent variables at which the derivative + is calculated. + params : array_like + Parameter values at which the derivative is calculated. + offset_exposure : array_like, optional + Combined offset and exposure. + + Returns + ------- + The derivative of the expected endog with respect to exog. + """ + + lin_pred = np.dot(exog, params) + if offset_exposure is not None: + lin_pred += offset_exposure + + idl = self.family.link.inverse_deriv(lin_pred) + dmat = np.outer(idl, params) + return dmat + + def _update_mean_params(self): + """ + Returns + ------- + update : array_like + The update vector such that params + update is the next + iterate when solving the score equations. + score : array_like + The current value of the score equations, not + incorporating the scale parameter. If desired, + multiply this vector by the scale parameter to + incorporate the scale. + """ + + endog = self.endog_li + exog = self.exog_li + weights = getattr(self, "weights_li", None) + + cached_means = self.cached_means + + varfunc = self.family.variance + + bmat, score = 0, 0 + for i in range(self.num_group): + + expval, lpr = cached_means[i] + resid = endog[i] - expval + dmat = self.mean_deriv(exog[i], lpr) + sdev = np.sqrt(varfunc(expval)) + + if weights is not None: + w = weights[i] + wresid = resid * w + wdmat = dmat * w[:, None] + else: + wresid = resid + wdmat = dmat + + rslt = self.cov_struct.covariance_matrix_solve( + expval, i, sdev, (wdmat, wresid)) + if rslt is None: + return None, None + vinv_d, vinv_resid = tuple(rslt) + + bmat += np.dot(dmat.T, vinv_d) + score += np.dot(dmat.T, vinv_resid) + + try: + update = np.linalg.solve(bmat, score) + except np.linalg.LinAlgError: + update = np.dot(np.linalg.pinv(bmat), score) + + self._fit_history["cov_adjust"].append( + self.cov_struct.cov_adjust) + + return update, score + + def update_cached_means(self, mean_params): + """ + cached_means should always contain the most recent calculation + of the group-wise mean vectors. This function should be + called every time the regression parameters are changed, to + keep the cached means up to date. + """ + + endog = self.endog_li + exog = self.exog_li + offset = self.offset_li + + linkinv = self.family.link.inverse + + self.cached_means = [] + + for i in range(self.num_group): + + if len(endog[i]) == 0: + continue + + lpr = np.dot(exog[i], mean_params) + if offset is not None: + lpr += offset[i] + expval = linkinv(lpr) + + self.cached_means.append((expval, lpr)) + + def _covmat(self): + """ + Returns the sampling covariance matrix of the regression + parameters and related quantities. + + Returns + ------- + cov_robust : array_like + The robust, or sandwich estimate of the covariance, which + is meaningful even if the working covariance structure is + incorrectly specified. + cov_naive : array_like + The model-based estimate of the covariance, which is + meaningful if the covariance structure is correctly + specified. + cmat : array_like + The center matrix of the sandwich expression, used in + obtaining score test results. + """ + + endog = self.endog_li + exog = self.exog_li + weights = getattr(self, "weights_li", None) + varfunc = self.family.variance + cached_means = self.cached_means + + # Calculate the naive (model-based) and robust (sandwich) + # covariances. + bmat, cmat = 0, 0 + for i in range(self.num_group): + + expval, lpr = cached_means[i] + resid = endog[i] - expval + dmat = self.mean_deriv(exog[i], lpr) + sdev = np.sqrt(varfunc(expval)) + + if weights is not None: + w = weights[i] + wresid = resid * w + wdmat = dmat * w[:, None] + else: + wresid = resid + wdmat = dmat + + rslt = self.cov_struct.covariance_matrix_solve( + expval, i, sdev, (wdmat, wresid)) + if rslt is None: + return None, None, None, None + vinv_d, vinv_resid = tuple(rslt) + + bmat += np.dot(dmat.T, vinv_d) + dvinv_resid = np.dot(dmat.T, vinv_resid) + cmat += np.outer(dvinv_resid, dvinv_resid) + + scale = self.estimate_scale() + + try: + bmati = np.linalg.inv(bmat) + except np.linalg.LinAlgError: + bmati = np.linalg.pinv(bmat) + + cov_naive = bmati * scale + cov_robust = np.dot(bmati, np.dot(cmat, bmati)) + + cov_naive *= self.scaling_factor + cov_robust *= self.scaling_factor + return cov_robust, cov_naive, cmat + + # Calculate the bias-corrected sandwich estimate of Mancl and + # DeRouen. + def _bc_covmat(self, cov_naive): + + cov_naive = cov_naive / self.scaling_factor + endog = self.endog_li + exog = self.exog_li + varfunc = self.family.variance + cached_means = self.cached_means + scale = self.estimate_scale() + + bcm = 0 + for i in range(self.num_group): + + expval, lpr = cached_means[i] + resid = endog[i] - expval + dmat = self.mean_deriv(exog[i], lpr) + sdev = np.sqrt(varfunc(expval)) + + rslt = self.cov_struct.covariance_matrix_solve( + expval, i, sdev, (dmat,)) + if rslt is None: + return None + vinv_d = rslt[0] + vinv_d /= scale + + hmat = np.dot(vinv_d, cov_naive) + hmat = np.dot(hmat, dmat.T).T + + f = self.weights_li[i] if self.weights is not None else 1. + + aresid = np.linalg.solve(np.eye(len(resid)) - hmat, resid) + rslt = self.cov_struct.covariance_matrix_solve( + expval, i, sdev, (aresid,)) + if rslt is None: + return None + srt = rslt[0] + srt = f * np.dot(dmat.T, srt) / scale + bcm += np.outer(srt, srt) + + cov_robust_bc = np.dot(cov_naive, np.dot(bcm, cov_naive)) + cov_robust_bc *= self.scaling_factor + + return cov_robust_bc + + def _starting_params(self): + + if np.isscalar(self._offset_exposure): + offset = None + else: + offset = self._offset_exposure + + model = GLM(self.endog, self.exog, family=self.family, + offset=offset, freq_weights=self.weights) + result = model.fit() + return result.params + + @Appender(_gee_fit_doc) + def fit(self, maxiter=60, ctol=1e-6, start_params=None, + params_niter=1, first_dep_update=0, + cov_type='robust', ddof_scale=None, scaling_factor=1., + scale=None): + + self.scaletype = scale + + # Subtract this number from the total sample size when + # normalizing the scale parameter estimate. + if ddof_scale is None: + self.ddof_scale = self.exog.shape[1] + else: + if not ddof_scale >= 0: + raise ValueError( + "ddof_scale must be a non-negative number or None") + self.ddof_scale = ddof_scale + + self.scaling_factor = scaling_factor + + self._fit_history = defaultdict(list) + + if self.weights is not None and cov_type == 'naive': + raise ValueError("when using weights, cov_type may not be naive") + + if start_params is None: + mean_params = self._starting_params() + else: + start_params = np.asarray(start_params) + mean_params = start_params.copy() + + self.update_cached_means(mean_params) + + del_params = -1. + num_assoc_updates = 0 + for itr in range(maxiter): + + update, score = self._update_mean_params() + if update is None: + warnings.warn("Singular matrix encountered in GEE update", + ConvergenceWarning) + break + mean_params += update + self.update_cached_means(mean_params) + + # L2 norm of the change in mean structure parameters at + # this iteration. + del_params = np.sqrt(np.sum(score ** 2)) + + self._fit_history['params'].append(mean_params.copy()) + self._fit_history['score'].append(score) + self._fit_history['dep_params'].append( + self.cov_struct.dep_params) + + # Do not exit until the association parameters have been + # updated at least once. + if (del_params < ctol and + (num_assoc_updates > 0 or self.update_dep is False)): + break + + # Update the dependence structure + if (self.update_dep and (itr % params_niter) == 0 + and (itr >= first_dep_update)): + self._update_assoc(mean_params) + num_assoc_updates += 1 + + if del_params >= ctol: + warnings.warn("Iteration limit reached prior to convergence", + IterationLimitWarning) + + if mean_params is None: + warnings.warn("Unable to estimate GEE parameters.", + ConvergenceWarning) + return None + + bcov, ncov, _ = self._covmat() + if bcov is None: + warnings.warn("Estimated covariance structure for GEE " + "estimates is singular", ConvergenceWarning) + return None + bc_cov = None + if cov_type == "bias_reduced": + bc_cov = self._bc_covmat(ncov) + + if self.constraint is not None: + x = mean_params.copy() + mean_params, bcov = self._handle_constraint(mean_params, bcov) + if mean_params is None: + warnings.warn("Unable to estimate constrained GEE " + "parameters.", ConvergenceWarning) + return None + + y, ncov = self._handle_constraint(x, ncov) + if y is None: + warnings.warn("Unable to estimate constrained GEE " + "parameters.", ConvergenceWarning) + return None + + if bc_cov is not None: + y, bc_cov = self._handle_constraint(x, bc_cov) + if x is None: + warnings.warn("Unable to estimate constrained GEE " + "parameters.", ConvergenceWarning) + return None + + scale = self.estimate_scale() + + # kwargs to add to results instance, need to be available in __init__ + res_kwds = dict(cov_type=cov_type, + cov_robust=bcov, + cov_naive=ncov, + cov_robust_bc=bc_cov) + + # The superclass constructor will multiply the covariance + # matrix argument bcov by scale, which we do not want, so we + # divide bcov by the scale parameter here + results = GEEResults(self, mean_params, bcov / scale, scale, + cov_type=cov_type, use_t=False, + attr_kwds=res_kwds) + + # attributes not needed during results__init__ + results.fit_history = self._fit_history + self.fit_history = defaultdict(list) + results.score_norm = del_params + results.converged = (del_params < ctol) + results.cov_struct = self.cov_struct + results.params_niter = params_niter + results.first_dep_update = first_dep_update + results.ctol = ctol + results.maxiter = maxiter + + # These will be copied over to subclasses when upgrading. + results._props = ["cov_type", "use_t", + "cov_params_default", "cov_robust", + "cov_naive", "cov_robust_bc", + "fit_history", + "score_norm", "converged", "cov_struct", + "params_niter", "first_dep_update", "ctol", + "maxiter"] + + return GEEResultsWrapper(results) + + def _update_regularized(self, params, pen_wt, scad_param, eps): + + sn, hm = 0, 0 + + for i in range(self.num_group): + + expval, _ = self.cached_means[i] + resid = self.endog_li[i] - expval + sdev = np.sqrt(self.family.variance(expval)) + + ex = self.exog_li[i] * sdev[:, None]**2 + rslt = self.cov_struct.covariance_matrix_solve( + expval, i, sdev, (resid, ex)) + sn0 = rslt[0] + sn += np.dot(ex.T, sn0) + hm0 = rslt[1] + hm += np.dot(ex.T, hm0) + + # Wang et al. divide sn here by num_group, but that + # seems to be incorrect + + ap = np.abs(params) + clipped = np.clip(scad_param * pen_wt - ap, 0, np.inf) + en = pen_wt * clipped * (ap > pen_wt) + en /= (scad_param - 1) * pen_wt + en += pen_wt * (ap <= pen_wt) + en /= eps + ap + + hm.flat[::hm.shape[0] + 1] += self.num_group * en + sn -= self.num_group * en * params + try: + update = np.linalg.solve(hm, sn) + except np.linalg.LinAlgError: + update = np.dot(np.linalg.pinv(hm), sn) + msg = "Encountered singularity in regularized GEE update" + warnings.warn(msg) + hm *= self.estimate_scale() + + return update, hm + + def _regularized_covmat(self, mean_params): + + self.update_cached_means(mean_params) + + ma = 0 + + for i in range(self.num_group): + + expval, _ = self.cached_means[i] + resid = self.endog_li[i] - expval + sdev = np.sqrt(self.family.variance(expval)) + + ex = self.exog_li[i] * sdev[:, None]**2 + rslt = self.cov_struct.covariance_matrix_solve( + expval, i, sdev, (resid,)) + ma0 = np.dot(ex.T, rslt[0]) + ma += np.outer(ma0, ma0) + + return ma + + def fit_regularized(self, pen_wt, scad_param=3.7, maxiter=100, + ddof_scale=None, update_assoc=5, + ctol=1e-5, ztol=1e-3, eps=1e-6, scale=None): + """ + Regularized estimation for GEE. + + Parameters + ---------- + pen_wt : float + The penalty weight (a non-negative scalar). + scad_param : float + Non-negative scalar determining the shape of the Scad + penalty. + maxiter : int + The maximum number of iterations. + ddof_scale : int + Value to subtract from `nobs` when calculating the + denominator degrees of freedom for t-statistics, defaults + to the number of columns in `exog`. + update_assoc : int + The dependence parameters are updated every `update_assoc` + iterations of the mean structure parameter updates. + ctol : float + Convergence criterion, default is one order of magnitude + smaller than proposed in section 3.1 of Wang et al. + ztol : float + Coefficients smaller than this value are treated as + being zero, default is based on section 5 of Wang et al. + eps : non-negative scalar + Numerical constant, see section 3.2 of Wang et al. + scale : float or string + If a float, this value is used as the scale parameter. + If "X2", the scale parameter is always estimated using + Pearson's chi-square method (e.g. as in a quasi-Poisson + analysis). If None, the default approach for the family + is used to estimate the scale parameter. + + Returns + ------- + GEEResults instance. Note that not all methods of the results + class make sense when the model has been fit with regularization. + + Notes + ----- + This implementation assumes that the link is canonical. + + References + ---------- + Wang L, Zhou J, Qu A. (2012). Penalized generalized estimating + equations for high-dimensional longitudinal data analysis. + Biometrics. 2012 Jun;68(2):353-60. + doi: 10.1111/j.1541-0420.2011.01678.x. + https://www.ncbi.nlm.nih.gov/pubmed/21955051 + http://users.stat.umn.edu/~wangx346/research/GEE_selection.pdf + """ + + self.scaletype = scale + + mean_params = np.zeros(self.exog.shape[1]) + self.update_cached_means(mean_params) + converged = False + fit_history = defaultdict(list) + + # Subtract this number from the total sample size when + # normalizing the scale parameter estimate. + if ddof_scale is None: + self.ddof_scale = self.exog.shape[1] + else: + if not ddof_scale >= 0: + raise ValueError( + "ddof_scale must be a non-negative number or None") + self.ddof_scale = ddof_scale + + # Keep this private for now. In some cases the early steps are + # very small so it seems necessary to ensure a certain minimum + # number of iterations before testing for convergence. + miniter = 20 + + for itr in range(maxiter): + + update, hm = self._update_regularized( + mean_params, pen_wt, scad_param, eps) + if update is None: + msg = "Singular matrix encountered in regularized GEE update" + warnings.warn(msg, ConvergenceWarning) + break + if itr > miniter and np.sqrt(np.sum(update**2)) < ctol: + converged = True + break + mean_params += update + fit_history['params'].append(mean_params.copy()) + self.update_cached_means(mean_params) + + if itr != 0 and (itr % update_assoc == 0): + self._update_assoc(mean_params) + + if not converged: + msg = "GEE.fit_regularized did not converge" + warnings.warn(msg) + + mean_params[np.abs(mean_params) < ztol] = 0 + + self._update_assoc(mean_params) + ma = self._regularized_covmat(mean_params) + cov = np.linalg.solve(hm, ma) + cov = np.linalg.solve(hm, cov.T) + + # kwargs to add to results instance, need to be available in __init__ + res_kwds = dict(cov_type="robust", cov_robust=cov) + + scale = self.estimate_scale() + rslt = GEEResults(self, mean_params, cov, scale, + regularized=True, attr_kwds=res_kwds) + rslt.fit_history = fit_history + + return GEEResultsWrapper(rslt) + + def _handle_constraint(self, mean_params, bcov): + """ + Expand the parameter estimate `mean_params` and covariance matrix + `bcov` to the coordinate system of the unconstrained model. + + Parameters + ---------- + mean_params : array_like + A parameter vector estimate for the reduced model. + bcov : array_like + The covariance matrix of mean_params. + + Returns + ------- + mean_params : array_like + The input parameter vector mean_params, expanded to the + coordinate system of the full model + bcov : array_like + The input covariance matrix bcov, expanded to the + coordinate system of the full model + """ + + # The number of variables in the full model + red_p = len(mean_params) + full_p = self.constraint.lhs.shape[1] + mean_params0 = np.r_[mean_params, np.zeros(full_p - red_p)] + + # Get the score vector under the full model. + save_exog_li = self.exog_li + self.exog_li = self.constraint.exog_fulltrans_li + import copy + save_cached_means = copy.deepcopy(self.cached_means) + self.update_cached_means(mean_params0) + _, score = self._update_mean_params() + + if score is None: + warnings.warn("Singular matrix encountered in GEE score test", + ConvergenceWarning) + return None, None + + _, ncov1, cmat = self._covmat() + scale = self.estimate_scale() + cmat = cmat / scale ** 2 + score2 = score[red_p:] / scale + amat = np.linalg.inv(ncov1) + + bmat_11 = cmat[0:red_p, 0:red_p] + bmat_22 = cmat[red_p:, red_p:] + bmat_12 = cmat[0:red_p, red_p:] + amat_11 = amat[0:red_p, 0:red_p] + amat_12 = amat[0:red_p, red_p:] + + score_cov = bmat_22 - np.dot(amat_12.T, + np.linalg.solve(amat_11, bmat_12)) + score_cov -= np.dot(bmat_12.T, + np.linalg.solve(amat_11, amat_12)) + score_cov += np.dot(amat_12.T, + np.dot(np.linalg.solve(amat_11, bmat_11), + np.linalg.solve(amat_11, amat_12))) + + from scipy.stats.distributions import chi2 + score_statistic = np.dot(score2, + np.linalg.solve(score_cov, score2)) + score_df = len(score2) + score_pvalue = 1 - chi2.cdf(score_statistic, score_df) + self.score_test_results = {"statistic": score_statistic, + "df": score_df, + "p-value": score_pvalue} + + mean_params = self.constraint.unpack_param(mean_params) + bcov = self.constraint.unpack_cov(bcov) + + self.exog_li = save_exog_li + self.cached_means = save_cached_means + self.exog = self.constraint.restore_exog() + + return mean_params, bcov + + def _update_assoc(self, params): + """ + Update the association parameters + """ + + self.cov_struct.update(params) + + def _derivative_exog(self, params, exog=None, transform='dydx', + dummy_idx=None, count_idx=None): + """ + For computing marginal effects, returns dF(XB) / dX where F(.) + is the fitted mean. + + transform can be 'dydx', 'dyex', 'eydx', or 'eyex'. + + Not all of these make sense in the presence of discrete regressors, + but checks are done in the results in get_margeff. + """ + # This form should be appropriate for group 1 probit, logit, + # logistic, cloglog, heckprob, xtprobit. + offset_exposure = None + if exog is None: + exog = self.exog + offset_exposure = self._offset_exposure + + margeff = self.mean_deriv_exog(exog, params, offset_exposure) + + if 'ex' in transform: + margeff *= exog + if 'ey' in transform: + margeff /= self.predict(params, exog)[:, None] + if count_idx is not None: + from statsmodels.discrete.discrete_margins import ( + _get_count_effects) + margeff = _get_count_effects(margeff, exog, count_idx, transform, + self, params) + if dummy_idx is not None: + from statsmodels.discrete.discrete_margins import ( + _get_dummy_effects) + margeff = _get_dummy_effects(margeff, exog, dummy_idx, transform, + self, params) + return margeff + + def qic(self, params, scale, cov_params, n_step=1000): + """ + Returns quasi-information criteria and quasi-likelihood values. + + Parameters + ---------- + params : array_like + The GEE estimates of the regression parameters. + scale : scalar + Estimated scale parameter + cov_params : array_like + An estimate of the covariance matrix for the + model parameters. Conventionally this is the robust + covariance matrix. + n_step : integer + The number of points in the trapezoidal approximation + to the quasi-likelihood function. + + Returns + ------- + ql : scalar + The quasi-likelihood value + qic : scalar + A QIC that can be used to compare the mean and covariance + structures of the model. + qicu : scalar + A simplified QIC that can be used to compare mean structures + but not covariance structures + + Notes + ----- + The quasi-likelihood used here is obtained by numerically evaluating + Wedderburn's integral representation of the quasi-likelihood function. + This approach is valid for all families and links. Many other + packages use analytical expressions for quasi-likelihoods that are + valid in special cases where the link function is canonical. These + analytical expressions may omit additive constants that only depend + on the data. Therefore, the numerical values of our QL and QIC values + will differ from the values reported by other packages. However only + the differences between two QIC values calculated for different models + using the same data are meaningful. Our QIC should produce the same + QIC differences as other software. + + When using the QIC for models with unknown scale parameter, use a + common estimate of the scale parameter for all models being compared. + + References + ---------- + .. [*] W. Pan (2001). Akaike's information criterion in generalized + estimating equations. Biometrics (57) 1. + """ + + varfunc = self.family.variance + + means = [] + omega = 0.0 + # omega^-1 is the model-based covariance assuming independence + + for i in range(self.num_group): + expval, lpr = self.cached_means[i] + means.append(expval) + dmat = self.mean_deriv(self.exog_li[i], lpr) + omega += np.dot(dmat.T, dmat) / scale + + means = np.concatenate(means) + + # The quasi-likelihood, use change of variables so the integration is + # from -1 to 1. + endog_li = np.concatenate(self.endog_li) + du = means - endog_li + qv = np.empty(n_step) + xv = np.linspace(-0.99999, 1, n_step) + for i, g in enumerate(xv): + u = endog_li + (g + 1) * du / 2.0 + vu = varfunc(u) + qv[i] = -np.sum(du**2 * (g + 1) / vu) + qv /= (4 * scale) + + try: + from scipy.integrate import trapezoid + except ImportError: + # Remove after minimum is SciPy 1.7 + from scipy.integrate import trapz as trapezoid + ql = trapezoid(qv, dx=xv[1] - xv[0]) + + qicu = -2 * ql + 2 * self.exog.shape[1] + qic = -2 * ql + 2 * np.trace(np.dot(omega, cov_params)) + + return ql, qic, qicu + + +class GEEResults(GLMResults): + + __doc__ = ( + "This class summarizes the fit of a marginal regression model " + "using GEE.\n" + _gee_results_doc) + + def __init__(self, model, params, cov_params, scale, + cov_type='robust', use_t=False, regularized=False, + **kwds): + + super().__init__( + model, params, normalized_cov_params=cov_params, scale=scale + ) + + # not added by super + self.df_resid = model.df_resid + self.df_model = model.df_model + self.family = model.family + + attr_kwds = kwds.pop('attr_kwds', {}) + self.__dict__.update(attr_kwds) + + # we do not do this if the cov_type has already been set + # subclasses can set it through attr_kwds + if not (hasattr(self, 'cov_type') and + hasattr(self, 'cov_params_default')): + self.cov_type = cov_type # keep alias + covariance_type = self.cov_type.lower() + allowed_covariances = ["robust", "naive", "bias_reduced"] + if covariance_type not in allowed_covariances: + msg = ("GEE: `cov_type` must be one of " + + ", ".join(allowed_covariances)) + raise ValueError(msg) + + if cov_type == "robust": + cov = self.cov_robust + elif cov_type == "naive": + cov = self.cov_naive + elif cov_type == "bias_reduced": + cov = self.cov_robust_bc + + self.cov_params_default = cov + else: + if self.cov_type != cov_type: + raise ValueError('cov_type in argument is different from ' + 'already attached cov_type') + + @cache_readonly + def resid(self): + """ + The response residuals. + """ + return self.resid_response + + def standard_errors(self, cov_type="robust"): + """ + This is a convenience function that returns the standard + errors for any covariance type. The value of `bse` is the + standard errors for whichever covariance type is specified as + an argument to `fit` (defaults to "robust"). + + Parameters + ---------- + cov_type : str + One of "robust", "naive", or "bias_reduced". Determines + the covariance used to compute standard errors. Defaults + to "robust". + """ + + # Check covariance_type + covariance_type = cov_type.lower() + allowed_covariances = ["robust", "naive", "bias_reduced"] + if covariance_type not in allowed_covariances: + msg = ("GEE: `covariance_type` must be one of " + + ", ".join(allowed_covariances)) + raise ValueError(msg) + + if covariance_type == "robust": + return np.sqrt(np.diag(self.cov_robust)) + elif covariance_type == "naive": + return np.sqrt(np.diag(self.cov_naive)) + elif covariance_type == "bias_reduced": + if self.cov_robust_bc is None: + raise ValueError( + "GEE: `bias_reduced` covariance not available") + return np.sqrt(np.diag(self.cov_robust_bc)) + + # Need to override to allow for different covariance types. + @cache_readonly + def bse(self): + return self.standard_errors(self.cov_type) + + def score_test(self): + """ + Return the results of a score test for a linear constraint. + + Returns + ------- + Adictionary containing the p-value, the test statistic, + and the degrees of freedom for the score test. + + Notes + ----- + See also GEE.compare_score_test for an alternative way to perform + a score test. GEEResults.score_test is more general, in that it + supports testing arbitrary linear equality constraints. However + GEE.compare_score_test might be easier to use when comparing + two explicit models. + + References + ---------- + Xu Guo and Wei Pan (2002). "Small sample performance of the score + test in GEE". + http://www.sph.umn.edu/faculty1/wp-content/uploads/2012/11/rr2002-013.pdf + """ + + if not hasattr(self.model, "score_test_results"): + msg = "score_test on results instance only available when " + msg += " model was fit with constraints" + raise ValueError(msg) + + return self.model.score_test_results + + @cache_readonly + def resid_split(self): + """ + Returns the residuals, the endogeneous data minus the fitted + values from the model. The residuals are returned as a list + of arrays containing the residuals for each cluster. + """ + sresid = [] + for v in self.model.group_labels: + ii = self.model.group_indices[v] + sresid.append(self.resid[ii]) + return sresid + + @cache_readonly + def resid_centered(self): + """ + Returns the residuals centered within each group. + """ + cresid = self.resid.copy() + for v in self.model.group_labels: + ii = self.model.group_indices[v] + cresid[ii] -= cresid[ii].mean() + return cresid + + @cache_readonly + def resid_centered_split(self): + """ + Returns the residuals centered within each group. The + residuals are returned as a list of arrays containing the + centered residuals for each cluster. + """ + sresid = [] + for v in self.model.group_labels: + ii = self.model.group_indices[v] + sresid.append(self.centered_resid[ii]) + return sresid + + def qic(self, scale=None, n_step=1000): + """ + Returns the QIC and QICu information criteria. + + See GEE.qic for documentation. + """ + + # It is easy to forget to set the scale parameter. Sometimes + # this is intentional, so we warn. + if scale is None: + warnings.warn("QIC values obtained using scale=None are not " + "appropriate for comparing models") + + if scale is None: + scale = self.scale + + _, qic, qicu = self.model.qic(self.params, scale, + self.cov_params(), + n_step=n_step) + + return qic, qicu + + # FIXME: alias to be removed, temporary backwards compatibility + split_resid = resid_split + centered_resid = resid_centered + split_centered_resid = resid_centered_split + + @Appender(_plot_added_variable_doc % {'extra_params_doc': ''}) + def plot_added_variable(self, focus_exog, resid_type=None, + use_glm_weights=True, fit_kwargs=None, + ax=None): + + from statsmodels.graphics.regressionplots import plot_added_variable + + fig = plot_added_variable(self, focus_exog, + resid_type=resid_type, + use_glm_weights=use_glm_weights, + fit_kwargs=fit_kwargs, ax=ax) + + return fig + + @Appender(_plot_partial_residuals_doc % {'extra_params_doc': ''}) + def plot_partial_residuals(self, focus_exog, ax=None): + + from statsmodels.graphics.regressionplots import plot_partial_residuals + + return plot_partial_residuals(self, focus_exog, ax=ax) + + @Appender(_plot_ceres_residuals_doc % {'extra_params_doc': ''}) + def plot_ceres_residuals(self, focus_exog, frac=0.66, cond_means=None, + ax=None): + + from statsmodels.graphics.regressionplots import plot_ceres_residuals + + return plot_ceres_residuals(self, focus_exog, frac, + cond_means=cond_means, ax=ax) + + def conf_int(self, alpha=.05, cols=None, cov_type=None): + """ + Returns confidence intervals for the fitted parameters. + + Parameters + ---------- + alpha : float, optional + The `alpha` level for the confidence interval. i.e., The + default `alpha` = .05 returns a 95% confidence interval. + cols : array_like, optional + `cols` specifies which confidence intervals to return + cov_type : str + The covariance type used for computing standard errors; + must be one of 'robust', 'naive', and 'bias reduced'. + See `GEE` for details. + + Notes + ----- + The confidence interval is based on the Gaussian distribution. + """ + # super does not allow to specify cov_type and method is not + # implemented, + # FIXME: remove this method here + if cov_type is None: + bse = self.bse + else: + bse = self.standard_errors(cov_type=cov_type) + params = self.params + dist = stats.norm + q = dist.ppf(1 - alpha / 2) + + if cols is None: + lower = self.params - q * bse + upper = self.params + q * bse + else: + cols = np.asarray(cols) + lower = params[cols] - q * bse[cols] + upper = params[cols] + q * bse[cols] + return np.asarray(lzip(lower, upper)) + + def summary(self, yname=None, xname=None, title=None, alpha=.05): + """ + Summarize the GEE regression results + + Parameters + ---------- + yname : str, optional + Default is `y` + xname : list[str], optional + Names for the exogenous variables, default is `var_#` for ## in + the number of regressors. Must match the number of parameters in + the model + title : str, optional + Title for the top table. If not None, then this replaces + the default title + alpha : float + significance level for the confidence intervals + cov_type : str + The covariance type used to compute the standard errors; + one of 'robust' (the usual robust sandwich-type covariance + estimate), 'naive' (ignores dependence), and 'bias + reduced' (the Mancl/DeRouen estimate). + + Returns + ------- + smry : Summary instance + this holds the summary tables and text, which can be + printed or converted to various output formats. + + See Also + -------- + statsmodels.iolib.summary.Summary : class to hold summary results + """ + + top_left = [('Dep. Variable:', None), + ('Model:', None), + ('Method:', ['Generalized']), + ('', ['Estimating Equations']), + ('Family:', [self.model.family.__class__.__name__]), + ('Dependence structure:', + [self.model.cov_struct.__class__.__name__]), + ('Date:', None), + ('Covariance type: ', [self.cov_type, ]) + ] + + NY = [len(y) for y in self.model.endog_li] + + top_right = [('No. Observations:', [sum(NY)]), + ('No. clusters:', [len(self.model.endog_li)]), + ('Min. cluster size:', [min(NY)]), + ('Max. cluster size:', [max(NY)]), + ('Mean cluster size:', ["%.1f" % np.mean(NY)]), + ('Num. iterations:', ['%d' % + len(self.fit_history['params'])]), + ('Scale:', ["%.3f" % self.scale]), + ('Time:', None), + ] + + # The skew of the residuals + skew1 = stats.skew(self.resid) + kurt1 = stats.kurtosis(self.resid) + skew2 = stats.skew(self.centered_resid) + kurt2 = stats.kurtosis(self.centered_resid) + + diagn_left = [('Skew:', ["%12.4f" % skew1]), + ('Centered skew:', ["%12.4f" % skew2])] + + diagn_right = [('Kurtosis:', ["%12.4f" % kurt1]), + ('Centered kurtosis:', ["%12.4f" % kurt2]) + ] + + if title is None: + title = self.model.__class__.__name__ + ' ' +\ + "Regression Results" + + # Override the exog variable names if xname is provided as an + # argument. + if xname is None: + xname = self.model.exog_names + + if yname is None: + yname = self.model.endog_names + + # Create summary table instance + from statsmodels.iolib.summary import Summary + smry = Summary() + smry.add_table_2cols(self, gleft=top_left, gright=top_right, + yname=yname, xname=xname, + title=title) + smry.add_table_params(self, yname=yname, xname=xname, + alpha=alpha, use_t=False) + smry.add_table_2cols(self, gleft=diagn_left, + gright=diagn_right, yname=yname, + xname=xname, title="") + + return smry + + def get_margeff(self, at='overall', method='dydx', atexog=None, + dummy=False, count=False): + """Get marginal effects of the fitted model. + + Parameters + ---------- + at : str, optional + Options are: + + - 'overall', The average of the marginal effects at each + observation. + - 'mean', The marginal effects at the mean of each regressor. + - 'median', The marginal effects at the median of each regressor. + - 'zero', The marginal effects at zero for each regressor. + - 'all', The marginal effects at each observation. If `at` is 'all' + only margeff will be available. + + Note that if `exog` is specified, then marginal effects for all + variables not specified by `exog` are calculated using the `at` + option. + method : str, optional + Options are: + + - 'dydx' - dy/dx - No transformation is made and marginal effects + are returned. This is the default. + - 'eyex' - estimate elasticities of variables in `exog` -- + d(lny)/d(lnx) + - 'dyex' - estimate semi-elasticity -- dy/d(lnx) + - 'eydx' - estimate semi-elasticity -- d(lny)/dx + + Note that tranformations are done after each observation is + calculated. Semi-elasticities for binary variables are computed + using the midpoint method. 'dyex' and 'eyex' do not make sense + for discrete variables. + atexog : array_like, optional + Optionally, you can provide the exogenous variables over which to + get the marginal effects. This should be a dictionary with the key + as the zero-indexed column number and the value of the dictionary. + Default is None for all independent variables less the constant. + dummy : bool, optional + If False, treats binary variables (if present) as continuous. This + is the default. Else if True, treats binary variables as + changing from 0 to 1. Note that any variable that is either 0 or 1 + is treated as binary. Each binary variable is treated separately + for now. + count : bool, optional + If False, treats count variables (if present) as continuous. This + is the default. Else if True, the marginal effect is the + change in probabilities when each observation is increased by one. + + Returns + ------- + effects : ndarray + the marginal effect corresponding to the input options + + Notes + ----- + When using after Poisson, returns the expected number of events + per period, assuming that the model is loglinear. + """ + + if self.model.constraint is not None: + warnings.warn("marginal effects ignore constraints", + ValueWarning) + + return GEEMargins(self, (at, method, atexog, dummy, count)) + + def plot_isotropic_dependence(self, ax=None, xpoints=10, + min_n=50): + """ + Create a plot of the pairwise products of within-group + residuals against the corresponding time differences. This + plot can be used to assess the possible form of an isotropic + covariance structure. + + Parameters + ---------- + ax : AxesSubplot + An axes on which to draw the graph. If None, new + figure and axes objects are created + xpoints : scalar or array_like + If scalar, the number of points equally spaced points on + the time difference axis used to define bins for + calculating local means. If an array, the specific points + that define the bins. + min_n : int + The minimum sample size in a bin for the mean residual + product to be included on the plot. + """ + + from statsmodels.graphics import utils as gutils + + resid = self.model.cluster_list(self.resid) + time = self.model.cluster_list(self.model.time) + + # All within-group pairwise time distances (xdt) and the + # corresponding products of scaled residuals (xre). + xre, xdt = [], [] + for re, ti in zip(resid, time): + ix = np.tril_indices(re.shape[0], 0) + re = re[ix[0]] * re[ix[1]] / self.scale ** 2 + xre.append(re) + dists = np.sqrt(((ti[ix[0], :] - ti[ix[1], :]) ** 2).sum(1)) + xdt.append(dists) + + xre = np.concatenate(xre) + xdt = np.concatenate(xdt) + + if ax is None: + fig, ax = gutils.create_mpl_ax(ax) + else: + fig = ax.get_figure() + + # Convert to a correlation + ii = np.flatnonzero(xdt == 0) + v0 = np.mean(xre[ii]) + xre /= v0 + + # Use the simple average to smooth, since fancier smoothers + # that trim and downweight outliers give biased results (we + # need the actual mean of a skewed distribution). + if np.isscalar(xpoints): + xpoints = np.linspace(0, max(xdt), xpoints) + dg = np.digitize(xdt, xpoints) + dgu = np.unique(dg) + hist = np.asarray([np.sum(dg == k) for k in dgu]) + ii = np.flatnonzero(hist >= min_n) + dgu = dgu[ii] + dgy = np.asarray([np.mean(xre[dg == k]) for k in dgu]) + dgx = np.asarray([np.mean(xdt[dg == k]) for k in dgu]) + + ax.plot(dgx, dgy, '-', color='orange', lw=5) + ax.set_xlabel("Time difference") + ax.set_ylabel("Product of scaled residuals") + + return fig + + def sensitivity_params(self, dep_params_first, + dep_params_last, num_steps): + """ + Refits the GEE model using a sequence of values for the + dependence parameters. + + Parameters + ---------- + dep_params_first : array_like + The first dep_params in the sequence + dep_params_last : array_like + The last dep_params in the sequence + num_steps : int + The number of dep_params in the sequence + + Returns + ------- + results : array_like + The GEEResults objects resulting from the fits. + """ + + model = self.model + + import copy + cov_struct = copy.deepcopy(self.model.cov_struct) + + # We are fixing the dependence structure in each run. + update_dep = model.update_dep + model.update_dep = False + + dep_params = [] + results = [] + for x in np.linspace(0, 1, num_steps): + + dp = x * dep_params_last + (1 - x) * dep_params_first + dep_params.append(dp) + + model.cov_struct = copy.deepcopy(cov_struct) + model.cov_struct.dep_params = dp + rslt = model.fit(start_params=self.params, + ctol=self.ctol, + params_niter=self.params_niter, + first_dep_update=self.first_dep_update, + cov_type=self.cov_type) + results.append(rslt) + + model.update_dep = update_dep + + return results + + # FIXME: alias to be removed, temporary backwards compatibility + params_sensitivity = sensitivity_params + + +class GEEResultsWrapper(lm.RegressionResultsWrapper): + _attrs = { + 'centered_resid': 'rows', + } + _wrap_attrs = wrap.union_dicts(lm.RegressionResultsWrapper._wrap_attrs, + _attrs) +wrap.populate_wrapper(GEEResultsWrapper, GEEResults) # noqa:E305 + + +class OrdinalGEE(GEE): + + __doc__ = ( + " Ordinal Response Marginal Regression Model using GEE\n" + + _gee_init_doc % {'extra_params': base._missing_param_doc, + 'family_doc': _gee_ordinal_family_doc, + 'example': _gee_ordinal_example, + 'notes': _gee_nointercept}) + + def __init__(self, endog, exog, groups, time=None, family=None, + cov_struct=None, missing='none', offset=None, + dep_data=None, constraint=None, **kwargs): + + if family is None: + family = families.Binomial() + else: + if not isinstance(family, families.Binomial): + raise ValueError("ordinal GEE must use a Binomial family") + + if cov_struct is None: + cov_struct = cov_structs.OrdinalIndependence() + + endog, exog, groups, time, offset = self.setup_ordinal( + endog, exog, groups, time, offset) + + super().__init__(endog, exog, groups, time, + family, cov_struct, missing, + offset, dep_data, constraint) + + def setup_ordinal(self, endog, exog, groups, time, offset): + """ + Restructure ordinal data as binary indicators so that they can + be analyzed using Generalized Estimating Equations. + """ + + self.endog_orig = endog.copy() + self.exog_orig = exog.copy() + self.groups_orig = groups.copy() + if offset is not None: + self.offset_orig = offset.copy() + else: + self.offset_orig = None + offset = np.zeros(len(endog)) + if time is not None: + self.time_orig = time.copy() + else: + self.time_orig = None + time = np.zeros((len(endog), 1)) + + exog = np.asarray(exog) + endog = np.asarray(endog) + groups = np.asarray(groups) + time = np.asarray(time) + offset = np.asarray(offset) + + # The unique outcomes, except the greatest one. + self.endog_values = np.unique(endog) + endog_cuts = self.endog_values[0:-1] + ncut = len(endog_cuts) + + nrows = ncut * len(endog) + exog_out = np.zeros((nrows, exog.shape[1]), + dtype=np.float64) + endog_out = np.zeros(nrows, dtype=np.float64) + intercepts = np.zeros((nrows, ncut), dtype=np.float64) + groups_out = np.zeros(nrows, dtype=groups.dtype) + time_out = np.zeros((nrows, time.shape[1]), + dtype=np.float64) + offset_out = np.zeros(nrows, dtype=np.float64) + + jrow = 0 + zipper = zip(exog, endog, groups, time, offset) + for (exog_row, endog_value, group_value, time_value, + offset_value) in zipper: + + # Loop over thresholds for the indicators + for thresh_ix, thresh in enumerate(endog_cuts): + + exog_out[jrow, :] = exog_row + endog_out[jrow] = int(np.squeeze(endog_value > thresh)) + intercepts[jrow, thresh_ix] = 1 + groups_out[jrow] = group_value + time_out[jrow] = time_value + offset_out[jrow] = offset_value + jrow += 1 + + exog_out = np.concatenate((intercepts, exog_out), axis=1) + + # exog column names, including intercepts + xnames = ["I(y>%.1f)" % v for v in endog_cuts] + if type(self.exog_orig) is pd.DataFrame: + xnames.extend(self.exog_orig.columns) + else: + xnames.extend(["x%d" % k for k in range(1, exog.shape[1] + 1)]) + exog_out = pd.DataFrame(exog_out, columns=xnames) + + # Preserve the endog name if there is one + if type(self.endog_orig) is pd.Series: + endog_out = pd.Series(endog_out, name=self.endog_orig.name) + + return endog_out, exog_out, groups_out, time_out, offset_out + + def _starting_params(self): + exposure = getattr(self, "exposure", None) + model = GEE(self.endog, self.exog, self.groups, + time=self.time, family=families.Binomial(), + offset=self.offset, exposure=exposure) + result = model.fit() + return result.params + + @Appender(_gee_fit_doc) + def fit(self, maxiter=60, ctol=1e-6, start_params=None, + params_niter=1, first_dep_update=0, + cov_type='robust'): + + rslt = super().fit(maxiter, ctol, start_params, + params_niter, first_dep_update, + cov_type=cov_type) + + rslt = rslt._results # use unwrapped instance + res_kwds = {k: getattr(rslt, k) for k in rslt._props} + # Convert the GEEResults to an OrdinalGEEResults + ord_rslt = OrdinalGEEResults(self, rslt.params, + rslt.cov_params() / rslt.scale, + rslt.scale, + cov_type=cov_type, + attr_kwds=res_kwds) + # for k in rslt._props: + # setattr(ord_rslt, k, getattr(rslt, k)) + # TODO: document or delete + + return OrdinalGEEResultsWrapper(ord_rslt) + + +class OrdinalGEEResults(GEEResults): + + __doc__ = ( + "This class summarizes the fit of a marginal regression model" + "for an ordinal response using GEE.\n" + + _gee_results_doc) + + def plot_distribution(self, ax=None, exog_values=None): + """ + Plot the fitted probabilities of endog in an ordinal model, + for specified values of the predictors. + + Parameters + ---------- + ax : AxesSubplot + An axes on which to draw the graph. If None, new + figure and axes objects are created + exog_values : array_like + A list of dictionaries, with each dictionary mapping + variable names to values at which the variable is held + fixed. The values P(endog=y | exog) are plotted for all + possible values of y, at the given exog value. Variables + not included in a dictionary are held fixed at the mean + value. + + Example: + -------- + We have a model with covariates 'age' and 'sex', and wish to + plot the probabilities P(endog=y | exog) for males (sex=0) and + for females (sex=1), as separate paths on the plot. Since + 'age' is not included below in the map, it is held fixed at + its mean value. + + >>> ev = [{"sex": 1}, {"sex": 0}] + >>> rslt.distribution_plot(exog_values=ev) + """ + + from statsmodels.graphics import utils as gutils + + if ax is None: + fig, ax = gutils.create_mpl_ax(ax) + else: + fig = ax.get_figure() + + # If no covariate patterns are specified, create one with all + # variables set to their mean values. + if exog_values is None: + exog_values = [{}, ] + + exog_means = self.model.exog.mean(0) + ix_icept = [i for i, x in enumerate(self.model.exog_names) if + x.startswith("I(")] + + for ev in exog_values: + + for k in ev.keys(): + if k not in self.model.exog_names: + raise ValueError("%s is not a variable in the model" + % k) + + # Get the fitted probability for each level, at the given + # covariate values. + pr = [] + for j in ix_icept: + + xp = np.zeros_like(self.params) + xp[j] = 1. + for i, vn in enumerate(self.model.exog_names): + if i in ix_icept: + continue + # User-specified value + if vn in ev: + xp[i] = ev[vn] + # Mean value + else: + xp[i] = exog_means[i] + + p = 1 / (1 + np.exp(-np.dot(xp, self.params))) + pr.append(p) + + pr.insert(0, 1) + pr.append(0) + pr = np.asarray(pr) + prd = -np.diff(pr) + + ax.plot(self.model.endog_values, prd, 'o-') + + ax.set_xlabel("Response value") + ax.set_ylabel("Probability") + ax.set_ylim(0, 1) + + return fig + + +def _score_test_submodel(par, sub): + """ + Return transformation matrices for design matrices. + + Parameters + ---------- + par : instance + The parent model + sub : instance + The sub-model + + Returns + ------- + qm : array_like + Matrix mapping the design matrix of the parent to the design matrix + for the sub-model. + qc : array_like + Matrix mapping the design matrix of the parent to the orthogonal + complement of the columnspace of the submodel in the columnspace + of the parent. + + Notes + ----- + Returns None, None if the provided submodel is not actually a submodel. + """ + + x1 = par.exog + x2 = sub.exog + + u, s, vt = np.linalg.svd(x1, 0) + v = vt.T + + # Get the orthogonal complement of col(x2) in col(x1). + a, _ = np.linalg.qr(x2) + a = u - np.dot(a, np.dot(a.T, u)) + x2c, sb, _ = np.linalg.svd(a, 0) + x2c = x2c[:, sb > 1e-12] + + # x1 * qm = x2 + ii = np.flatnonzero(np.abs(s) > 1e-12) + qm = np.dot(v[:, ii], np.dot(u[:, ii].T, x2) / s[ii, None]) + + e = np.max(np.abs(x2 - np.dot(x1, qm))) + if e > 1e-8: + return None, None + + # x1 * qc = x2c + qc = np.dot(v[:, ii], np.dot(u[:, ii].T, x2c) / s[ii, None]) + + return qm, qc + + +class OrdinalGEEResultsWrapper(GEEResultsWrapper): + pass +wrap.populate_wrapper(OrdinalGEEResultsWrapper, OrdinalGEEResults) # noqa:E305 + + +class NominalGEE(GEE): + + __doc__ = ( + " Nominal Response Marginal Regression Model using GEE.\n" + + _gee_init_doc % {'extra_params': base._missing_param_doc, + 'family_doc': _gee_nominal_family_doc, + 'example': _gee_nominal_example, + 'notes': _gee_nointercept}) + + def __init__(self, endog, exog, groups, time=None, family=None, + cov_struct=None, missing='none', offset=None, + dep_data=None, constraint=None, **kwargs): + + endog, exog, groups, time, offset = self.setup_nominal( + endog, exog, groups, time, offset) + + if family is None: + family = _Multinomial(self.ncut + 1) + + if cov_struct is None: + cov_struct = cov_structs.NominalIndependence() + + super().__init__( + endog, exog, groups, time, family, cov_struct, missing, + offset, dep_data, constraint) + + def _starting_params(self): + exposure = getattr(self, "exposure", None) + model = GEE(self.endog, self.exog, self.groups, + time=self.time, family=families.Binomial(), + offset=self.offset, exposure=exposure) + result = model.fit() + return result.params + + def setup_nominal(self, endog, exog, groups, time, offset): + """ + Restructure nominal data as binary indicators so that they can + be analyzed using Generalized Estimating Equations. + """ + + self.endog_orig = endog.copy() + self.exog_orig = exog.copy() + self.groups_orig = groups.copy() + if offset is not None: + self.offset_orig = offset.copy() + else: + self.offset_orig = None + offset = np.zeros(len(endog)) + if time is not None: + self.time_orig = time.copy() + else: + self.time_orig = None + time = np.zeros((len(endog), 1)) + + exog = np.asarray(exog) + endog = np.asarray(endog) + groups = np.asarray(groups) + time = np.asarray(time) + offset = np.asarray(offset) + + # The unique outcomes, except the greatest one. + self.endog_values = np.unique(endog) + endog_cuts = self.endog_values[0:-1] + ncut = len(endog_cuts) + self.ncut = ncut + + nrows = len(endog_cuts) * exog.shape[0] + ncols = len(endog_cuts) * exog.shape[1] + exog_out = np.zeros((nrows, ncols), dtype=np.float64) + endog_out = np.zeros(nrows, dtype=np.float64) + groups_out = np.zeros(nrows, dtype=np.float64) + time_out = np.zeros((nrows, time.shape[1]), + dtype=np.float64) + offset_out = np.zeros(nrows, dtype=np.float64) + + jrow = 0 + zipper = zip(exog, endog, groups, time, offset) + for (exog_row, endog_value, group_value, time_value, + offset_value) in zipper: + + # Loop over thresholds for the indicators + for thresh_ix, thresh in enumerate(endog_cuts): + + u = np.zeros(len(endog_cuts), dtype=np.float64) + u[thresh_ix] = 1 + exog_out[jrow, :] = np.kron(u, exog_row) + endog_out[jrow] = int(np.squeeze(endog_value == thresh)) + groups_out[jrow] = group_value + time_out[jrow] = time_value + offset_out[jrow] = offset_value + jrow += 1 + + # exog names + if isinstance(self.exog_orig, pd.DataFrame): + xnames_in = self.exog_orig.columns + else: + xnames_in = ["x%d" % k for k in range(1, exog.shape[1] + 1)] + xnames = [] + for tr in endog_cuts: + xnames.extend([f"{v}[{tr:.1f}]" for v in xnames_in]) + exog_out = pd.DataFrame(exog_out, columns=xnames) + exog_out = pd.DataFrame(exog_out, columns=xnames) + + # Preserve endog name if there is one + if isinstance(self.endog_orig, pd.Series): + endog_out = pd.Series(endog_out, name=self.endog_orig.name) + + return endog_out, exog_out, groups_out, time_out, offset_out + + def mean_deriv(self, exog, lin_pred): + """ + Derivative of the expected endog with respect to the parameters. + + Parameters + ---------- + exog : array_like + The exogeneous data at which the derivative is computed, + number of rows must be a multiple of `ncut`. + lin_pred : array_like + The values of the linear predictor, length must be multiple + of `ncut`. + + Returns + ------- + The derivative of the expected endog with respect to the + parameters. + """ + + expval = np.exp(lin_pred) + + # Reshape so that each row contains all the indicators + # corresponding to one multinomial observation. + expval_m = np.reshape(expval, (len(expval) // self.ncut, + self.ncut)) + + # The normalizing constant for the multinomial probabilities. + denom = 1 + expval_m.sum(1) + denom = np.kron(denom, np.ones(self.ncut, dtype=np.float64)) + + # The multinomial probabilities + mprob = expval / denom + + # First term of the derivative: denom * expval' / denom^2 = + # expval' / denom. + dmat = mprob[:, None] * exog + + # Second term of the derivative: -expval * denom' / denom^2 + ddenom = expval[:, None] * exog + dmat -= mprob[:, None] * ddenom / denom[:, None] + + return dmat + + def mean_deriv_exog(self, exog, params, offset_exposure=None): + """ + Derivative of the expected endog with respect to exog for the + multinomial model, used in analyzing marginal effects. + + Parameters + ---------- + exog : array_like + The exogeneous data at which the derivative is computed, + number of rows must be a multiple of `ncut`. + lpr : array_like + The linear predictor values, length must be multiple of + `ncut`. + + Returns + ------- + The value of the derivative of the expected endog with respect + to exog. + + Notes + ----- + offset_exposure must be set at None for the multinomial family. + """ + + if offset_exposure is not None: + warnings.warn("Offset/exposure ignored for the multinomial family", + ValueWarning) + + lpr = np.dot(exog, params) + expval = np.exp(lpr) + + expval_m = np.reshape(expval, (len(expval) // self.ncut, + self.ncut)) + + denom = 1 + expval_m.sum(1) + denom = np.kron(denom, np.ones(self.ncut, dtype=np.float64)) + + bmat0 = np.outer(np.ones(exog.shape[0]), params) + + # Masking matrix + qmat = [] + for j in range(self.ncut): + ee = np.zeros(self.ncut, dtype=np.float64) + ee[j] = 1 + qmat.append(np.kron(ee, np.ones(len(params) // self.ncut))) + qmat = np.array(qmat) + qmat = np.kron(np.ones((exog.shape[0] // self.ncut, 1)), qmat) + bmat = bmat0 * qmat + + dmat = expval[:, None] * bmat / denom[:, None] + + expval_mb = np.kron(expval_m, np.ones((self.ncut, 1))) + expval_mb = np.kron(expval_mb, np.ones((1, self.ncut))) + + dmat -= expval[:, None] * (bmat * expval_mb) / denom[:, None] ** 2 + + return dmat + + @Appender(_gee_fit_doc) + def fit(self, maxiter=60, ctol=1e-6, start_params=None, + params_niter=1, first_dep_update=0, + cov_type='robust'): + + rslt = super().fit(maxiter, ctol, start_params, + params_niter, first_dep_update, + cov_type=cov_type) + if rslt is None: + warnings.warn("GEE updates did not converge", + ConvergenceWarning) + return None + + rslt = rslt._results # use unwrapped instance + res_kwds = {k: getattr(rslt, k) for k in rslt._props} + # Convert the GEEResults to a NominalGEEResults + nom_rslt = NominalGEEResults(self, rslt.params, + rslt.cov_params() / rslt.scale, + rslt.scale, + cov_type=cov_type, + attr_kwds=res_kwds) + # TODO: document or delete + # for k in rslt._props: + # setattr(nom_rslt, k, getattr(rslt, k)) + + return NominalGEEResultsWrapper(nom_rslt) + + +class NominalGEEResults(GEEResults): + + __doc__ = ( + "This class summarizes the fit of a marginal regression model" + "for a nominal response using GEE.\n" + + _gee_results_doc) + + def plot_distribution(self, ax=None, exog_values=None): + """ + Plot the fitted probabilities of endog in an nominal model, + for specified values of the predictors. + + Parameters + ---------- + ax : AxesSubplot + An axes on which to draw the graph. If None, new + figure and axes objects are created + exog_values : array_like + A list of dictionaries, with each dictionary mapping + variable names to values at which the variable is held + fixed. The values P(endog=y | exog) are plotted for all + possible values of y, at the given exog value. Variables + not included in a dictionary are held fixed at the mean + value. + + Example: + -------- + We have a model with covariates 'age' and 'sex', and wish to + plot the probabilities P(endog=y | exog) for males (sex=0) and + for females (sex=1), as separate paths on the plot. Since + 'age' is not included below in the map, it is held fixed at + its mean value. + + >>> ex = [{"sex": 1}, {"sex": 0}] + >>> rslt.distribution_plot(exog_values=ex) + """ + + from statsmodels.graphics import utils as gutils + + if ax is None: + fig, ax = gutils.create_mpl_ax(ax) + else: + fig = ax.get_figure() + + # If no covariate patterns are specified, create one with all + # variables set to their mean values. + if exog_values is None: + exog_values = [{}, ] + + link = self.model.family.link.inverse + ncut = self.model.family.ncut + + k = int(self.model.exog.shape[1] / ncut) + exog_means = self.model.exog.mean(0)[0:k] + exog_names = self.model.exog_names[0:k] + exog_names = [x.split("[")[0] for x in exog_names] + + params = np.reshape(self.params, + (ncut, len(self.params) // ncut)) + + for ev in exog_values: + + exog = exog_means.copy() + + for k in ev.keys(): + if k not in exog_names: + raise ValueError("%s is not a variable in the model" + % k) + + ii = exog_names.index(k) + exog[ii] = ev[k] + + lpr = np.dot(params, exog) + pr = link(lpr) + pr = np.r_[pr, 1 - pr.sum()] + + ax.plot(self.model.endog_values, pr, 'o-') + + ax.set_xlabel("Response value") + ax.set_ylabel("Probability") + ax.set_xticks(self.model.endog_values) + ax.set_xticklabels(self.model.endog_values) + ax.set_ylim(0, 1) + + return fig + + +class NominalGEEResultsWrapper(GEEResultsWrapper): + pass +wrap.populate_wrapper(NominalGEEResultsWrapper, NominalGEEResults) # noqa:E305 + + +class _MultinomialLogit(Link): + """ + The multinomial logit transform, only for use with GEE. + + Notes + ----- + The data are assumed coded as binary indicators, where each + observed multinomial value y is coded as I(y == S[0]), ..., I(y == + S[-1]), where S is the set of possible response labels, excluding + the largest one. Thererefore functions in this class should only + be called using vector argument whose length is a multiple of |S| + = ncut, which is an argument to be provided when initializing the + class. + + call and derivative use a private method _clean to trim p by 1e-10 + so that p is in (0, 1) + """ + + def __init__(self, ncut): + self.ncut = ncut + + def inverse(self, lpr): + """ + Inverse of the multinomial logit transform, which gives the + expected values of the data as a function of the linear + predictors. + + Parameters + ---------- + lpr : array_like (length must be divisible by `ncut`) + The linear predictors + + Returns + ------- + prob : ndarray + Probabilities, or expected values + """ + + expval = np.exp(lpr) + + denom = 1 + np.reshape(expval, (len(expval) // self.ncut, + self.ncut)).sum(1) + denom = np.kron(denom, np.ones(self.ncut, dtype=np.float64)) + + prob = expval / denom + + return prob + + +class _Multinomial(families.Family): + """ + Pseudo-link function for fitting nominal multinomial models with + GEE. Not for use outside the GEE class. + """ + + links = [_MultinomialLogit, ] + variance = varfuncs.binary + safe_links = [_MultinomialLogit, ] + + def __init__(self, nlevels, check_link=True): + """ + Parameters + ---------- + nlevels : int + The number of distinct categories for the multinomial + distribution. + """ + self._check_link = check_link + self.initialize(nlevels) + + def initialize(self, nlevels): + self.ncut = nlevels - 1 + self.link = _MultinomialLogit(self.ncut) + + +class GEEMargins: + """ + Estimated marginal effects for a regression model fit with GEE. + + Parameters + ---------- + results : GEEResults instance + The results instance of a fitted discrete choice model + args : tuple + Args are passed to `get_margeff`. This is the same as + results.get_margeff. See there for more information. + kwargs : dict + Keyword args are passed to `get_margeff`. This is the same as + results.get_margeff. See there for more information. + """ + + def __init__(self, results, args, kwargs={}): + self._cache = {} + self.results = results + self.get_margeff(*args, **kwargs) + + def _reset(self): + self._cache = {} + + @cache_readonly + def tvalues(self): + _check_at_is_all(self.margeff_options) + return self.margeff / self.margeff_se + + def summary_frame(self, alpha=.05): + """ + Returns a DataFrame summarizing the marginal effects. + + Parameters + ---------- + alpha : float + Number between 0 and 1. The confidence intervals have the + probability 1-alpha. + + Returns + ------- + frame : DataFrames + A DataFrame summarizing the marginal effects. + """ + _check_at_is_all(self.margeff_options) + from pandas import DataFrame + names = [_transform_names[self.margeff_options['method']], + 'Std. Err.', 'z', 'Pr(>|z|)', + 'Conf. Int. Low', 'Cont. Int. Hi.'] + ind = self.results.model.exog.var(0) != 0 # True if not a constant + exog_names = self.results.model.exog_names + var_names = [name for i, name in enumerate(exog_names) if ind[i]] + table = np.column_stack((self.margeff, self.margeff_se, self.tvalues, + self.pvalues, self.conf_int(alpha))) + return DataFrame(table, columns=names, index=var_names) + + @cache_readonly + def pvalues(self): + _check_at_is_all(self.margeff_options) + return stats.norm.sf(np.abs(self.tvalues)) * 2 + + def conf_int(self, alpha=.05): + """ + Returns the confidence intervals of the marginal effects + + Parameters + ---------- + alpha : float + Number between 0 and 1. The confidence intervals have the + probability 1-alpha. + + Returns + ------- + conf_int : ndarray + An array with lower, upper confidence intervals for the marginal + effects. + """ + _check_at_is_all(self.margeff_options) + me_se = self.margeff_se + q = stats.norm.ppf(1 - alpha / 2) + lower = self.margeff - q * me_se + upper = self.margeff + q * me_se + return np.asarray(lzip(lower, upper)) + + def summary(self, alpha=.05): + """ + Returns a summary table for marginal effects + + Parameters + ---------- + alpha : float + Number between 0 and 1. The confidence intervals have the + probability 1-alpha. + + Returns + ------- + Summary : SummaryTable + A SummaryTable instance + """ + _check_at_is_all(self.margeff_options) + results = self.results + model = results.model + title = model.__class__.__name__ + " Marginal Effects" + method = self.margeff_options['method'] + top_left = [('Dep. Variable:', [model.endog_names]), + ('Method:', [method]), + ('At:', [self.margeff_options['at']]), ] + + from statsmodels.iolib.summary import (Summary, summary_params, + table_extend) + exog_names = model.exog_names[:] # copy + smry = Summary() + + const_idx = model.data.const_idx + if const_idx is not None: + exog_names.pop(const_idx) + + J = int(getattr(model, "J", 1)) + if J > 1: + yname, yname_list = results._get_endog_name(model.endog_names, + None, all=True) + else: + yname = model.endog_names + yname_list = [yname] + + smry.add_table_2cols(self, gleft=top_left, gright=[], + yname=yname, xname=exog_names, title=title) + + # NOTE: add_table_params is not general enough yet for margeff + # could use a refactor with getattr instead of hard-coded params + # tvalues etc. + table = [] + conf_int = self.conf_int(alpha) + margeff = self.margeff + margeff_se = self.margeff_se + tvalues = self.tvalues + pvalues = self.pvalues + if J > 1: + for eq in range(J): + restup = (results, margeff[:, eq], margeff_se[:, eq], + tvalues[:, eq], pvalues[:, eq], conf_int[:, :, eq]) + tble = summary_params(restup, yname=yname_list[eq], + xname=exog_names, alpha=alpha, + use_t=False, + skip_header=True) + tble.title = yname_list[eq] + # overwrite coef with method name + header = ['', _transform_names[method], 'std err', 'z', + 'P>|z|', + '[%3.1f%% Conf. Int.]' % (100 - alpha * 100)] + tble.insert_header_row(0, header) + # from IPython.core.debugger import Pdb; Pdb().set_trace() + table.append(tble) + + table = table_extend(table, keep_headers=True) + else: + restup = (results, margeff, margeff_se, tvalues, pvalues, conf_int) + table = summary_params(restup, yname=yname, xname=exog_names, + alpha=alpha, use_t=False, skip_header=True) + header = ['', _transform_names[method], 'std err', 'z', + 'P>|z|', '[%3.1f%% Conf. Int.]' % (100 - alpha * 100)] + table.insert_header_row(0, header) + + smry.tables.append(table) + return smry + + def get_margeff(self, at='overall', method='dydx', atexog=None, + dummy=False, count=False): + + self._reset() # always reset the cache when this is called + # TODO: if at is not all or overall, we can also put atexog values + # in summary table head + method = method.lower() + at = at.lower() + _check_margeff_args(at, method) + self.margeff_options = dict(method=method, at=at) + results = self.results + model = results.model + params = results.params + exog = model.exog.copy() # copy because values are changed + effects_idx = exog.var(0) != 0 + const_idx = model.data.const_idx + + if dummy: + _check_discrete_args(at, method) + dummy_idx, dummy = _get_dummy_index(exog, const_idx) + else: + dummy_idx = None + + if count: + _check_discrete_args(at, method) + count_idx, count = _get_count_index(exog, const_idx) + else: + count_idx = None + + # get the exogenous variables + exog = _get_margeff_exog(exog, at, atexog, effects_idx) + + # get base marginal effects, handled by sub-classes + effects = model._derivative_exog(params, exog, method, + dummy_idx, count_idx) + effects = _effects_at(effects, at) + + if at == 'all': + self.margeff = effects[:, effects_idx] + else: + # Set standard error of the marginal effects by Delta method. + margeff_cov, margeff_se = margeff_cov_with_se( + model, params, exog, results.cov_params(), at, + model._derivative_exog, dummy_idx, count_idx, + method, 1) + + # do not care about at constant + self.margeff_cov = margeff_cov[effects_idx][:, effects_idx] + self.margeff_se = margeff_se[effects_idx] + self.margeff = effects[effects_idx] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/genmod/generalized_linear_model.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/genmod/generalized_linear_model.py new file mode 100644 index 0000000000000000000000000000000000000000..4ac38283cc5fa9098b011718e5720a396bb923fb --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/genmod/generalized_linear_model.py @@ -0,0 +1,2604 @@ +""" +Generalized linear models currently supports estimation using the one-parameter +exponential families + +References +---------- +Gill, Jeff. 2000. Generalized Linear Models: A Unified Approach. + SAGE QASS Series. + +Green, PJ. 1984. "Iteratively reweighted least squares for maximum + likelihood estimation, and some robust and resistant alternatives." + Journal of the Royal Statistical Society, Series B, 46, 149-192. + +Hardin, J.W. and Hilbe, J.M. 2007. "Generalized Linear Models and + Extensions." 2nd ed. Stata Press, College Station, TX. + +McCullagh, P. and Nelder, J.A. 1989. "Generalized Linear Models." 2nd ed. + Chapman & Hall, Boca Rotan. +""" +from statsmodels.compat.pandas import Appender + +import warnings + +import numpy as np +from numpy.linalg import LinAlgError + +import statsmodels.base.model as base +import statsmodels.base.wrapper as wrap + +from statsmodels.base import _prediction_inference as pred +from statsmodels.base._prediction_inference import PredictionResultsMean +import statsmodels.base._parameter_inference as pinfer + +from statsmodels.graphics._regressionplots_doc import ( + _plot_added_variable_doc, + _plot_ceres_residuals_doc, + _plot_partial_residuals_doc, +) +import statsmodels.regression._tools as reg_tools +import statsmodels.regression.linear_model as lm +from statsmodels.tools.decorators import ( + cache_readonly, + cached_data, + cached_value, +) +from statsmodels.tools.docstring import Docstring +from statsmodels.tools.sm_exceptions import ( + DomainWarning, + HessianInversionWarning, + PerfectSeparationWarning, +) +from statsmodels.tools.validation import float_like + +# need import in module instead of lazily to copy `__doc__` +from . import families + + +__all__ = ['GLM', 'PredictionResultsMean'] + + +def _check_convergence(criterion, iteration, atol, rtol): + return np.allclose(criterion[iteration], criterion[iteration + 1], + atol=atol, rtol=rtol) + + +# Remove after 0.13 when bic changes to bic llf +class _ModuleVariable: + _value = None + + @property + def use_bic_llf(self): + return self._value + + def set_use_bic_llf(self, val): + if val not in (True, False, None): + raise ValueError("Must be True, False or None") + self._value = bool(val) if val is not None else val + + +_use_bic_helper = _ModuleVariable() +SET_USE_BIC_LLF = _use_bic_helper.set_use_bic_llf + + +class GLM(base.LikelihoodModel): + __doc__ = """ + Generalized Linear Models + + GLM inherits from statsmodels.base.model.LikelihoodModel + + Parameters + ---------- + endog : array_like + 1d array of endogenous response variable. This array can be 1d or 2d. + Binomial family models accept a 2d array with two columns. If + supplied, each observation is expected to be [success, failure]. + exog : array_like + A nobs x k array where `nobs` is the number of observations and `k` + is the number of regressors. An intercept is not included by default + and should be added by the user (models specified using a formula + include an intercept by default). See `statsmodels.tools.add_constant`. + family : family class instance + The default is Gaussian. To specify the binomial distribution + family = sm.family.Binomial() + Each family can take a link instance as an argument. See + statsmodels.family.family for more information. + offset : array_like or None + An offset to be included in the model. If provided, must be + an array whose length is the number of rows in exog. + exposure : array_like or None + Log(exposure) will be added to the linear prediction in the model. + Exposure is only valid if the log link is used. If provided, it must be + an array with the same length as endog. + freq_weights : array_like + 1d array of frequency weights. The default is None. If None is selected + or a blank value, then the algorithm will replace with an array of 1's + with length equal to the endog. + WARNING: Using weights is not verified yet for all possible options + and results, see Notes. + var_weights : array_like + 1d array of variance (analytic) weights. The default is None. If None + is selected or a blank value, then the algorithm will replace with an + array of 1's with length equal to the endog. + WARNING: Using weights is not verified yet for all possible options + and results, see Notes. + {extra_params} + + Attributes + ---------- + df_model : float + Model degrees of freedom is equal to p - 1, where p is the number + of regressors. Note that the intercept is not reported as a + degree of freedom. + df_resid : float + Residual degrees of freedom is equal to the number of observation n + minus the number of regressors p. + endog : ndarray + See Notes. Note that `endog` is a reference to the data so that if + data is already an array and it is changed, then `endog` changes + as well. + exposure : array_like + Include ln(exposure) in model with coefficient constrained to 1. Can + only be used if the link is the logarithm function. + exog : ndarray + See Notes. Note that `exog` is a reference to the data so that if + data is already an array and it is changed, then `exog` changes + as well. + freq_weights : ndarray + See Notes. Note that `freq_weights` is a reference to the data so that + if data is already an array and it is changed, then `freq_weights` + changes as well. + var_weights : ndarray + See Notes. Note that `var_weights` is a reference to the data so that + if data is already an array and it is changed, then `var_weights` + changes as well. + iteration : int + The number of iterations that fit has run. Initialized at 0. + family : family class instance + The distribution family of the model. Can be any family in + statsmodels.families. Default is Gaussian. + mu : ndarray + The mean response of the transformed variable. `mu` is the value of + the inverse of the link function at lin_pred, where lin_pred is the + linear predicted value of the WLS fit of the transformed variable. + `mu` is only available after fit is called. See + statsmodels.families.family.fitted of the distribution family for more + information. + n_trials : ndarray + See Notes. Note that `n_trials` is a reference to the data so that if + data is already an array and it is changed, then `n_trials` changes + as well. `n_trials` is the number of binomial trials and only available + with that distribution. See statsmodels.families.Binomial for more + information. + normalized_cov_params : ndarray + The p x p normalized covariance of the design / exogenous data. + This is approximately equal to (X.T X)^(-1) + offset : array_like + Include offset in model with coefficient constrained to 1. + scale : float + The estimate of the scale / dispersion of the model fit. Only + available after fit is called. See GLM.fit and GLM.estimate_scale + for more information. + scaletype : str + The scaling used for fitting the model. This is only available after + fit is called. The default is None. See GLM.fit for more information. + weights : ndarray + The value of the weights after the last iteration of fit. Only + available after fit is called. See statsmodels.families.family for + the specific distribution weighting functions. + + Examples + -------- + >>> import statsmodels.api as sm + >>> data = sm.datasets.scotland.load() + >>> data.exog = sm.add_constant(data.exog) + + Instantiate a gamma family model with the default link function. + + >>> gamma_model = sm.GLM(data.endog, data.exog, + ... family=sm.families.Gamma()) + + >>> gamma_results = gamma_model.fit() + >>> gamma_results.params + array([-0.01776527, 0.00004962, 0.00203442, -0.00007181, 0.00011185, + -0.00000015, -0.00051868, -0.00000243]) + >>> gamma_results.scale + 0.0035842831734919055 + >>> gamma_results.deviance + 0.087388516416999198 + >>> gamma_results.pearson_chi2 + 0.086022796163805704 + >>> gamma_results.llf + -83.017202161073527 + + See Also + -------- + statsmodels.genmod.families.family.Family + :ref:`families` + :ref:`links` + + Notes + ----- + Note: PerfectSeparationError exception has been converted to a + PerfectSeparationWarning and perfect separation or perfect prediction will + not raise an exception by default. (changed in version 0.14) + + Only the following combinations make sense for family and link: + + ============= ===== === ===== ====== ======= === ==== ====== ====== ==== + Family ident log logit probit cloglog pow opow nbinom loglog logc + ============= ===== === ===== ====== ======= === ==== ====== ====== ==== + Gaussian x x x x x x x x x + inv Gaussian x x x + binomial x x x x x x x x x + Poisson x x x + neg binomial x x x x + gamma x x x + Tweedie x x x + ============= ===== === ===== ====== ======= === ==== ====== ====== ==== + + Not all of these link functions are currently available. + + Endog and exog are references so that if the data they refer to are already + arrays and these arrays are changed, endog and exog will change. + + statsmodels supports two separate definitions of weights: frequency weights + and variance weights. + + Frequency weights produce the same results as repeating observations by the + frequencies (if those are integers). Frequency weights will keep the number + of observations consistent, but the degrees of freedom will change to + reflect the new weights. + + Variance weights (referred to in other packages as analytic weights) are + used when ``endog`` represents an an average or mean. This relies on the + assumption that that the inverse variance scales proportionally to the + weight--an observation that is deemed more credible should have less + variance and therefore have more weight. For the ``Poisson`` family--which + assumes that occurrences scale proportionally with time--a natural practice + would be to use the amount of time as the variance weight and set ``endog`` + to be a rate (occurrences per period of time). Similarly, using a + compound Poisson family, namely ``Tweedie``, makes a similar assumption + about the rate (or frequency) of occurrences having variance proportional to + time. + + Both frequency and variance weights are verified for all basic results with + nonrobust or heteroscedasticity robust ``cov_type``. Other robust + covariance types have not yet been verified, and at least the small sample + correction is currently not based on the correct total frequency count. + + Currently, all residuals are not weighted by frequency, although they may + incorporate ``n_trials`` for ``Binomial`` and ``var_weights`` + + +---------------+----------------------------------+ + | Residual Type | Applicable weights | + +===============+==================================+ + | Anscombe | ``var_weights`` | + +---------------+----------------------------------+ + | Deviance | ``var_weights`` | + +---------------+----------------------------------+ + | Pearson | ``var_weights`` and ``n_trials`` | + +---------------+----------------------------------+ + | Reponse | ``n_trials`` | + +---------------+----------------------------------+ + | Working | ``n_trials`` | + +---------------+----------------------------------+ + + WARNING: Loglikelihood and deviance are not valid in models where + scale is equal to 1 (i.e., ``Binomial``, ``NegativeBinomial``, and + ``Poisson``). If variance weights are specified, then results such as + ``loglike`` and ``deviance`` are based on a quasi-likelihood + interpretation. The loglikelihood is not correctly specified in this case, + and statistics based on it, such AIC or likelihood ratio tests, are not + appropriate. + """.format(extra_params=base._missing_param_doc) + # Maximum number of endogenous variables when using a formula + _formula_max_endog = 2 + + def __init__(self, endog, exog, family=None, offset=None, + exposure=None, freq_weights=None, var_weights=None, + missing='none', **kwargs): + + if type(self) is GLM: + self._check_kwargs(kwargs, ['n_trials']) + + if (family is not None) and not isinstance(family.link, + tuple(family.safe_links)): + + warnings.warn((f"The {type(family.link).__name__} link function " + "does not respect the domain of the " + f"{type(family).__name__} family."), + DomainWarning) + + if exposure is not None: + exposure = np.log(exposure) + if offset is not None: # this should probably be done upstream + offset = np.asarray(offset) + + if freq_weights is not None: + freq_weights = np.asarray(freq_weights) + if var_weights is not None: + var_weights = np.asarray(var_weights) + + self.freq_weights = freq_weights + self.var_weights = var_weights + + super().__init__(endog, exog, missing=missing, + offset=offset, exposure=exposure, + freq_weights=freq_weights, + var_weights=var_weights, **kwargs) + self._check_inputs(family, self.offset, self.exposure, self.endog, + self.freq_weights, self.var_weights) + if offset is None: + delattr(self, 'offset') + if exposure is None: + delattr(self, 'exposure') + + self.nobs = self.endog.shape[0] + + # things to remove_data + self._data_attr.extend(['weights', 'mu', 'freq_weights', + 'var_weights', 'iweights', '_offset_exposure', + 'n_trials']) + # register kwds for __init__, offset and exposure are added by super + self._init_keys.append('family') + + self._setup_binomial() + # internal usage for recreating a model + if 'n_trials' in kwargs: + self.n_trials = kwargs['n_trials'] + + # Construct a combined offset/exposure term. Note that + # exposure has already been logged if present. + offset_exposure = 0. + if hasattr(self, 'offset'): + offset_exposure = self.offset + if hasattr(self, 'exposure'): + offset_exposure = offset_exposure + self.exposure + self._offset_exposure = offset_exposure + + self.scaletype = None + + def initialize(self): + """ + Initialize a generalized linear model. + """ + self.df_model = np.linalg.matrix_rank(self.exog) - 1 + + if (self.freq_weights is not None) and \ + (self.freq_weights.shape[0] == self.endog.shape[0]): + self.wnobs = self.freq_weights.sum() + self.df_resid = self.wnobs - self.df_model - 1 + else: + self.wnobs = self.exog.shape[0] + self.df_resid = self.exog.shape[0] - self.df_model - 1 + + def _check_inputs(self, family, offset, exposure, endog, freq_weights, + var_weights): + + # Default family is Gaussian + if family is None: + family = families.Gaussian() + self.family = family + + if exposure is not None: + if not isinstance(self.family.link, families.links.Log): + raise ValueError("exposure can only be used with the log " + "link function") + elif exposure.shape[0] != endog.shape[0]: + raise ValueError("exposure is not the same length as endog") + + if offset is not None: + if offset.shape[0] != endog.shape[0]: + raise ValueError("offset is not the same length as endog") + + if freq_weights is not None: + if freq_weights.shape[0] != endog.shape[0]: + raise ValueError("freq weights not the same length as endog") + if len(freq_weights.shape) > 1: + raise ValueError("freq weights has too many dimensions") + + # internal flag to store whether freq_weights were not None + self._has_freq_weights = (self.freq_weights is not None) + if self.freq_weights is None: + self.freq_weights = np.ones(endog.shape[0]) + # TODO: check do we want to keep None as sentinel for freq_weights + + if np.shape(self.freq_weights) == () and self.freq_weights > 1: + self.freq_weights = (self.freq_weights * + np.ones(endog.shape[0])) + + if var_weights is not None: + if var_weights.shape[0] != endog.shape[0]: + raise ValueError("var weights not the same length as endog") + if len(var_weights.shape) > 1: + raise ValueError("var weights has too many dimensions") + + # internal flag to store whether var_weights were not None + self._has_var_weights = (var_weights is not None) + if var_weights is None: + self.var_weights = np.ones(endog.shape[0]) + # TODO: check do we want to keep None as sentinel for var_weights + self.iweights = np.asarray(self.freq_weights * self.var_weights) + + def _get_init_kwds(self): + # this is a temporary fixup because exposure has been transformed + # see #1609, copied from discrete_model.CountModel + kwds = super()._get_init_kwds() + if 'exposure' in kwds and kwds['exposure'] is not None: + kwds['exposure'] = np.exp(kwds['exposure']) + return kwds + + def loglike_mu(self, mu, scale=1.): + """ + Evaluate the log-likelihood for a generalized linear model. + """ + scale = float_like(scale, "scale") + return self.family.loglike(self.endog, mu, self.var_weights, + self.freq_weights, scale) + + def loglike(self, params, scale=None): + """ + Evaluate the log-likelihood for a generalized linear model. + """ + scale = float_like(scale, "scale", optional=True) + lin_pred = np.dot(self.exog, params) + self._offset_exposure + expval = self.family.link.inverse(lin_pred) + if scale is None: + scale = self.estimate_scale(expval) + llf = self.family.loglike(self.endog, expval, self.var_weights, + self.freq_weights, scale) + return llf + + def score_obs(self, params, scale=None): + """score first derivative of the loglikelihood for each observation. + + Parameters + ---------- + params : ndarray + Parameter at which score is evaluated. + scale : None or float + If scale is None, then the default scale will be calculated. + Default scale is defined by `self.scaletype` and set in fit. + If scale is not None, then it is used as a fixed scale. + + Returns + ------- + score_obs : ndarray, 2d + The first derivative of the loglikelihood function evaluated at + params for each observation. + """ + scale = float_like(scale, "scale", optional=True) + score_factor = self.score_factor(params, scale=scale) + return score_factor[:, None] * self.exog + + def score(self, params, scale=None): + """score, first derivative of the loglikelihood function + + Parameters + ---------- + params : ndarray + Parameter at which score is evaluated. + scale : None or float + If scale is None, then the default scale will be calculated. + Default scale is defined by `self.scaletype` and set in fit. + If scale is not None, then it is used as a fixed scale. + + Returns + ------- + score : ndarray_1d + The first derivative of the loglikelihood function calculated as + the sum of `score_obs` + """ + scale = float_like(scale, "scale", optional=True) + score_factor = self.score_factor(params, scale=scale) + return np.dot(score_factor, self.exog) + + def score_factor(self, params, scale=None): + """weights for score for each observation + + This can be considered as score residuals. + + Parameters + ---------- + params : ndarray + parameter at which score is evaluated + scale : None or float + If scale is None, then the default scale will be calculated. + Default scale is defined by `self.scaletype` and set in fit. + If scale is not None, then it is used as a fixed scale. + + Returns + ------- + score_factor : ndarray_1d + A 1d weight vector used in the calculation of the score_obs. + The score_obs are obtained by `score_factor[:, None] * exog` + """ + scale = float_like(scale, "scale", optional=True) + mu = self.predict(params) + if scale is None: + scale = self.estimate_scale(mu) + + score_factor = (self.endog - mu) / self.family.link.deriv(mu) + score_factor /= self.family.variance(mu) + score_factor *= self.iweights * self.n_trials + + if not scale == 1: + score_factor /= scale + + return score_factor + + def hessian_factor(self, params, scale=None, observed=True): + """Weights for calculating Hessian + + Parameters + ---------- + params : ndarray + parameter at which Hessian is evaluated + scale : None or float + If scale is None, then the default scale will be calculated. + Default scale is defined by `self.scaletype` and set in fit. + If scale is not None, then it is used as a fixed scale. + observed : bool + If True, then the observed Hessian is returned. If false then the + expected information matrix is returned. + + Returns + ------- + hessian_factor : ndarray, 1d + A 1d weight vector used in the calculation of the Hessian. + The hessian is obtained by `(exog.T * hessian_factor).dot(exog)` + """ + + # calculating eim_factor + mu = self.predict(params) + if scale is None: + scale = self.estimate_scale(mu) + + eim_factor = 1 / (self.family.link.deriv(mu)**2 * + self.family.variance(mu)) + eim_factor *= self.iweights * self.n_trials + + if not observed: + if not scale == 1: + eim_factor /= scale + return eim_factor + + # calculating oim_factor, eim_factor is with scale=1 + + score_factor = self.score_factor(params, scale=1.) + if eim_factor.ndim > 1 or score_factor.ndim > 1: + raise RuntimeError('something wrong') + + tmp = self.family.variance(mu) * self.family.link.deriv2(mu) + tmp += self.family.variance.deriv(mu) * self.family.link.deriv(mu) + + tmp = score_factor * tmp + # correct for duplicatee iweights in oim_factor and score_factor + tmp /= self.iweights * self.n_trials + oim_factor = eim_factor * (1 + tmp) + + if tmp.ndim > 1: + raise RuntimeError('something wrong') + + if not scale == 1: + oim_factor /= scale + + return oim_factor + + def hessian(self, params, scale=None, observed=None): + """Hessian, second derivative of loglikelihood function + + Parameters + ---------- + params : ndarray + parameter at which Hessian is evaluated + scale : None or float + If scale is None, then the default scale will be calculated. + Default scale is defined by `self.scaletype` and set in fit. + If scale is not None, then it is used as a fixed scale. + observed : bool + If True, then the observed Hessian is returned (default). + If False, then the expected information matrix is returned. + + Returns + ------- + hessian : ndarray + Hessian, i.e. observed information, or expected information matrix. + """ + if observed is None: + if getattr(self, '_optim_hessian', None) == 'eim': + observed = False + else: + observed = True + scale = float_like(scale, "scale", optional=True) + tmp = getattr(self, '_tmp_like_exog', np.empty_like(self.exog, dtype=float)) + + factor = self.hessian_factor(params, scale=scale, observed=observed) + np.multiply(self.exog.T, factor, out=tmp.T) + return -tmp.T.dot(self.exog) + + def information(self, params, scale=None): + """ + Fisher information matrix. + """ + scale = float_like(scale, "scale", optional=True) + return self.hessian(params, scale=scale, observed=False) + + def _derivative_exog(self, params, exog=None, transform="dydx", + dummy_idx=None, count_idx=None, + offset=None, exposure=None): + """ + Derivative of mean, expected endog with respect to the parameters + """ + if exog is None: + exog = self.exog + if (offset is not None) or (exposure is not None): + raise NotImplementedError("offset and exposure not supported") + + lin_pred = self.predict(params, exog, which="linear", + offset=offset, exposure=exposure) + + k_extra = getattr(self, 'k_extra', 0) + params_exog = params if k_extra == 0 else params[:-k_extra] + + margeff = (self.family.link.inverse_deriv(lin_pred)[:, None] * + params_exog) + if 'ex' in transform: + margeff *= exog + if 'ey' in transform: + mean = self.family.link.inverse(lin_pred) + margeff /= mean[:,None] + + return self._derivative_exog_helper(margeff, params, exog, + dummy_idx, count_idx, transform) + + def _derivative_exog_helper(self, margeff, params, exog, dummy_idx, + count_idx, transform): + """ + Helper for _derivative_exog to wrap results appropriately + """ + from statsmodels.discrete.discrete_margins import ( + _get_count_effects, + _get_dummy_effects, + ) + + if count_idx is not None: + margeff = _get_count_effects(margeff, exog, count_idx, transform, + self, params) + if dummy_idx is not None: + margeff = _get_dummy_effects(margeff, exog, dummy_idx, transform, + self, params) + + return margeff + + def _derivative_predict(self, params, exog=None, transform='dydx', + offset=None, exposure=None): + """ + Derivative of the expected endog with respect to the parameters. + + Parameters + ---------- + params : ndarray + parameter at which score is evaluated + exog : ndarray or None + Explanatory variables at which derivative are computed. + If None, then the estimation exog is used. + offset, exposure : None + Not yet implemented. + + Returns + ------- + The value of the derivative of the expected endog with respect + to the parameter vector. + """ + # core part is same as derivative_mean_params + # additionally handles exog and transform + if exog is None: + exog = self.exog + if (offset is not None) or (exposure is not None) or ( + getattr(self, 'offset', None) is not None): + raise NotImplementedError("offset and exposure not supported") + + lin_pred = self.predict(params, exog=exog, which="linear") + idl = self.family.link.inverse_deriv(lin_pred) + dmat = exog * idl[:, None] + if 'ey' in transform: + mean = self.family.link.inverse(lin_pred) + dmat /= mean[:, None] + + return dmat + + def _deriv_mean_dparams(self, params): + """ + Derivative of the expected endog with respect to the parameters. + + Parameters + ---------- + params : ndarray + parameter at which score is evaluated + + Returns + ------- + The value of the derivative of the expected endog with respect + to the parameter vector. + """ + lin_pred = self.predict(params, which="linear") + idl = self.family.link.inverse_deriv(lin_pred) + dmat = self.exog * idl[:, None] + return dmat + + def _deriv_score_obs_dendog(self, params, scale=None): + """derivative of score_obs w.r.t. endog + + Parameters + ---------- + params : ndarray + parameter at which score is evaluated + scale : None or float + If scale is None, then the default scale will be calculated. + Default scale is defined by `self.scaletype` and set in fit. + If scale is not None, then it is used as a fixed scale. + + Returns + ------- + derivative : ndarray_2d + The derivative of the score_obs with respect to endog. This + can is given by `score_factor0[:, None] * exog` where + `score_factor0` is the score_factor without the residual. + """ + scale = float_like(scale, "scale", optional=True) + mu = self.predict(params) + if scale is None: + scale = self.estimate_scale(mu) + + score_factor = 1 / self.family.link.deriv(mu) + score_factor /= self.family.variance(mu) + score_factor *= self.iweights * self.n_trials + + if not scale == 1: + score_factor /= scale + + return score_factor[:, None] * self.exog + + def score_test(self, params_constrained, k_constraints=None, + exog_extra=None, observed=True): + """score test for restrictions or for omitted variables + + The covariance matrix for the score is based on the Hessian, i.e. + observed information matrix or optionally on the expected information + matrix.. + + Parameters + ---------- + params_constrained : array_like + estimated parameter of the restricted model. This can be the + parameter estimate for the current when testing for omitted + variables. + k_constraints : int or None + Number of constraints that were used in the estimation of params + restricted relative to the number of exog in the model. + This must be provided if no exog_extra are given. If exog_extra is + not None, then k_constraints is assumed to be zero if it is None. + exog_extra : None or array_like + Explanatory variables that are jointly tested for inclusion in the + model, i.e. omitted variables. + observed : bool + If True, then the observed Hessian is used in calculating the + covariance matrix of the score. If false then the expected + information matrix is used. + + Returns + ------- + chi2_stat : float + chisquare statistic for the score test + p-value : float + P-value of the score test based on the chisquare distribution. + df : int + Degrees of freedom used in the p-value calculation. This is equal + to the number of constraints. + + Notes + ----- + not yet verified for case with scale not equal to 1. + """ + + if exog_extra is None: + if k_constraints is None: + raise ValueError('if exog_extra is None, then k_constraints' + 'needs to be given') + + score = self.score(params_constrained) + hessian = self.hessian(params_constrained, observed=observed) + + else: + # exog_extra = np.asarray(exog_extra) + if k_constraints is None: + k_constraints = 0 + + ex = np.column_stack((self.exog, exog_extra)) + k_constraints += ex.shape[1] - self.exog.shape[1] + + score_factor = self.score_factor(params_constrained) + score = (score_factor[:, None] * ex).sum(0) + hessian_factor = self.hessian_factor(params_constrained, + observed=observed) + hessian = -np.dot(ex.T * hessian_factor, ex) + + from scipy import stats + + # TODO check sign, why minus? + chi2stat = -score.dot(np.linalg.solve(hessian, score[:, None])) + pval = stats.chi2.sf(chi2stat, k_constraints) + # return a stats results instance instead? Contrast? + return chi2stat, pval, k_constraints + + def _update_history(self, tmp_result, mu, history): + """ + Helper method to update history during iterative fit. + """ + history['params'].append(tmp_result.params) + history['deviance'].append(self.family.deviance(self.endog, mu, + self.var_weights, + self.freq_weights, + self.scale)) + return history + + def estimate_scale(self, mu): + """ + Estimate the dispersion/scale. + + Type of scale can be chose in the fit method. + + Parameters + ---------- + mu : ndarray + mu is the mean response estimate + + Returns + ------- + Estimate of scale + + Notes + ----- + The default scale for Binomial, Poisson and Negative Binomial + families is 1. The default for the other families is Pearson's + Chi-Square estimate. + + See Also + -------- + statsmodels.genmod.generalized_linear_model.GLM.fit + """ + if not self.scaletype: + if isinstance(self.family, (families.Binomial, families.Poisson, + families.NegativeBinomial)): + return 1. + else: + return self._estimate_x2_scale(mu) + + if isinstance(self.scaletype, float): + return np.array(self.scaletype) + + if isinstance(self.scaletype, str): + if self.scaletype.lower() == 'x2': + return self._estimate_x2_scale(mu) + elif self.scaletype.lower() == 'dev': + return (self.family.deviance(self.endog, mu, self.var_weights, + self.freq_weights, 1.) / + (self.df_resid)) + else: + raise ValueError("Scale %s with type %s not understood" % + (self.scaletype, type(self.scaletype))) + else: + raise ValueError("Scale %s with type %s not understood" % + (self.scaletype, type(self.scaletype))) + + def _estimate_x2_scale(self, mu): + resid = np.power(self.endog - mu, 2) * self.iweights + return np.sum(resid / self.family.variance(mu)) / self.df_resid + + def estimate_tweedie_power(self, mu, method='brentq', low=1.01, high=5.): + """ + Tweedie specific function to estimate scale and the variance parameter. + The variance parameter is also referred to as p, xi, or shape. + + Parameters + ---------- + mu : array_like + Fitted mean response variable + method : str, defaults to 'brentq' + Scipy optimizer used to solve the Pearson equation. Only brentq + currently supported. + low : float, optional + Low end of the bracketing interval [a,b] to be used in the search + for the power. Defaults to 1.01. + high : float, optional + High end of the bracketing interval [a,b] to be used in the search + for the power. Defaults to 5. + + Returns + ------- + power : float + The estimated shape or power. + """ + if method == 'brentq': + from scipy.optimize import brentq + + def psi_p(power, mu): + scale = ((self.iweights * (self.endog - mu) ** 2 / + (mu ** power)).sum() / self.df_resid) + return (np.sum(self.iweights * ((self.endog - mu) ** 2 / + (scale * (mu ** power)) - 1) * + np.log(mu)) / self.freq_weights.sum()) + power = brentq(psi_p, low, high, args=(mu)) + else: + raise NotImplementedError('Only brentq can currently be used') + return power + + def predict(self, params, exog=None, exposure=None, offset=None, + which="mean", linear=None): + """ + Return predicted values for a design matrix + + Parameters + ---------- + params : array_like + Parameters / coefficients of a GLM. + exog : array_like, optional + Design / exogenous data. Is exog is None, model exog is used. + exposure : array_like, optional + Exposure time values, only can be used with the log link + function. See notes for details. + offset : array_like, optional + Offset values. See notes for details. + which : 'mean', 'linear', 'var'(optional) + Statitistic to predict. Default is 'mean'. + + - 'mean' returns the conditional expectation of endog E(y | x), + i.e. inverse of the model's link function of linear predictor. + - 'linear' returns the linear predictor of the mean function. + - 'var_unscaled' variance of endog implied by the likelihood model. + This does not include scale or var_weights. + + linear : bool + The ``linear` keyword is deprecated and will be removed, + use ``which`` keyword instead. + If True, returns the linear predicted values. If False or None, + then the statistic specified by ``which`` will be returned. + + + Returns + ------- + An array of fitted values + + Notes + ----- + Any `exposure` and `offset` provided here take precedence over + the `exposure` and `offset` used in the model fit. If `exog` + is passed as an argument here, then any `exposure` and + `offset` values in the fit will be ignored. + + Exposure values must be strictly positive. + """ + if linear is not None: + msg = 'linear keyword is deprecated, use which="linear"' + warnings.warn(msg, FutureWarning) + if linear is True: + which = "linear" + + # Use fit offset if appropriate + if offset is None and exog is None and hasattr(self, 'offset'): + offset = self.offset + elif offset is None: + offset = 0. + + if exposure is not None and not isinstance(self.family.link, + families.links.Log): + raise ValueError("exposure can only be used with the log link " + "function") + + # Use fit exposure if appropriate + if exposure is None and exog is None and hasattr(self, 'exposure'): + # Already logged + exposure = self.exposure + elif exposure is None: + exposure = 0. + else: + exposure = np.log(np.asarray(exposure)) + + if exog is None: + exog = self.exog + + linpred = np.dot(exog, params) + offset + exposure + + if which == "mean": + return self.family.fitted(linpred) + elif which == "linear": + return linpred + elif which == "var_unscaled": + mean = self.family.fitted(linpred) + var_ = self.family.variance(mean) + return var_ + else: + raise ValueError(f'The which value "{which}" is not recognized') + + def get_distribution(self, params, scale=None, exog=None, exposure=None, + offset=None, var_weights=1., n_trials=1.): + """ + Return a instance of the predictive distribution. + + Parameters + ---------- + params : array_like + The model parameters. + scale : scalar + The scale parameter. + exog : array_like + The predictor variable matrix. + offset : array_like or None + Offset variable for predicted mean. + exposure : array_like or None + Log(exposure) will be added to the linear prediction. + var_weights : array_like + 1d array of variance (analytic) weights. The default is None. + n_trials : int + Number of trials for the binomial distribution. The default is 1 + which corresponds to a Bernoulli random variable. + + Returns + ------- + gen + Instance of a scipy frozen distribution based on estimated + parameters. + Use the ``rvs`` method to generate random values. + + Notes + ----- + Due to the behavior of ``scipy.stats.distributions objects``, the + returned random number generator must be called with ``gen.rvs(n)`` + where ``n`` is the number of observations in the data set used + to fit the model. If any other value is used for ``n``, misleading + results will be produced. + """ + scale = float_like(scale, "scale", optional=True) + # use scale=1, independent of QMLE scale for discrete + if isinstance(self.family, (families.Binomial, families.Poisson, + families.NegativeBinomial)): + scale = 1. + + mu = self.predict(params, exog, exposure, offset, which="mean") + + kwds = {} + if (np.any(n_trials != 1) and + isinstance(self.family, families.Binomial)): + + kwds["n_trials"] = n_trials + + distr = self.family.get_distribution(mu, scale, + var_weights=var_weights, **kwds) + return distr + + def _setup_binomial(self): + # this checks what kind of data is given for Binomial. + # family will need a reference to endog if this is to be removed from + # preprocessing + self.n_trials = np.ones(self.endog.shape[0]) # For binomial + if isinstance(self.family, families.Binomial): + tmp = self.family.initialize(self.endog, self.freq_weights) + self.endog = tmp[0] + self.n_trials = tmp[1] + self._init_keys.append('n_trials') + + def fit(self, start_params=None, maxiter=100, method='IRLS', tol=1e-8, + scale=None, cov_type='nonrobust', cov_kwds=None, use_t=None, + full_output=True, disp=False, max_start_irls=3, **kwargs): + """ + Fits a generalized linear model for a given family. + + Parameters + ---------- + start_params : array_like, optional + Initial guess of the solution for the loglikelihood maximization. + The default is family-specific and is given by the + ``family.starting_mu(endog)``. If start_params is given then the + initial mean will be calculated as ``np.dot(exog, start_params)``. + maxiter : int, optional + Default is 100. + method : str + Default is 'IRLS' for iteratively reweighted least squares. + Otherwise gradient optimization is used. + tol : float + Convergence tolerance. Default is 1e-8. + scale : str or float, optional + `scale` can be 'X2', 'dev', or a float + The default value is None, which uses `X2` for Gamma, Gaussian, + and Inverse Gaussian. + `X2` is Pearson's chi-square divided by `df_resid`. + The default is 1 for the Binomial and Poisson families. + `dev` is the deviance divided by df_resid + cov_type : str + The type of parameter estimate covariance matrix to compute. + cov_kwds : dict-like + Extra arguments for calculating the covariance of the parameter + estimates. + use_t : bool + If True, the Student t-distribution is used for inference. + full_output : bool, optional + Set to True to have all available output in the Results object's + mle_retvals attribute. The output is dependent on the solver. + See LikelihoodModelResults notes section for more information. + Not used if methhod is IRLS. + disp : bool, optional + Set to True to print convergence messages. Not used if method is + IRLS. + max_start_irls : int + The number of IRLS iterations used to obtain starting + values for gradient optimization. Only relevant if + `method` is set to something other than 'IRLS'. + atol : float, optional + (available with IRLS fits) The absolute tolerance criterion that + must be satisfied. Defaults to ``tol``. Convergence is attained + when: :math:`rtol * prior + atol > abs(current - prior)` + rtol : float, optional + (available with IRLS fits) The relative tolerance criterion that + must be satisfied. Defaults to 0 which means ``rtol`` is not used. + Convergence is attained when: + :math:`rtol * prior + atol > abs(current - prior)` + tol_criterion : str, optional + (available with IRLS fits) Defaults to ``'deviance'``. Can + optionally be ``'params'``. + wls_method : str, optional + (available with IRLS fits) options are 'lstsq', 'pinv' and 'qr' + specifies which linear algebra function to use for the irls + optimization. Default is `lstsq` which uses the same underlying + svd based approach as 'pinv', but is faster during iterations. + 'lstsq' and 'pinv' regularize the estimate in singular and + near-singular cases by truncating small singular values based + on `rcond` of the respective numpy.linalg function. 'qr' is + only valid for cases that are not singular nor near-singular. + optim_hessian : {'eim', 'oim'}, optional + (available with scipy optimizer fits) When 'oim'--the default--the + observed Hessian is used in fitting. 'eim' is the expected Hessian. + This may provide more stable fits, but adds assumption that the + Hessian is correctly specified. + + Notes + ----- + If method is 'IRLS', then an additional keyword 'attach_wls' is + available. This is currently for internal use only and might change + in future versions. If attach_wls' is true, then the final WLS + instance of the IRLS iteration is attached to the results instance + as `results_wls` attribute. + """ + if isinstance(scale, str): + scale = scale.lower() + if scale not in ("x2", "dev"): + raise ValueError( + "scale must be either X2 or dev when a string." + ) + elif scale is not None: + # GH-6627 + try: + scale = float(scale) + except Exception as exc: + raise type(exc)( + "scale must be a float if given and no a string." + ) + self.scaletype = scale + + if method.lower() == "irls": + if cov_type.lower() == 'eim': + cov_type = 'nonrobust' + return self._fit_irls(start_params=start_params, maxiter=maxiter, + tol=tol, scale=scale, cov_type=cov_type, + cov_kwds=cov_kwds, use_t=use_t, **kwargs) + else: + self._optim_hessian = kwargs.get('optim_hessian') + if self._optim_hessian is not None: + del kwargs['optim_hessian'] + self._tmp_like_exog = np.empty_like(self.exog, dtype=float) + fit_ = self._fit_gradient(start_params=start_params, + method=method, + maxiter=maxiter, + tol=tol, scale=scale, + full_output=full_output, + disp=disp, cov_type=cov_type, + cov_kwds=cov_kwds, use_t=use_t, + max_start_irls=max_start_irls, + **kwargs) + del self._optim_hessian + del self._tmp_like_exog + return fit_ + + def _fit_gradient(self, start_params=None, method="newton", + maxiter=100, tol=1e-8, full_output=True, + disp=True, scale=None, cov_type='nonrobust', + cov_kwds=None, use_t=None, max_start_irls=3, + **kwargs): + """ + Fits a generalized linear model for a given family iteratively + using the scipy gradient optimizers. + """ + + # fix scale during optimization, see #4616 + scaletype = self.scaletype + self.scaletype = 1. + + if (max_start_irls > 0) and (start_params is None): + irls_rslt = self._fit_irls(start_params=start_params, + maxiter=max_start_irls, + tol=tol, scale=1., cov_type='nonrobust', + cov_kwds=None, use_t=None, + **kwargs) + start_params = irls_rslt.params + del irls_rslt + rslt = super().fit(start_params=start_params, + maxiter=maxiter, full_output=full_output, + method=method, disp=disp, **kwargs) + + # reset scaletype to original + self.scaletype = scaletype + + mu = self.predict(rslt.params) + scale = self.estimate_scale(mu) + + if rslt.normalized_cov_params is None: + cov_p = None + else: + cov_p = rslt.normalized_cov_params / scale + + if cov_type.lower() == 'eim': + oim = False + cov_type = 'nonrobust' + else: + oim = True + + try: + cov_p = np.linalg.inv(-self.hessian(rslt.params, observed=oim)) / scale + except LinAlgError: + warnings.warn('Inverting hessian failed, no bse or cov_params ' + 'available', HessianInversionWarning) + cov_p = None + + results_class = getattr(self, '_results_class', GLMResults) + results_class_wrapper = getattr(self, '_results_class_wrapper', GLMResultsWrapper) + glm_results = results_class(self, rslt.params, + cov_p, + scale, + cov_type=cov_type, cov_kwds=cov_kwds, + use_t=use_t) + + # TODO: iteration count is not always available + history = {'iteration': 0} + if full_output: + glm_results.mle_retvals = rslt.mle_retvals + if 'iterations' in rslt.mle_retvals: + history['iteration'] = rslt.mle_retvals['iterations'] + glm_results.method = method + glm_results.fit_history = history + + return results_class_wrapper(glm_results) + + def _fit_irls(self, start_params=None, maxiter=100, tol=1e-8, + scale=None, cov_type='nonrobust', cov_kwds=None, + use_t=None, **kwargs): + """ + Fits a generalized linear model for a given family using + iteratively reweighted least squares (IRLS). + """ + attach_wls = kwargs.pop('attach_wls', False) + atol = kwargs.get('atol') + rtol = kwargs.get('rtol', 0.) + tol_criterion = kwargs.get('tol_criterion', 'deviance') + wls_method = kwargs.get('wls_method', 'lstsq') + atol = tol if atol is None else atol + + endog = self.endog + wlsexog = self.exog + if start_params is None: + start_params = np.zeros(self.exog.shape[1]) + mu = self.family.starting_mu(self.endog) + lin_pred = self.family.predict(mu) + else: + lin_pred = np.dot(wlsexog, start_params) + self._offset_exposure + mu = self.family.fitted(lin_pred) + self.scale = self.estimate_scale(mu) + dev = self.family.deviance(self.endog, mu, self.var_weights, + self.freq_weights, self.scale) + if np.isnan(dev): + raise ValueError("The first guess on the deviance function " + "returned a nan. This could be a boundary " + " problem and should be reported.") + + # first guess on the deviance is assumed to be scaled by 1. + # params are none to start, so they line up with the deviance + history = dict(params=[np.inf, start_params], deviance=[np.inf, dev]) + converged = False + criterion = history[tol_criterion] + # This special case is used to get the likelihood for a specific + # params vector. + if maxiter == 0: + mu = self.family.fitted(lin_pred) + self.scale = self.estimate_scale(mu) + wls_results = lm.RegressionResults(self, start_params, None) + iteration = 0 + for iteration in range(maxiter): + self.weights = (self.iweights * self.n_trials * + self.family.weights(mu)) + wlsendog = (lin_pred + self.family.link.deriv(mu) * (self.endog-mu) + - self._offset_exposure) + wls_mod = reg_tools._MinimalWLS(wlsendog, wlsexog, + self.weights, check_endog=True, + check_weights=True) + wls_results = wls_mod.fit(method=wls_method) + lin_pred = np.dot(self.exog, wls_results.params) + lin_pred += self._offset_exposure + mu = self.family.fitted(lin_pred) + history = self._update_history(wls_results, mu, history) + self.scale = self.estimate_scale(mu) + if endog.squeeze().ndim == 1 and np.allclose(mu - endog, 0): + msg = ("Perfect separation or prediction detected, " + "parameter may not be identified") + warnings.warn(msg, category=PerfectSeparationWarning) + converged = _check_convergence(criterion, iteration + 1, atol, + rtol) + if converged: + break + self.mu = mu + + if maxiter > 0: # Only if iterative used + wls_method2 = 'pinv' if wls_method == 'lstsq' else wls_method + wls_model = lm.WLS(wlsendog, wlsexog, self.weights) + wls_results = wls_model.fit(method=wls_method2) + + glm_results = GLMResults(self, wls_results.params, + wls_results.normalized_cov_params, + self.scale, + cov_type=cov_type, cov_kwds=cov_kwds, + use_t=use_t) + + glm_results.method = "IRLS" + glm_results.mle_settings = {} + glm_results.mle_settings['wls_method'] = wls_method + glm_results.mle_settings['optimizer'] = glm_results.method + if (maxiter > 0) and (attach_wls is True): + glm_results.results_wls = wls_results + history['iteration'] = iteration + 1 + glm_results.fit_history = history + glm_results.converged = converged + return GLMResultsWrapper(glm_results) + + def fit_regularized(self, method="elastic_net", alpha=0., + start_params=None, refit=False, + opt_method="bfgs", **kwargs): + r""" + Return a regularized fit to a linear regression model. + + Parameters + ---------- + method : {'elastic_net'} + Only the `elastic_net` approach is currently implemented. + alpha : scalar or array_like + The penalty weight. If a scalar, the same penalty weight + applies to all variables in the model. If a vector, it + must have the same length as `params`, and contains a + penalty weight for each coefficient. + start_params : array_like + Starting values for `params`. + refit : bool + If True, the model is refit using only the variables that + have non-zero coefficients in the regularized fit. The + refitted model is not regularized. + opt_method : string + The method used for numerical optimization. + **kwargs + Additional keyword arguments used when fitting the model. + + Returns + ------- + GLMResults + An array or a GLMResults object, same type returned by `fit`. + + Notes + ----- + The penalty is the ``elastic net`` penalty, which is a + combination of L1 and L2 penalties. + + The function that is minimized is: + + .. math:: + + -loglike/n + alpha*((1-L1\_wt)*|params|_2^2/2 + L1\_wt*|params|_1) + + where :math:`|*|_1` and :math:`|*|_2` are the L1 and L2 norms. + + Post-estimation results are based on the same data used to + select variables, hence may be subject to overfitting biases. + + The elastic_net method uses the following keyword arguments: + + maxiter : int + Maximum number of iterations + L1_wt : float + Must be in [0, 1]. The L1 penalty has weight L1_wt and the + L2 penalty has weight 1 - L1_wt. + cnvrg_tol : float + Convergence threshold for maximum parameter change after + one sweep through all coefficients. + zero_tol : float + Coefficients below this threshold are treated as zero. + """ + + if kwargs.get("L1_wt", 1) == 0: + return self._fit_ridge(alpha, start_params, opt_method) + + from statsmodels.base.elastic_net import fit_elasticnet + + if method != "elastic_net": + raise ValueError("method for fit_regularized must be elastic_net") + + defaults = {"maxiter": 50, "L1_wt": 1, "cnvrg_tol": 1e-10, + "zero_tol": 1e-10} + defaults.update(kwargs) + + llkw = kwargs.get("loglike_kwds", {}) + sckw = kwargs.get("score_kwds", {}) + hekw = kwargs.get("hess_kwds", {}) + llkw["scale"] = 1 + sckw["scale"] = 1 + hekw["scale"] = 1 + defaults["loglike_kwds"] = llkw + defaults["score_kwds"] = sckw + defaults["hess_kwds"] = hekw + + result = fit_elasticnet(self, method=method, + alpha=alpha, + start_params=start_params, + refit=refit, + **defaults) + + self.mu = self.predict(result.params) + self.scale = self.estimate_scale(self.mu) + + if not result.converged: + warnings.warn("Elastic net fitting did not converge") + + return result + + def _fit_ridge(self, alpha, start_params, method): + + if start_params is None: + start_params = np.zeros(self.exog.shape[1]) + + def fun(x): + return -(self.loglike(x) / self.nobs - np.sum(alpha * x**2) / 2) + + def grad(x): + return -(self.score(x) / self.nobs - alpha * x) + + from scipy.optimize import minimize + + from statsmodels.base.elastic_net import ( + RegularizedResults, + RegularizedResultsWrapper, + ) + + mr = minimize(fun, start_params, jac=grad, method=method) + params = mr.x + + if not mr.success: + ngrad = np.sqrt(np.sum(mr.jac**2)) + msg = "GLM ridge optimization may have failed, |grad|=%f" % ngrad + warnings.warn(msg) + + results = RegularizedResults(self, params) + results = RegularizedResultsWrapper(results) + + return results + + def fit_constrained(self, constraints, start_params=None, **fit_kwds): + """fit the model subject to linear equality constraints + + The constraints are of the form `R params = q` + where R is the constraint_matrix and q is the vector of + constraint_values. + + The estimation creates a new model with transformed design matrix, + exog, and converts the results back to the original parameterization. + + + Parameters + ---------- + constraints : formula expression or tuple + If it is a tuple, then the constraint needs to be given by two + arrays (constraint_matrix, constraint_value), i.e. (R, q). + Otherwise, the constraints can be given as strings or list of + strings. + see t_test for details + start_params : None or array_like + starting values for the optimization. `start_params` needs to be + given in the original parameter space and are internally + transformed. + **fit_kwds : keyword arguments + fit_kwds are used in the optimization of the transformed model. + + Returns + ------- + results : Results instance + """ + + from patsy import DesignInfo + + from statsmodels.base._constraints import ( + LinearConstraints, + fit_constrained, + ) + + # same pattern as in base.LikelihoodModel.t_test + lc = DesignInfo(self.exog_names).linear_constraint(constraints) + R, q = lc.coefs, lc.constants + + # TODO: add start_params option, need access to tranformation + # fit_constrained needs to do the transformation + params, cov, res_constr = fit_constrained(self, R, q, + start_params=start_params, + fit_kwds=fit_kwds) + # create dummy results Instance, TODO: wire up properly + res = self.fit(start_params=params, maxiter=0) # we get a wrapper back + res._results.params = params + res._results.cov_params_default = cov + cov_type = fit_kwds.get('cov_type', 'nonrobust') + if cov_type != 'nonrobust': + res._results.normalized_cov_params = cov / res_constr.scale + else: + res._results.normalized_cov_params = None + res._results.scale = res_constr.scale + k_constr = len(q) + res._results.df_resid += k_constr + res._results.df_model -= k_constr + res._results.constraints = LinearConstraints.from_patsy(lc) + res._results.k_constr = k_constr + res._results.results_constrained = res_constr + return res + + +get_prediction_doc = Docstring(pred.get_prediction_glm.__doc__) +get_prediction_doc.remove_parameters("pred_kwds") + + +class GLMResults(base.LikelihoodModelResults): + """ + Class to contain GLM results. + + GLMResults inherits from statsmodels.LikelihoodModelResults + + Attributes + ---------- + df_model : float + See GLM.df_model + df_resid : float + See GLM.df_resid + fit_history : dict + Contains information about the iterations. Its keys are `iterations`, + `deviance` and `params`. + model : class instance + Pointer to GLM model instance that called fit. + nobs : float + The number of observations n. + normalized_cov_params : ndarray + See GLM docstring + params : ndarray + The coefficients of the fitted model. Note that interpretation + of the coefficients often depends on the distribution family and the + data. + pvalues : ndarray + The two-tailed p-values for the parameters. + scale : float + The estimate of the scale / dispersion for the model fit. + See GLM.fit and GLM.estimate_scale for more information. + stand_errors : ndarray + The standard errors of the fitted GLM. #TODO still named bse + + See Also + -------- + statsmodels.base.model.LikelihoodModelResults + """ + + def __init__(self, model, params, normalized_cov_params, scale, + cov_type='nonrobust', cov_kwds=None, use_t=None): + super().__init__( + model, + params, + normalized_cov_params=normalized_cov_params, + scale=scale) + self.family = model.family + self._endog = model.endog + self.nobs = model.endog.shape[0] + self._freq_weights = model.freq_weights + self._var_weights = model.var_weights + self._iweights = model.iweights + if isinstance(self.family, families.Binomial): + self._n_trials = self.model.n_trials + else: + self._n_trials = 1 + self.df_resid = model.df_resid + self.df_model = model.df_model + self._cache = {} + # are these intermediate results needed or can we just + # call the model's attributes? + + # for remove data and pickle without large arrays + self._data_attr.extend(['results_constrained', '_freq_weights', + '_var_weights', '_iweights']) + self._data_in_cache.extend(['null', 'mu']) + self._data_attr_model = getattr(self, '_data_attr_model', []) + self._data_attr_model.append('mu') + + # robust covariance + from statsmodels.base.covtype import get_robustcov_results + if use_t is None: + self.use_t = False # TODO: class default + else: + self.use_t = use_t + + # temporary warning + ct = (cov_type == 'nonrobust') or (cov_type.upper().startswith('HC')) + if self.model._has_freq_weights and not ct: + + from statsmodels.tools.sm_exceptions import SpecificationWarning + warnings.warn('cov_type not fully supported with freq_weights', + SpecificationWarning) + + if self.model._has_var_weights and not ct: + + from statsmodels.tools.sm_exceptions import SpecificationWarning + warnings.warn('cov_type not fully supported with var_weights', + SpecificationWarning) + + if cov_type == 'nonrobust': + self.cov_type = 'nonrobust' + self.cov_kwds = {'description': 'Standard Errors assume that the' + + ' covariance matrix of the errors is correctly ' + + 'specified.'} + + else: + if cov_kwds is None: + cov_kwds = {} + get_robustcov_results(self, cov_type=cov_type, use_self=True, + use_t=use_t, **cov_kwds) + + @cached_data + def resid_response(self): + """ + Response residuals. The response residuals are defined as + `endog` - `fittedvalues` + """ + return self._n_trials * (self._endog-self.mu) + + @cached_data + def resid_pearson(self): + """ + Pearson residuals. The Pearson residuals are defined as + (`endog` - `mu`)/sqrt(VAR(`mu`)) where VAR is the distribution + specific variance function. See statsmodels.families.family and + statsmodels.families.varfuncs for more information. + """ + return (np.sqrt(self._n_trials) * (self._endog-self.mu) * + np.sqrt(self._var_weights) / + np.sqrt(self.family.variance(self.mu))) + + @cached_data + def resid_working(self): + """ + Working residuals. The working residuals are defined as + `resid_response`/link'(`mu`). See statsmodels.family.links for the + derivatives of the link functions. They are defined analytically. + """ + # Isn't self.resid_response is already adjusted by _n_trials? + val = (self.resid_response * self.family.link.deriv(self.mu)) + val *= self._n_trials + return val + + @cached_data + def resid_anscombe(self): + """ + Anscombe residuals. See statsmodels.families.family for distribution- + specific Anscombe residuals. Currently, the unscaled residuals are + provided. In a future version, the scaled residuals will be provided. + """ + return self.resid_anscombe_scaled + + @cached_data + def resid_anscombe_scaled(self): + """ + Scaled Anscombe residuals. See statsmodels.families.family for + distribution-specific Anscombe residuals. + """ + return self.family.resid_anscombe(self._endog, self.fittedvalues, + var_weights=self._var_weights, + scale=self.scale) + + @cached_data + def resid_anscombe_unscaled(self): + """ + Unscaled Anscombe residuals. See statsmodels.families.family for + distribution-specific Anscombe residuals. + """ + return self.family.resid_anscombe(self._endog, self.fittedvalues, + var_weights=self._var_weights, + scale=1.) + + @cached_data + def resid_deviance(self): + """ + Deviance residuals. See statsmodels.families.family for distribution- + specific deviance residuals. + """ + dev = self.family.resid_dev(self._endog, self.fittedvalues, + var_weights=self._var_weights, + scale=1.) + return dev + + @cached_value + def pearson_chi2(self): + """ + Pearson's Chi-Squared statistic is defined as the sum of the squares + of the Pearson residuals. + """ + chisq = (self._endog - self.mu)**2 / self.family.variance(self.mu) + chisq *= self._iweights * self._n_trials + chisqsum = np.sum(chisq) + return chisqsum + + @cached_data + def fittedvalues(self): + """ + The estimated mean response. + + This is the value of the inverse of the link function at + lin_pred, where lin_pred is the linear predicted value + obtained by multiplying the design matrix by the coefficient + vector. + """ + return self.mu + + @cached_data + def mu(self): + """ + See GLM docstring. + """ + return self.model.predict(self.params) + + @cache_readonly + def null(self): + """ + Fitted values of the null model + """ + endog = self._endog + model = self.model + exog = np.ones((len(endog), 1)) + + kwargs = model._get_init_kwds().copy() + kwargs.pop('family') + + for key in getattr(model, '_null_drop_keys', []): + del kwargs[key] + start_params = np.atleast_1d(self.family.link(endog.mean())) + oe = self.model._offset_exposure + if not (np.size(oe) == 1 and oe == 0): + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DomainWarning) + mod = GLM(endog, exog, family=self.family, **kwargs) + fitted = mod.fit(start_params=start_params).fittedvalues + else: + # correct if fitted is identical across observations + wls_model = lm.WLS(endog, exog, + weights=self._iweights * self._n_trials) + fitted = wls_model.fit().fittedvalues + + return fitted + + @cache_readonly + def deviance(self): + """ + See statsmodels.families.family for the distribution-specific deviance + functions. + """ + return self.family.deviance(self._endog, self.mu, self._var_weights, + self._freq_weights) + + @cache_readonly + def null_deviance(self): + """The value of the deviance function for the model fit with a constant + as the only regressor.""" + return self.family.deviance(self._endog, self.null, self._var_weights, + self._freq_weights) + + @cache_readonly + def llnull(self): + """ + Log-likelihood of the model fit with a constant as the only regressor + """ + return self.family.loglike(self._endog, self.null, + var_weights=self._var_weights, + freq_weights=self._freq_weights, + scale=self.scale) + + def llf_scaled(self, scale=None): + """ + Return the log-likelihood at the given scale, using the + estimated scale if the provided scale is None. In the Gaussian + case with linear link, the concentrated log-likelihood is + returned. + """ + + _modelfamily = self.family + if scale is None: + if (isinstance(self.family, families.Gaussian) and + isinstance(self.family.link, families.links.Power) and + (self.family.link.power == 1.)): + # Scale for the concentrated Gaussian log likelihood + # (profile log likelihood with the scale parameter + # profiled out). + scale = (np.power(self._endog - self.mu, 2) * self._iweights).sum() + scale /= self.model.wnobs + else: + scale = self.scale + val = _modelfamily.loglike(self._endog, self.mu, + var_weights=self._var_weights, + freq_weights=self._freq_weights, + scale=scale) + return val + + @cached_value + def llf(self): + """ + Value of the loglikelihood function evalued at params. + See statsmodels.families.family for distribution-specific + loglikelihoods. The result uses the concentrated + log-likelihood if the family is Gaussian and the link is linear, + otherwise it uses the non-concentrated log-likelihood evaluated + at the estimated scale. + """ + return self.llf_scaled() + + def pseudo_rsquared(self, kind="cs"): + """ + Pseudo R-squared + + Cox-Snell likelihood ratio pseudo R-squared is valid for both discrete + and continuous data. McFadden's pseudo R-squared is only valid for + discrete data. + + Cox & Snell's pseudo-R-squared: 1 - exp((llnull - llf)*(2/nobs)) + + McFadden's pseudo-R-squared: 1 - (llf / llnull) + + Parameters + ---------- + kind : P"cs", "mcf"} + Type of pseudo R-square to return + + Returns + ------- + float + Pseudo R-squared + """ + kind = kind.lower() + if kind.startswith("mcf"): + prsq = 1 - self.llf / self.llnull + elif kind.startswith("cox") or kind in ["cs", "lr"]: + prsq = 1 - np.exp((self.llnull - self.llf) * (2 / self.nobs)) + else: + raise ValueError("only McFadden and Cox-Snell are available") + return prsq + + @cached_value + def aic(self): + """ + Akaike Information Criterion + -2 * `llf` + 2 * (`df_model` + 1) + """ + return self.info_criteria("aic") + + @property + def bic(self): + """ + Bayes Information Criterion + + `deviance` - `df_resid` * log(`nobs`) + + .. warning:: + + The current definition is based on the deviance rather than the + log-likelihood. This is not consistent with the AIC definition, + and after 0.13 both will make use of the log-likelihood definition. + + Notes + ----- + The log-likelihood version is defined + -2 * `llf` + (`df_model` + 1)*log(n) + """ + if _use_bic_helper.use_bic_llf not in (True, False): + warnings.warn( + "The bic value is computed using the deviance formula. After " + "0.13 this will change to the log-likelihood based formula. " + "This change has no impact on the relative rank of models " + "compared using BIC. You can directly access the " + "log-likelihood version using the `bic_llf` attribute. You " + "can suppress this message by calling " + "statsmodels.genmod.generalized_linear_model.SET_USE_BIC_LLF " + "with True to get the LLF-based version now or False to retain" + "the deviance version.", + FutureWarning + ) + if bool(_use_bic_helper.use_bic_llf): + return self.bic_llf + + return self.bic_deviance + + @cached_value + def bic_deviance(self): + """ + Bayes Information Criterion + + Based on the deviance, + `deviance` - `df_resid` * log(`nobs`) + """ + return (self.deviance - + (self.model.wnobs - self.df_model - 1) * + np.log(self.model.wnobs)) + + @cached_value + def bic_llf(self): + """ + Bayes Information Criterion + + Based on the log-likelihood, + -2 * `llf` + log(n) * (`df_model` + 1) + """ + return self.info_criteria("bic") + + def info_criteria(self, crit, scale=None, dk_params=0): + """Return an information criterion for the model. + + Parameters + ---------- + crit : string + One of 'aic', 'bic', or 'qaic'. + scale : float + The scale parameter estimated using the parent model, + used only for qaic. + dk_params : int or float + Correction to the number of parameters used in the information + criterion. By default, only mean parameters are included, the + scale parameter is not included in the parameter count. + Use ``dk_params=1`` to include scale in the parameter count. + + Returns + ------- + Value of information criterion. + + Notes + ----- + The quasi-Akaike Information criterion (qaic) is -2 * + `llf`/`scale` + 2 * (`df_model` + 1). It may not give + meaningful results except for Poisson and related models. + + The QAIC (ic_type='qaic') must be evaluated with a provided + scale parameter. Two QAIC values are only comparable if they + are calculated using the same scale parameter. The scale + parameter should be estimated using the largest model among + all models being compared. + + References + ---------- + Burnham KP, Anderson KR (2002). Model Selection and Multimodel + Inference; Springer New York. + """ + crit = crit.lower() + k_params = self.df_model + 1 + dk_params + + if crit == "aic": + return -2 * self.llf + 2 * k_params + elif crit == "bic": + nobs = self.df_model + self.df_resid + 1 + bic = -2*self.llf + k_params*np.log(nobs) + return bic + elif crit == "qaic": + f = self.model.family + fl = (families.Poisson, families.NegativeBinomial, + families.Binomial) + if not isinstance(f, fl): + msg = "QAIC is only valid for Binomial, Poisson and " + msg += "Negative Binomial families." + warnings.warn(msg) + llf = self.llf_scaled(scale=1) + return -2 * llf/scale + 2 * k_params + + # now explicit docs, old and new behavior, copied from generic classes + # @Appender(str(get_prediction_doc)) + def get_prediction(self, exog=None, exposure=None, offset=None, + transform=True, which=None, linear=None, + average=False, agg_weights=None, + row_labels=None): + """ + Compute prediction results for GLM compatible models. + + Options and return class depend on whether "which" is None or not. + + Parameters + ---------- + exog : array_like, optional + The values for which you want to predict. + exposure : array_like, optional + Exposure time values, only can be used with the log link + function. + offset : array_like, optional + Offset values. + transform : bool, optional + If the model was fit via a formula, do you want to pass + exog through the formula. Default is True. E.g., if you fit + a model y ~ log(x1) + log(x2), and transform is True, then + you can pass a data structure that contains x1 and x2 in + their original form. Otherwise, you'd need to log the data + first. + which : 'mean', 'linear', 'var'(optional) + Statitistic to predict. Default is 'mean'. + If which is None, then the deprecated keyword "linear" applies. + If which is not None, then a generic Prediction results class will + be returned. Some options are only available if which is not None. + See notes. + + - 'mean' returns the conditional expectation of endog E(y | x), + i.e. inverse of the model's link function of linear predictor. + - 'linear' returns the linear predictor of the mean function. + - 'var_unscaled' variance of endog implied by the likelihood model. + This does not include scale or var_weights. + + linear : bool + The ``linear` keyword is deprecated and will be removed, + use ``which`` keyword instead. + If which is None, then the linear keyword is used, otherwise it will + be ignored. + If True and which is None, the linear predicted values are returned. + If False or None, then the statistic specified by ``which`` will be + returned. + average : bool + Keyword is only used if ``which`` is not None. + If average is True, then the mean prediction is computed, that is, + predictions are computed for individual exog and then the average + over observation is used. + If average is False, then the results are the predictions for all + observations, i.e. same length as ``exog``. + agg_weights : ndarray, optional + Keyword is only used if ``which`` is not None. + Aggregation weights, only used if average is True. + row_labels : list of str or None + If row_lables are provided, then they will replace the generated + labels. + + Returns + ------- + prediction_results : instance of a PredictionResults class. + The prediction results instance contains prediction and prediction + variance and can on demand calculate confidence intervals and summary + tables for the prediction of the mean and of new observations. + The Results class of the return depends on the value of ``which``. + + See Also + -------- + GLM.predict + GLMResults.predict + + Notes + ----- + Changes in statsmodels 0.14: The ``which`` keyword has been added. + If ``which`` is None, then the behavior is the same as in previous + versions, and returns the mean and linear prediction results. + If the ``which`` keyword is not None, then a generic prediction results + class is returned and is not backwards compatible with the old prediction + results class, e.g. column names of summary_frame differs. + There are more choices for the returned predicted statistic using + ``which``. More choices will be added in the next release. + Two additional keyword, average and agg_weights options are now also + available if ``which`` is not None. + In a future version ``which`` will become not None and the backwards + compatible prediction results class will be removed. + + """ + + import statsmodels.regression._prediction as linpred + + pred_kwds = {'exposure': exposure, 'offset': offset, 'which': 'linear'} + + if which is None: + # two calls to a get_prediction duplicates exog generation if patsy + res_linpred = linpred.get_prediction(self, exog=exog, + transform=transform, + row_labels=row_labels, + pred_kwds=pred_kwds) + + pred_kwds['which'] = 'mean' + res = pred.get_prediction_glm(self, exog=exog, transform=transform, + row_labels=row_labels, + linpred=res_linpred, + link=self.model.family.link, + pred_kwds=pred_kwds) + else: + # new generic version, if 'which' is specified + + pred_kwds = {'exposure': exposure, 'offset': offset} + # not yet, only applies to count families + # y_values is explicit so we can add it to the docstring + # if y_values is not None: + # pred_kwds["y_values"] = y_values + + res = pred.get_prediction( + self, + exog=exog, + which=which, + transform=transform, + row_labels=row_labels, + average=average, + agg_weights=agg_weights, + pred_kwds=pred_kwds + ) + + return res + + @Appender(pinfer.score_test.__doc__) + def score_test(self, exog_extra=None, params_constrained=None, + hypothesis='joint', cov_type=None, cov_kwds=None, + k_constraints=None, observed=True): + + if self.model._has_freq_weights is True: + warnings.warn("score test has not been verified with freq_weights", + UserWarning) + if self.model._has_var_weights is True: + warnings.warn("score test has not been verified with var_weights", + UserWarning) + + # We need to temporarily change model.df_resid for scale computation + # TODO: find a nicer way. gh #7840 + mod_df_resid = self.model.df_resid + self.model.df_resid = self.df_resid + if k_constraints is not None: + self.model.df_resid += k_constraints + res = pinfer.score_test(self, exog_extra=exog_extra, + params_constrained=params_constrained, + hypothesis=hypothesis, + cov_type=cov_type, cov_kwds=cov_kwds, + k_constraints=k_constraints, + scale=None, + observed=observed) + + self.model.df_resid = mod_df_resid + return res + + def get_hat_matrix_diag(self, observed=True): + """ + Compute the diagonal of the hat matrix + + Parameters + ---------- + observed : bool + If true, then observed hessian is used in the hat matrix + computation. If false, then the expected hessian is used. + In the case of a canonical link function both are the same. + + Returns + ------- + hat_matrix_diag : ndarray + The diagonal of the hat matrix computed from the observed + or expected hessian. + """ + weights = self.model.hessian_factor(self.params, observed=observed) + wexog = np.sqrt(weights)[:, None] * self.model.exog + + hd = (wexog * np.linalg.pinv(wexog).T).sum(1) + return hd + + def get_influence(self, observed=True): + """ + Get an instance of GLMInfluence with influence and outlier measures + + Parameters + ---------- + observed : bool + If true, then observed hessian is used in the hat matrix + computation. If false, then the expected hessian is used. + In the case of a canonical link function both are the same. + + Returns + ------- + infl : GLMInfluence instance + The instance has methods to calculate the main influence and + outlier measures as attributes. + + See Also + -------- + statsmodels.stats.outliers_influence.GLMInfluence + """ + from statsmodels.stats.outliers_influence import GLMInfluence + + weights = self.model.hessian_factor(self.params, observed=observed) + weights_sqrt = np.sqrt(weights) + wexog = weights_sqrt[:, None] * self.model.exog + wendog = weights_sqrt * self.model.endog + + # using get_hat_matrix_diag has duplicated computation + hat_matrix_diag = self.get_hat_matrix_diag(observed=observed) + infl = GLMInfluence(self, endog=wendog, exog=wexog, + resid=self.resid_pearson / np.sqrt(self.scale), + hat_matrix_diag=hat_matrix_diag) + return infl + + def get_distribution(self, exog=None, exposure=None, + offset=None, var_weights=1., n_trials=1.): + """ + Return a instance of the predictive distribution. + + Parameters + ---------- + scale : scalar + The scale parameter. + exog : array_like + The predictor variable matrix. + offset : array_like or None + Offset variable for predicted mean. + exposure : array_like or None + Log(exposure) will be added to the linear prediction. + var_weights : array_like + 1d array of variance (analytic) weights. The default is None. + n_trials : int + Number of trials for the binomial distribution. The default is 1 + which corresponds to a Bernoulli random variable. + + Returns + ------- + gen + Instance of a scipy frozen distribution based on estimated + parameters. + Use the ``rvs`` method to generate random values. + + Notes + ----- + Due to the behavior of ``scipy.stats.distributions objects``, the + returned random number generator must be called with ``gen.rvs(n)`` + where ``n`` is the number of observations in the data set used + to fit the model. If any other value is used for ``n``, misleading + results will be produced. + """ + # Note this is mostly a copy of GLM.get_prediction + # calling here results.predict avoids the exog check and trasnform + + if isinstance(self.model.family, (families.Binomial, families.Poisson, + families.NegativeBinomial)): + # use scale=1, independent of QMLE scale for discrete + scale = 1. + if self.scale != 1.: + msg = "using scale=1, no exess dispersion in distribution" + warnings.warn(msg, UserWarning) + else: + scale = self.scale + + mu = self.predict(exog, exposure, offset, which="mean") + + kwds = {} + if (np.any(n_trials != 1) and + isinstance(self.model.family, families.Binomial)): + + kwds["n_trials"] = n_trials + + distr = self.model.family.get_distribution( + mu, scale, var_weights=var_weights, **kwds) + return distr + + def get_margeff(self, at='overall', method='dydx', atexog=None, + dummy=False, count=False): + """Get marginal effects of the fitted model. + + Warning: offset, exposure and weights (var_weights and freq_weights) + are not supported by margeff. + + Parameters + ---------- + at : str, optional + Options are: + + - 'overall', The average of the marginal effects at each + observation. + - 'mean', The marginal effects at the mean of each regressor. + - 'median', The marginal effects at the median of each regressor. + - 'zero', The marginal effects at zero for each regressor. + - 'all', The marginal effects at each observation. If `at` is all + only margeff will be available from the returned object. + + Note that if `exog` is specified, then marginal effects for all + variables not specified by `exog` are calculated using the `at` + option. + method : str, optional + Options are: + + - 'dydx' - dy/dx - No transformation is made and marginal effects + are returned. This is the default. + - 'eyex' - estimate elasticities of variables in `exog` -- + d(lny)/d(lnx) + - 'dyex' - estimate semi-elasticity -- dy/d(lnx) + - 'eydx' - estimate semi-elasticity -- d(lny)/dx + + Note that tranformations are done after each observation is + calculated. Semi-elasticities for binary variables are computed + using the midpoint method. 'dyex' and 'eyex' do not make sense + for discrete variables. For interpretations of these methods + see notes below. + atexog : array_like, optional + Optionally, you can provide the exogenous variables over which to + get the marginal effects. This should be a dictionary with the key + as the zero-indexed column number and the value of the dictionary. + Default is None for all independent variables less the constant. + dummy : bool, optional + If False, treats binary variables (if present) as continuous. This + is the default. Else if True, treats binary variables as + changing from 0 to 1. Note that any variable that is either 0 or 1 + is treated as binary. Each binary variable is treated separately + for now. + count : bool, optional + If False, treats count variables (if present) as continuous. This + is the default. Else if True, the marginal effect is the + change in probabilities when each observation is increased by one. + + Returns + ------- + DiscreteMargins : marginal effects instance + Returns an object that holds the marginal effects, standard + errors, confidence intervals, etc. See + `statsmodels.discrete.discrete_margins.DiscreteMargins` for more + information. + + Notes + ----- + Interpretations of methods: + + - 'dydx' - change in `endog` for a change in `exog`. + - 'eyex' - proportional change in `endog` for a proportional change + in `exog`. + - 'dyex' - change in `endog` for a proportional change in `exog`. + - 'eydx' - proportional change in `endog` for a change in `exog`. + + When using after Poisson, returns the expected number of events per + period, assuming that the model is loglinear. + + Status : unsupported features offset, exposure and weights. Default + handling of freq_weights for average effect "overall" might change. + + """ + if getattr(self.model, "offset", None) is not None: + raise NotImplementedError("Margins with offset are not available.") + if (np.any(self.model.var_weights != 1) or + np.any(self.model.freq_weights != 1)): + warnings.warn("weights are not taken into account by margeff") + from statsmodels.discrete.discrete_margins import DiscreteMargins + return DiscreteMargins(self, (at, method, atexog, dummy, count)) + + @Appender(base.LikelihoodModelResults.remove_data.__doc__) + def remove_data(self): + # GLM has alias/reference in result instance + self._data_attr.extend([i for i in self.model._data_attr + if '_data.' not in i]) + super(self.__class__, self).remove_data() + + # TODO: what are these in results? + self._endog = None + self._freq_weights = None + self._var_weights = None + self._iweights = None + self._n_trials = None + + @Appender(_plot_added_variable_doc % {'extra_params_doc': ''}) + def plot_added_variable(self, focus_exog, resid_type=None, + use_glm_weights=True, fit_kwargs=None, + ax=None): + + from statsmodels.graphics.regressionplots import plot_added_variable + + fig = plot_added_variable(self, focus_exog, + resid_type=resid_type, + use_glm_weights=use_glm_weights, + fit_kwargs=fit_kwargs, ax=ax) + + return fig + + @Appender(_plot_partial_residuals_doc % {'extra_params_doc': ''}) + def plot_partial_residuals(self, focus_exog, ax=None): + + from statsmodels.graphics.regressionplots import plot_partial_residuals + + return plot_partial_residuals(self, focus_exog, ax=ax) + + @Appender(_plot_ceres_residuals_doc % {'extra_params_doc': ''}) + def plot_ceres_residuals(self, focus_exog, frac=0.66, cond_means=None, + ax=None): + + from statsmodels.graphics.regressionplots import plot_ceres_residuals + + return plot_ceres_residuals(self, focus_exog, frac, + cond_means=cond_means, ax=ax) + + def summary(self, yname=None, xname=None, title=None, alpha=.05): + """ + Summarize the Regression Results + + Parameters + ---------- + yname : str, optional + Default is `y` + xname : list[str], optional + Names for the exogenous variables, default is `var_#` for ## in + the number of regressors. Must match the number of parameters in + the model + title : str, optional + Title for the top table. If not None, then this replaces the + default title + alpha : float + significance level for the confidence intervals + + Returns + ------- + smry : Summary instance + this holds the summary tables and text, which can be printed or + converted to various output formats. + + See Also + -------- + statsmodels.iolib.summary.Summary : class to hold summary results + """ + + top_left = [('Dep. Variable:', None), + ('Model:', None), + ('Model Family:', [self.family.__class__.__name__]), + ('Link Function:', [self.family.link.__class__.__name__]), + ('Method:', [self.method]), + ('Date:', None), + ('Time:', None), + ('No. Iterations:', + ["%d" % self.fit_history['iteration']]), + ] + + try: + prsquared = self.pseudo_rsquared(kind="cs") + except ValueError: + prsquared = np.nan + + top_right = [('No. Observations:', None), + ('Df Residuals:', None), + ('Df Model:', None), + ('Scale:', ["%#8.5g" % self.scale]), + ('Log-Likelihood:', None), + ('Deviance:', ["%#8.5g" % self.deviance]), + ('Pearson chi2:', ["%#6.3g" % self.pearson_chi2]), + ('Pseudo R-squ. (CS):', ["%#6.4g" % prsquared]) + ] + + if hasattr(self, 'cov_type'): + top_left.append(('Covariance Type:', [self.cov_type])) + + if title is None: + title = "Generalized Linear Model Regression Results" + + # create summary tables + from statsmodels.iolib.summary import Summary + smry = Summary() + smry.add_table_2cols(self, gleft=top_left, gright=top_right, + yname=yname, xname=xname, title=title) + smry.add_table_params(self, yname=yname, xname=xname, alpha=alpha, + use_t=self.use_t) + + if hasattr(self, 'constraints'): + smry.add_extra_txt(['Model has been estimated subject to linear ' + 'equality constraints.']) + return smry + + def summary2(self, yname=None, xname=None, title=None, alpha=.05, + float_format="%.4f"): + """Experimental summary for regression Results + + Parameters + ---------- + yname : str + Name of the dependent variable (optional) + xname : list[str], optional + Names for the exogenous variables, default is `var_#` for ## in + the number of regressors. Must match the number of parameters in + the model + title : str, optional + Title for the top table. If not None, then this replaces the + default title + alpha : float + significance level for the confidence intervals + float_format : str + print format for floats in parameters summary + + Returns + ------- + smry : Summary instance + this holds the summary tables and text, which can be printed or + converted to various output formats. + + See Also + -------- + statsmodels.iolib.summary2.Summary : class to hold summary results + """ + self.method = 'IRLS' + from statsmodels.iolib import summary2 + smry = summary2.Summary() + with warnings.catch_warnings(): + warnings.simplefilter("ignore", FutureWarning) + smry.add_base(results=self, alpha=alpha, float_format=float_format, + xname=xname, yname=yname, title=title) + if hasattr(self, 'constraints'): + smry.add_text('Model has been estimated subject to linear ' + 'equality constraints.') + + return smry + + +class GLMResultsWrapper(lm.RegressionResultsWrapper): + _attrs = { + 'resid_anscombe': 'rows', + 'resid_deviance': 'rows', + 'resid_pearson': 'rows', + 'resid_response': 'rows', + 'resid_working': 'rows' + } + _wrap_attrs = wrap.union_dicts(lm.RegressionResultsWrapper._wrap_attrs, + _attrs) + + +wrap.populate_wrapper(GLMResultsWrapper, GLMResults) + +if __name__ == "__main__": + from statsmodels.datasets import longley + data = longley.load() + # data.exog = add_constant(data.exog) + GLMmod = GLM(data.endog, data.exog).fit() + GLMT = GLMmod.summary(returns='tables') + # GLMT[0].extend_right(GLMT[1]) + # print(GLMT[0]) + # print(GLMT[2]) + GLMTp = GLMmod.summary(title='Test GLM') + """ +From Stata +. webuse beetle +. glm r i.beetle ldose, family(binomial n) link(cloglog) + +Iteration 0: log likelihood = -79.012269 +Iteration 1: log likelihood = -76.94951 +Iteration 2: log likelihood = -76.945645 +Iteration 3: log likelihood = -76.945645 + +Generalized linear models No. of obs = 24 +Optimization : ML Residual df = 20 + Scale parameter = 1 +Deviance = 73.76505595 (1/df) Deviance = 3.688253 +Pearson = 71.8901173 (1/df) Pearson = 3.594506 + +Variance function: V(u) = u*(1-u/n) [Binomial] +Link function : g(u) = ln(-ln(1-u/n)) [Complementary log-log] + + AIC = 6.74547 +Log likelihood = -76.94564525 BIC = 10.20398 + +------------------------------------------------------------------------------ + | OIM + r | Coef. Std. Err. z P>|z| [95% Conf. Interval] +-------------+---------------------------------------------------------------- + beetle | + 2 | -.0910396 .1076132 -0.85 0.398 -.3019576 .1198783 + 3 | -1.836058 .1307125 -14.05 0.000 -2.09225 -1.579867 + | + ldose | 19.41558 .9954265 19.50 0.000 17.46458 21.36658 + _cons | -34.84602 1.79333 -19.43 0.000 -38.36089 -31.33116 +------------------------------------------------------------------------------ +""" diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/genmod/qif.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/genmod/qif.py new file mode 100644 index 0000000000000000000000000000000000000000..cd3e540d38c9989aa100f62efce6cbb254d8316a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/genmod/qif.py @@ -0,0 +1,524 @@ +import numpy as np +from collections import defaultdict +import statsmodels.base.model as base +from statsmodels.genmod import families +from statsmodels.genmod.generalized_linear_model import GLM +from statsmodels.genmod.families import links +from statsmodels.genmod.families import varfuncs +import statsmodels.regression.linear_model as lm +import statsmodels.base.wrapper as wrap +from statsmodels.tools.decorators import cache_readonly + + +class QIFCovariance: + """ + A covariance model for quadratic inference function regression. + + The mat method returns a basis matrix B such that the inverse + of the working covariance lies in the linear span of the + basis matrices. + + Subclasses should set the number of basis matrices `num_terms`, + so that `mat(d, j)` for j=0, ..., num_terms-1 gives the basis + of dimension d.` + """ + + def mat(self, dim, term): + """ + Returns the term'th basis matrix, which is a dim x dim + matrix. + """ + raise NotImplementedError + + +class QIFIndependence(QIFCovariance): + """ + Independent working covariance for QIF regression. This covariance + model gives identical results to GEE with the independence working + covariance. When using QIFIndependence as the working covariance, + the QIF value will be zero, and cannot be used for chi^2 testing, or + for model selection using AIC, BIC, etc. + """ + + def __init__(self): + self.num_terms = 1 + + def mat(self, dim, term): + if term == 0: + return np.eye(dim) + else: + return None + + +class QIFExchangeable(QIFCovariance): + """ + Exchangeable working covariance for QIF regression. + """ + + def __init__(self): + self.num_terms = 2 + + def mat(self, dim, term): + if term == 0: + return np.eye(dim) + elif term == 1: + return np.ones((dim, dim)) + else: + return None + + +class QIFAutoregressive(QIFCovariance): + """ + Autoregressive working covariance for QIF regression. + """ + + def __init__(self): + self.num_terms = 3 + + def mat(self, dim, term): + + if dim < 3: + msg = ("Groups must have size at least 3 for " + + "autoregressive covariance.") + raise ValueError(msg) + + if term == 0: + return np.eye(dim) + elif term == 1: + mat = np.zeros((dim, dim)) + mat.flat[1::(dim+1)] = 1 + mat += mat.T + return mat + elif term == 2: + mat = np.zeros((dim, dim)) + mat[0, 0] = 1 + mat[dim-1, dim-1] = 1 + return mat + else: + return None + + +class QIF(base.Model): + """ + Fit a regression model using quadratic inference functions (QIF). + + QIF is an alternative to GEE that can be more efficient, and that + offers different approaches for model selection and inference. + + Parameters + ---------- + endog : array_like + The dependent variables of the regression. + exog : array_like + The independent variables of the regression. + groups : array_like + Labels indicating which group each observation belongs to. + Observations in different groups should be independent. + family : genmod family + An instance of a GLM family. + cov_struct : QIFCovariance instance + An instance of a QIFCovariance. + + References + ---------- + A. Qu, B. Lindsay, B. Li (2000). Improving Generalized Estimating + Equations using Quadratic Inference Functions, Biometrika 87:4. + www.jstor.org/stable/2673612 + """ + + def __init__(self, endog, exog, groups, family=None, + cov_struct=None, missing='none', **kwargs): + + # Handle the family argument + if family is None: + family = families.Gaussian() + else: + if not issubclass(family.__class__, families.Family): + raise ValueError("QIF: `family` must be a genmod " + "family instance") + self.family = family + + self._fit_history = defaultdict(list) + + # Handle the cov_struct argument + if cov_struct is None: + cov_struct = QIFIndependence() + else: + if not isinstance(cov_struct, QIFCovariance): + raise ValueError( + "QIF: `cov_struct` must be a QIFCovariance instance") + self.cov_struct = cov_struct + + groups = np.asarray(groups) + + super().__init__( + endog, exog, groups=groups, missing=missing, **kwargs + ) + + self.group_names = list(set(groups)) + self.nobs = len(self.endog) + + groups_ix = defaultdict(list) + for i, g in enumerate(groups): + groups_ix[g].append(i) + self.groups_ix = [groups_ix[na] for na in self.group_names] + + self._check_args(groups) + + def _check_args(self, groups): + + if len(groups) != len(self.endog): + msg = "QIF: groups and endog should have the same length" + raise ValueError(msg) + + if len(self.endog) != self.exog.shape[0]: + msg = ("QIF: the length of endog should be equal to the " + "number of rows of exog.") + raise ValueError(msg) + + def objective(self, params): + """ + Calculate the gradient of the QIF objective function. + + Parameters + ---------- + params : array_like + The model parameters at which the gradient is evaluated. + + Returns + ------- + grad : array_like + The gradient vector of the QIF objective function. + gn_deriv : array_like + The gradients of each estimating equation with + respect to the parameter. + """ + + endog = self.endog + exog = self.exog + lpr = np.dot(exog, params) + mean = self.family.link.inverse(lpr) + va = self.family.variance(mean) + + # Mean derivative + idl = self.family.link.inverse_deriv(lpr) + idl2 = self.family.link.inverse_deriv2(lpr) + vd = self.family.variance.deriv(mean) + + m = self.cov_struct.num_terms + p = exog.shape[1] + + d = p * m + gn = np.zeros(d) + gi = np.zeros(d) + gi_deriv = np.zeros((d, p)) + gn_deriv = np.zeros((d, p)) + cn_deriv = [0] * p + cmat = np.zeros((d, d)) + + fastvar = self.family.variance is varfuncs.constant + fastlink = isinstance( + self.family.link, + # TODO: Remove links.identity after deprecation final + (links.Identity, links.identity) + ) + + for ix in self.groups_ix: + sd = np.sqrt(va[ix]) + resid = endog[ix] - mean[ix] + sresid = resid / sd + deriv = exog[ix, :] * idl[ix, None] + + jj = 0 + for j in range(m): + # The derivative of each term in (5) of Qu et al. + # There are four terms involving beta in a product. + # Iterated application of the product rule gives + # the gradient as a sum of four terms. + c = self.cov_struct.mat(len(ix), j) + crs1 = np.dot(c, sresid) / sd + gi[jj:jj+p] = np.dot(deriv.T, crs1) + crs2 = np.dot(c, -deriv / sd[:, None]) / sd[:, None] + gi_deriv[jj:jj+p, :] = np.dot(deriv.T, crs2) + if not (fastlink and fastvar): + for k in range(p): + m1 = np.dot(exog[ix, :].T, + idl2[ix] * exog[ix, k] * crs1) + if not fastvar: + vx = -0.5 * vd[ix] * deriv[:, k] / va[ix]**1.5 + m2 = np.dot(deriv.T, vx * np.dot(c, sresid)) + m3 = np.dot(deriv.T, np.dot(c, vx * resid) / sd) + else: + m2, m3 = 0, 0 + gi_deriv[jj:jj+p, k] += m1 + m2 + m3 + jj += p + + for j in range(p): + u = np.outer(gi, gi_deriv[:, j]) + cn_deriv[j] += u + u.T + + gn += gi + gn_deriv += gi_deriv + + cmat += np.outer(gi, gi) + + ngrp = len(self.groups_ix) + gn /= ngrp + gn_deriv /= ngrp + cmat /= ngrp**2 + + qif = np.dot(gn, np.linalg.solve(cmat, gn)) + + gcg = np.zeros(p) + for j in range(p): + cn_deriv[j] /= len(self.groups_ix)**2 + u = np.linalg.solve(cmat, cn_deriv[j]).T + u = np.linalg.solve(cmat, u) + gcg[j] = np.dot(gn, np.dot(u, gn)) + + grad = 2 * np.dot(gn_deriv.T, np.linalg.solve(cmat, gn)) - gcg + + return qif, grad, cmat, gn, gn_deriv + + def estimate_scale(self, params): + """ + Estimate the dispersion/scale. + + The scale parameter for binomial and Poisson families is + fixed at 1, otherwise it is estimated from the data. + """ + + if isinstance(self.family, (families.Binomial, families.Poisson)): + return 1. + + if hasattr(self, "ddof_scale"): + ddof_scale = self.ddof_scale + else: + ddof_scale = self.exog[1] + + lpr = np.dot(self.exog, params) + mean = self.family.link.inverse(lpr) + resid = self.endog - mean + scale = np.sum(resid**2) / (self.nobs - ddof_scale) + + return scale + + @classmethod + def from_formula(cls, formula, groups, data, subset=None, + *args, **kwargs): + """ + Create a QIF model instance from a formula and dataframe. + + Parameters + ---------- + formula : str or generic Formula object + The formula specifying the model + groups : array_like or string + Array of grouping labels. If a string, this is the name + of a variable in `data` that contains the grouping labels. + data : array_like + The data for the model. + subset : array_like + An array_like object of booleans, integers, or index + values that indicate the subset of the data to used when + fitting the model. + + Returns + ------- + model : QIF model instance + """ + + if isinstance(groups, str): + groups = data[groups] + + model = super().from_formula( + formula, data=data, subset=subset, + groups=groups, *args, **kwargs) + + return model + + def fit(self, maxiter=100, start_params=None, tol=1e-6, gtol=1e-4, + ddof_scale=None): + """ + Fit a GLM to correlated data using QIF. + + Parameters + ---------- + maxiter : int + Maximum number of iterations. + start_params : array_like, optional + Starting values + tol : float + Convergence threshold for difference of successive + estimates. + gtol : float + Convergence threshold for gradient. + ddof_scale : int, optional + Degrees of freedom for the scale parameter + + Returns + ------- + QIFResults object + """ + + if ddof_scale is None: + self.ddof_scale = self.exog.shape[1] + else: + self.ddof_scale = ddof_scale + + if start_params is None: + model = GLM(self.endog, self.exog, family=self.family) + result = model.fit() + params = result.params + else: + params = start_params + + for _ in range(maxiter): + + qif, grad, cmat, _, gn_deriv = self.objective(params) + + gnorm = np.sqrt(np.sum(grad * grad)) + self._fit_history["qif"].append(qif) + self._fit_history["gradnorm"].append(gnorm) + + if gnorm < gtol: + break + + cjac = 2 * np.dot(gn_deriv.T, np.linalg.solve(cmat, gn_deriv)) + step = np.linalg.solve(cjac, grad) + + snorm = np.sqrt(np.sum(step * step)) + self._fit_history["stepnorm"].append(snorm) + if snorm < tol: + break + params -= step + + vcov = np.dot(gn_deriv.T, np.linalg.solve(cmat, gn_deriv)) + vcov = np.linalg.inv(vcov) + scale = self.estimate_scale(params) + + rslt = QIFResults(self, params, vcov / scale, scale) + rslt.fit_history = self._fit_history + self._fit_history = defaultdict(list) + + return QIFResultsWrapper(rslt) + + +class QIFResults(base.LikelihoodModelResults): + """Results class for QIF Regression""" + def __init__(self, model, params, cov_params, scale, + use_t=False, **kwds): + + super().__init__( + model, params, normalized_cov_params=cov_params, + scale=scale) + + self.qif, _, _, _, _ = self.model.objective(params) + + @cache_readonly + def aic(self): + """ + An AIC-like statistic for models fit using QIF. + """ + if isinstance(self.model.cov_struct, QIFIndependence): + msg = "AIC not available with QIFIndependence covariance" + raise ValueError(msg) + df = self.model.exog.shape[1] + return self.qif + 2*df + + @cache_readonly + def bic(self): + """ + A BIC-like statistic for models fit using QIF. + """ + if isinstance(self.model.cov_struct, QIFIndependence): + msg = "BIC not available with QIFIndependence covariance" + raise ValueError(msg) + df = self.model.exog.shape[1] + return self.qif + np.log(self.model.nobs)*df + + @cache_readonly + def fittedvalues(self): + """ + Returns the fitted values from the model. + """ + return self.model.family.link.inverse( + np.dot(self.model.exog, self.params)) + + def summary(self, yname=None, xname=None, title=None, alpha=.05): + """ + Summarize the QIF regression results + + Parameters + ---------- + yname : str, optional + Default is `y` + xname : list[str], optional + Names for the exogenous variables, default is `var_#` for ## in + the number of regressors. Must match the number of parameters in + the model + title : str, optional + Title for the top table. If not None, then this replaces + the default title + alpha : float + significance level for the confidence intervals + + Returns + ------- + smry : Summary instance + this holds the summary tables and text, which can be + printed or converted to various output formats. + + See Also + -------- + statsmodels.iolib.summary.Summary : class to hold summary results + """ + + top_left = [('Dep. Variable:', None), + ('Method:', ['QIF']), + ('Family:', [self.model.family.__class__.__name__]), + ('Covariance structure:', + [self.model.cov_struct.__class__.__name__]), + ('Date:', None), + ('Time:', None), + ] + + NY = [len(y) for y in self.model.groups_ix] + + top_right = [('No. Observations:', [sum(NY)]), + ('No. clusters:', [len(NY)]), + ('Min. cluster size:', [min(NY)]), + ('Max. cluster size:', [max(NY)]), + ('Mean cluster size:', ["%.1f" % np.mean(NY)]), + ('Scale:', ["%.3f" % self.scale]), + ] + + if title is None: + title = self.model.__class__.__name__ + ' ' +\ + "Regression Results" + + # Override the exog variable names if xname is provided as an + # argument. + if xname is None: + xname = self.model.exog_names + + if yname is None: + yname = self.model.endog_names + + # Create summary table instance + from statsmodels.iolib.summary import Summary + smry = Summary() + smry.add_table_2cols(self, gleft=top_left, gright=top_right, + yname=yname, xname=xname, + title=title) + smry.add_table_params(self, yname=yname, xname=xname, + alpha=alpha, use_t=False) + + return smry + + +class QIFResultsWrapper(lm.RegressionResultsWrapper): + pass + + +wrap.populate_wrapper(QIFResultsWrapper, QIFResults) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..691559ca60fe92a39e770cdb5d16c42a4c5651e1 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/__init__.py @@ -0,0 +1,3 @@ +from statsmodels.tools._test_runner import PytestTester + +test = PytestTester() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/_regressionplots_doc.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/_regressionplots_doc.py new file mode 100644 index 0000000000000000000000000000000000000000..59bac854a78a5d1c33d49a4025ce629d42f14840 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/_regressionplots_doc.py @@ -0,0 +1,220 @@ +_plot_added_variable_doc = """\ + Create an added variable plot for a fitted regression model. + + Parameters + ---------- + %(extra_params_doc)sfocus_exog : int or string + The column index of exog, or a variable name, indicating the + variable whose role in the regression is to be assessed. + resid_type : str + The type of residuals to use for the dependent variable. If + None, uses `resid_deviance` for GLM/GEE and `resid` otherwise. + use_glm_weights : bool + Only used if the model is a GLM or GEE. If True, the + residuals for the focus predictor are computed using WLS, with + the weights obtained from the IRLS calculations for fitting + the GLM. If False, unweighted regression is used. + fit_kwargs : dict, optional + Keyword arguments to be passed to fit when refitting the + model. + ax: Axes + Matplotlib Axes instance + + Returns + ------- + Figure + A matplotlib figure instance. +""" + +_plot_partial_residuals_doc = """\ + Create a partial residual, or 'component plus residual' plot for a + fitted regression model. + + Parameters + ---------- + %(extra_params_doc)sfocus_exog : int or string + The column index of exog, or variable name, indicating the + variable whose role in the regression is to be assessed. + ax: Axes + Matplotlib Axes instance + + Returns + ------- + Figure + A matplotlib figure instance. +""" + +_plot_ceres_residuals_doc = """\ + Conditional Expectation Partial Residuals (CERES) plot. + + Produce a CERES plot for a fitted regression model. + + Parameters + ---------- + %(extra_params_doc)s + focus_exog : {int, str} + The column index of results.model.exog, or the variable name, + indicating the variable whose role in the regression is to be + assessed. + frac : float + Lowess tuning parameter for the adjusted model used in the + CERES analysis. Not used if `cond_means` is provided. + cond_means : array_like, optional + If provided, the columns of this array span the space of the + conditional means E[exog | focus exog], where exog ranges over + some or all of the columns of exog (other than the focus exog). + ax : matplotlib.Axes instance, optional + The axes on which to draw the plot. If not provided, a new + axes instance is created. + + Returns + ------- + Figure + The figure on which the partial residual plot is drawn. + + Notes + ----- + `cond_means` is intended to capture the behavior of E[x1 | + x2], where x2 is the focus exog and x1 are all the other exog + variables. If all the conditional mean relationships are + linear, it is sufficient to set cond_means equal to the focus + exog. Alternatively, cond_means may consist of one or more + columns containing functional transformations of the focus + exog (e.g. x2^2) that are thought to capture E[x1 | x2]. + + If nothing is known or suspected about the form of E[x1 | x2], + set `cond_means` to None, and it will be estimated by + smoothing each non-focus exog against the focus exog. The + values of `frac` control these lowess smooths. + + If cond_means contains only the focus exog, the results are + equivalent to a partial residual plot. + + If the focus variable is believed to be independent of the + other exog variables, `cond_means` can be set to an (empty) + nx0 array. + + References + ---------- + .. [1] RD Cook and R Croos-Dabrera (1998). Partial residual plots + in generalized linear models. Journal of the American + Statistical Association, 93:442. + + .. [2] RD Cook (1993). Partial residual plots. Technometrics 35:4. + + Examples + -------- + Using a model built from the the state crime dataset, make a CERES plot with + the rate of Poverty as the focus variable. + + >>> import statsmodels.api as sm + >>> import matplotlib.pyplot as plt + >>> import statsmodels.formula.api as smf + >>> from statsmodels.graphics.regressionplots import plot_ceres_residuals + + >>> crime_data = sm.datasets.statecrime.load_pandas() + >>> results = smf.ols('murder ~ hs_grad + urban + poverty + single', + ... data=crime_data.data).fit() + >>> plot_ceres_residuals(results, 'poverty') + >>> plt.show() + + .. plot:: plots/graphics_regression_ceres_residuals.py +""" + + +_plot_influence_doc = """\ + Plot of influence in regression. Plots studentized resids vs. leverage. + + Parameters + ---------- + {extra_params_doc} + external : bool + Whether to use externally or internally studentized residuals. It is + recommended to leave external as True. + alpha : float + The alpha value to identify large studentized residuals. Large means + abs(resid_studentized) > t.ppf(1-alpha/2, dof=results.df_resid) + criterion : str {{'DFFITS', 'Cooks'}} + Which criterion to base the size of the points on. Options are + DFFITS or Cook's D. + size : float + The range of `criterion` is mapped to 10**2 - size**2 in points. + plot_alpha : float + The `alpha` of the plotted points. + ax : AxesSubplot + An instance of a matplotlib Axes. + **kwargs + Additional parameters passed through to `plot`. + + Returns + ------- + Figure + The matplotlib figure that contains the Axes. + + Notes + ----- + Row labels for the observations in which the leverage, measured by the + diagonal of the hat matrix, is high or the residuals are large, as the + combination of large residuals and a high influence value indicates an + influence point. The value of large residuals can be controlled using the + `alpha` parameter. Large leverage points are identified as + hat_i > 2 * (df_model + 1)/nobs. + + Examples + -------- + Using a model built from the the state crime dataset, plot the influence in + regression. Observations with high leverage, or large residuals will be + labeled in the plot to show potential influence points. + + >>> import statsmodels.api as sm + >>> import matplotlib.pyplot as plt + >>> import statsmodels.formula.api as smf + + >>> crime_data = sm.datasets.statecrime.load_pandas() + >>> results = smf.ols('murder ~ hs_grad + urban + poverty + single', + ... data=crime_data.data).fit() + >>> sm.graphics.influence_plot(results) + >>> plt.show() + + .. plot:: plots/graphics_regression_influence.py + """ + + +_plot_leverage_resid2_doc = """\ + Plot leverage statistics vs. normalized residuals squared + + Parameters + ---------- + results : results instance + A regression results instance + alpha : float + Specifies the cut-off for large-standardized residuals. Residuals + are assumed to be distributed N(0, 1) with alpha=alpha. + ax : Axes + Matplotlib Axes instance + **kwargs + Additional parameters passed the plot command. + + Returns + ------- + Figure + A matplotlib figure instance. + + Examples + -------- + Using a model built from the the state crime dataset, plot the leverage + statistics vs. normalized residuals squared. Observations with + Large-standardized Residuals will be labeled in the plot. + + >>> import statsmodels.api as sm + >>> import matplotlib.pyplot as plt + >>> import statsmodels.formula.api as smf + + >>> crime_data = sm.datasets.statecrime.load_pandas() + >>> results = smf.ols('murder ~ hs_grad + urban + poverty + single', + ... data=crime_data.data).fit() + >>> sm.graphics.plot_leverage_resid2(results) + >>> plt.show() + + .. plot:: plots/graphics_regression_leverage_resid2.py + """ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/agreement.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/agreement.py new file mode 100644 index 0000000000000000000000000000000000000000..83c40cd8c6eeef7b22357f81d4e999ace4cbafef --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/agreement.py @@ -0,0 +1,154 @@ +''' +Bland-Altman mean-difference plots + +Author: Joses Ho +License: BSD-3 +''' + +import numpy as np + +from . import utils + + +def mean_diff_plot(m1, m2, sd_limit=1.96, ax=None, scatter_kwds=None, + mean_line_kwds=None, limit_lines_kwds=None): + """ + Construct a Tukey/Bland-Altman Mean Difference Plot. + + Tukey's Mean Difference Plot (also known as a Bland-Altman plot) is a + graphical method to analyze the differences between two methods of + measurement. The mean of the measures is plotted against their difference. + + For more information see + https://en.wikipedia.org/wiki/Bland-Altman_plot + + Parameters + ---------- + m1 : array_like + A 1-d array. + m2 : array_like + A 1-d array. + sd_limit : float + The limit of agreements expressed in terms of the standard deviation of + the differences. If `md` is the mean of the differences, and `sd` is + the standard deviation of those differences, then the limits of + agreement that will be plotted are md +/- sd_limit * sd. + The default of 1.96 will produce 95% confidence intervals for the means + of the differences. If sd_limit = 0, no limits will be plotted, and + the ylimit of the plot defaults to 3 standard deviations on either + side of the mean. + ax : AxesSubplot + If `ax` is None, then a figure is created. If an axis instance is + given, the mean difference plot is drawn on the axis. + scatter_kwds : dict + Options to to style the scatter plot. Accepts any keywords for the + matplotlib Axes.scatter plotting method + mean_line_kwds : dict + Options to to style the scatter plot. Accepts any keywords for the + matplotlib Axes.axhline plotting method + limit_lines_kwds : dict + Options to to style the scatter plot. Accepts any keywords for the + matplotlib Axes.axhline plotting method + + Returns + ------- + Figure + If `ax` is None, the created figure. Otherwise the figure to which + `ax` is connected. + + References + ---------- + Bland JM, Altman DG (1986). "Statistical methods for assessing agreement + between two methods of clinical measurement" + + Examples + -------- + + Load relevant libraries. + + >>> import statsmodels.api as sm + >>> import numpy as np + >>> import matplotlib.pyplot as plt + + Making a mean difference plot. + + >>> # Seed the random number generator. + >>> # This ensures that the results below are reproducible. + >>> np.random.seed(9999) + >>> m1 = np.random.random(20) + >>> m2 = np.random.random(20) + >>> f, ax = plt.subplots(1, figsize = (8,5)) + >>> sm.graphics.mean_diff_plot(m1, m2, ax = ax) + >>> plt.show() + + .. plot:: plots/graphics-mean_diff_plot.py + """ + fig, ax = utils.create_mpl_ax(ax) + + if len(m1) != len(m2): + raise ValueError('m1 does not have the same length as m2.') + if sd_limit < 0: + raise ValueError(f'sd_limit ({sd_limit}) is less than 0.') + + means = np.mean([m1, m2], axis=0) + diffs = m1 - m2 + mean_diff = np.mean(diffs) + std_diff = np.std(diffs, axis=0) + + scatter_kwds = scatter_kwds or {} + if 's' not in scatter_kwds: + scatter_kwds['s'] = 20 + mean_line_kwds = mean_line_kwds or {} + limit_lines_kwds = limit_lines_kwds or {} + for kwds in [mean_line_kwds, limit_lines_kwds]: + if 'color' not in kwds: + kwds['color'] = 'gray' + if 'linewidth' not in kwds: + kwds['linewidth'] = 1 + if 'linestyle' not in mean_line_kwds: + kwds['linestyle'] = '--' + if 'linestyle' not in limit_lines_kwds: + kwds['linestyle'] = ':' + + ax.scatter(means, diffs, **scatter_kwds) # Plot the means against the diffs. + ax.axhline(mean_diff, **mean_line_kwds) # draw mean line. + + # Annotate mean line with mean difference. + ax.annotate(f'mean diff:\n{np.round(mean_diff, 2)}', + xy=(0.99, 0.5), + horizontalalignment='right', + verticalalignment='center', + fontsize=14, + xycoords='axes fraction') + + if sd_limit > 0: + half_ylim = (1.5 * sd_limit) * std_diff + ax.set_ylim(mean_diff - half_ylim, + mean_diff + half_ylim) + limit_of_agreement = sd_limit * std_diff + lower = mean_diff - limit_of_agreement + upper = mean_diff + limit_of_agreement + for j, lim in enumerate([lower, upper]): + ax.axhline(lim, **limit_lines_kwds) + ax.annotate(f'-{sd_limit} SD: {lower:0.2g}', + xy=(0.99, 0.07), + horizontalalignment='right', + verticalalignment='bottom', + fontsize=14, + xycoords='axes fraction') + ax.annotate(f'+{sd_limit} SD: {upper:0.2g}', + xy=(0.99, 0.92), + horizontalalignment='right', + fontsize=14, + xycoords='axes fraction') + + elif sd_limit == 0: + half_ylim = 3 * std_diff + ax.set_ylim(mean_diff - half_ylim, + mean_diff + half_ylim) + + ax.set_ylabel('Difference', fontsize=15) + ax.set_xlabel('Means', fontsize=15) + ax.tick_params(labelsize=13) + fig.tight_layout() + return fig diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/api.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/api.py new file mode 100644 index 0000000000000000000000000000000000000000..b5ae388f20820c08b2f9529314049db715eaa196 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/api.py @@ -0,0 +1,43 @@ +from . import tsaplots as tsa +from .agreement import mean_diff_plot +from .boxplots import beanplot, violinplot +from .correlation import plot_corr, plot_corr_grid +from .factorplots import interaction_plot +from .functional import fboxplot, hdrboxplot, rainbowplot +from .gofplots import qqplot +from .plottools import rainbow +from .regressionplots import ( + abline_plot, + influence_plot, + plot_ccpr, + plot_ccpr_grid, + plot_fit, + plot_leverage_resid2, + plot_partregress, + plot_partregress_grid, + plot_regress_exog, +) + +__all__ = [ + "abline_plot", + "beanplot", + "fboxplot", + "hdrboxplot", + "influence_plot", + "interaction_plot", + "mean_diff_plot", + "plot_ccpr", + "plot_ccpr_grid", + "plot_corr", + "plot_corr_grid", + "plot_fit", + "plot_leverage_resid2", + "plot_partregress", + "plot_partregress_grid", + "plot_regress_exog", + "qqplot", + "rainbow", + "rainbowplot", + "tsa", + "violinplot", +] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/boxplots.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/boxplots.py new file mode 100644 index 0000000000000000000000000000000000000000..2b856e8dbd907748bc3e62d5862bb7d995ca1d97 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/boxplots.py @@ -0,0 +1,423 @@ +"""Variations on boxplots.""" + +# Author: Ralf Gommers +# Based on code by Flavio Coelho and Teemu Ikonen. + +import numpy as np +from scipy.stats import gaussian_kde + +from . import utils + +__all__ = ['violinplot', 'beanplot'] + + +def violinplot(data, ax=None, labels=None, positions=None, side='both', + show_boxplot=True, plot_opts=None): + """ + Make a violin plot of each dataset in the `data` sequence. + + A violin plot is a boxplot combined with a kernel density estimate of the + probability density function per point. + + Parameters + ---------- + data : sequence[array_like] + Data arrays, one array per value in `positions`. + ax : AxesSubplot, optional + If given, this subplot is used to plot in instead of a new figure being + created. + labels : list[str], optional + Tick labels for the horizontal axis. If not given, integers + ``1..len(data)`` are used. + positions : array_like, optional + Position array, used as the horizontal axis of the plot. If not given, + spacing of the violins will be equidistant. + side : {'both', 'left', 'right'}, optional + How to plot the violin. Default is 'both'. The 'left', 'right' + options can be used to create asymmetric violin plots. + show_boxplot : bool, optional + Whether or not to show normal box plots on top of the violins. + Default is True. + plot_opts : dict, optional + A dictionary with plotting options. Any of the following can be + provided, if not present in `plot_opts` the defaults will be used:: + + - 'violin_fc', MPL color. Fill color for violins. Default is 'y'. + - 'violin_ec', MPL color. Edge color for violins. Default is 'k'. + - 'violin_lw', scalar. Edge linewidth for violins. Default is 1. + - 'violin_alpha', float. Transparancy of violins. Default is 0.5. + - 'cutoff', bool. If True, limit violin range to data range. + Default is False. + - 'cutoff_val', scalar. Where to cut off violins if `cutoff` is + True. Default is 1.5 standard deviations. + - 'cutoff_type', {'std', 'abs'}. Whether cutoff value is absolute, + or in standard deviations. Default is 'std'. + - 'violin_width' : float. Relative width of violins. Max available + space is 1, default is 0.8. + - 'label_fontsize', MPL fontsize. Adjusts fontsize only if given. + - 'label_rotation', scalar. Adjusts label rotation only if given. + Specify in degrees. + - 'bw_factor', Adjusts the scipy gaussian_kde kernel. default: None. + Options for scalar or callable. + + Returns + ------- + Figure + If `ax` is None, the created figure. Otherwise the figure to which + `ax` is connected. + + See Also + -------- + beanplot : Bean plot, builds on `violinplot`. + matplotlib.pyplot.boxplot : Standard boxplot. + + Notes + ----- + The appearance of violins can be customized with `plot_opts`. If + customization of boxplot elements is required, set `show_boxplot` to False + and plot it on top of the violins by calling the Matplotlib `boxplot` + function directly. For example:: + + violinplot(data, ax=ax, show_boxplot=False) + ax.boxplot(data, sym='cv', whis=2.5) + + It can happen that the axis labels or tick labels fall outside the plot + area, especially with rotated labels on the horizontal axis. With + Matplotlib 1.1 or higher, this can easily be fixed by calling + ``ax.tight_layout()``. With older Matplotlib one has to use ``plt.rc`` or + ``plt.rcParams`` to fix this, for example:: + + plt.rc('figure.subplot', bottom=0.25) + violinplot(data, ax=ax) + + References + ---------- + J.L. Hintze and R.D. Nelson, "Violin Plots: A Box Plot-Density Trace + Synergism", The American Statistician, Vol. 52, pp.181-84, 1998. + + Examples + -------- + We use the American National Election Survey 1996 dataset, which has Party + Identification of respondents as independent variable and (among other + data) age as dependent variable. + + >>> data = sm.datasets.anes96.load_pandas() + >>> party_ID = np.arange(7) + >>> labels = ["Strong Democrat", "Weak Democrat", "Independent-Democrat", + ... "Independent-Indpendent", "Independent-Republican", + ... "Weak Republican", "Strong Republican"] + + Group age by party ID, and create a violin plot with it: + + >>> plt.rcParams['figure.subplot.bottom'] = 0.23 # keep labels visible + >>> age = [data.exog['age'][data.endog == id] for id in party_ID] + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111) + >>> sm.graphics.violinplot(age, ax=ax, labels=labels, + ... plot_opts={'cutoff_val':5, 'cutoff_type':'abs', + ... 'label_fontsize':'small', + ... 'label_rotation':30}) + >>> ax.set_xlabel("Party identification of respondent.") + >>> ax.set_ylabel("Age") + >>> plt.show() + + .. plot:: plots/graphics_boxplot_violinplot.py + """ + plot_opts = {} if plot_opts is None else plot_opts + if max([np.size(arr) for arr in data]) == 0: + msg = "No Data to make Violin: Try again!" + raise ValueError(msg) + + fig, ax = utils.create_mpl_ax(ax) + + data = list(map(np.asarray, data)) + if positions is None: + positions = np.arange(len(data)) + 1 + + # Determine available horizontal space for each individual violin. + pos_span = np.max(positions) - np.min(positions) + width = np.min([0.15 * np.max([pos_span, 1.]), + plot_opts.get('violin_width', 0.8) / 2.]) + + # Plot violins. + for pos_data, pos in zip(data, positions): + _single_violin(ax, pos, pos_data, width, side, plot_opts) + + if show_boxplot: + try: + ax.boxplot(data, notch=1, positions=positions, orientation="vertical") + except TypeError: + # Deprecated in MPL 3.10 + ax.boxplot(data, notch=1, positions=positions, vert=1) + + # Set ticks and tick labels of horizontal axis. + _set_ticks_labels(ax, data, labels, positions, plot_opts) + + return fig + + +def _single_violin(ax, pos, pos_data, width, side, plot_opts): + """""" + bw_factor = plot_opts.get('bw_factor', None) + + def _violin_range(pos_data, plot_opts): + """Return array with correct range, with which violins can be plotted.""" + cutoff = plot_opts.get('cutoff', False) + cutoff_type = plot_opts.get('cutoff_type', 'std') + cutoff_val = plot_opts.get('cutoff_val', 1.5) + + s = 0.0 + if not cutoff: + if cutoff_type == 'std': + s = cutoff_val * np.std(pos_data) + else: + s = cutoff_val + + x_lower = kde.dataset.min() - s + x_upper = kde.dataset.max() + s + return np.linspace(x_lower, x_upper, 100) + + pos_data = np.asarray(pos_data) + # Kernel density estimate for data at this position. + kde = gaussian_kde(pos_data, bw_method=bw_factor) + + # Create violin for pos, scaled to the available space. + xvals = _violin_range(pos_data, plot_opts) + violin = kde.evaluate(xvals) + violin = width * violin / violin.max() + + if side == 'both': + envelope_l, envelope_r = (-violin + pos, violin + pos) + elif side == 'right': + envelope_l, envelope_r = (pos, violin + pos) + elif side == 'left': + envelope_l, envelope_r = (-violin + pos, pos) + else: + msg = "`side` parameter should be one of {'left', 'right', 'both'}." + raise ValueError(msg) + + # Draw the violin. + ax.fill_betweenx(xvals, envelope_l, envelope_r, + facecolor=plot_opts.get('violin_fc', '#66c2a5'), + edgecolor=plot_opts.get('violin_ec', 'k'), + lw=plot_opts.get('violin_lw', 1), + alpha=plot_opts.get('violin_alpha', 0.5)) + + return xvals, violin + + +def _set_ticks_labels(ax, data, labels, positions, plot_opts): + """Set ticks and labels on horizontal axis.""" + + # Set xticks and limits. + ax.set_xlim([np.min(positions) - 0.5, np.max(positions) + 0.5]) + ax.set_xticks(positions) + + label_fontsize = plot_opts.get('label_fontsize') + label_rotation = plot_opts.get('label_rotation') + if label_fontsize or label_rotation: + from matplotlib.artist import setp + + if labels is not None: + if not len(labels) == len(data): + msg = "Length of `labels` should equal length of `data`." + raise ValueError(msg) + + xticknames = ax.set_xticklabels(labels) + if label_fontsize: + setp(xticknames, fontsize=label_fontsize) + + if label_rotation: + setp(xticknames, rotation=label_rotation) + + return + + +def beanplot(data, ax=None, labels=None, positions=None, side='both', + jitter=False, plot_opts={}): + """ + Bean plot of each dataset in a sequence. + + A bean plot is a combination of a `violinplot` (kernel density estimate of + the probability density function per point) with a line-scatter plot of all + individual data points. + + Parameters + ---------- + data : sequence[array_like] + Data arrays, one array per value in `positions`. + ax : AxesSubplot + If given, this subplot is used to plot in instead of a new figure being + created. + labels : list[str], optional + Tick labels for the horizontal axis. If not given, integers + ``1..len(data)`` are used. + positions : array_like, optional + Position array, used as the horizontal axis of the plot. If not given, + spacing of the violins will be equidistant. + side : {'both', 'left', 'right'}, optional + How to plot the violin. Default is 'both'. The 'left', 'right' + options can be used to create asymmetric violin plots. + jitter : bool, optional + If True, jitter markers within violin instead of plotting regular lines + around the center. This can be useful if the data is very dense. + plot_opts : dict, optional + A dictionary with plotting options. All the options for `violinplot` + can be specified, they will simply be passed to `violinplot`. Options + specific to `beanplot` are: + + - 'violin_width' : float. Relative width of violins. Max available + space is 1, default is 0.8. + - 'bean_color', MPL color. Color of bean plot lines. Default is 'k'. + Also used for jitter marker edge color if `jitter` is True. + - 'bean_size', scalar. Line length as a fraction of maximum length. + Default is 0.5. + - 'bean_lw', scalar. Linewidth, default is 0.5. + - 'bean_show_mean', bool. If True (default), show mean as a line. + - 'bean_show_median', bool. If True (default), show median as a + marker. + - 'bean_mean_color', MPL color. Color of mean line. Default is 'b'. + - 'bean_mean_lw', scalar. Linewidth of mean line, default is 2. + - 'bean_mean_size', scalar. Line length as a fraction of maximum length. + Default is 0.5. + - 'bean_median_color', MPL color. Color of median marker. Default + is 'r'. + - 'bean_median_marker', MPL marker. Marker type, default is '+'. + - 'jitter_marker', MPL marker. Marker type for ``jitter=True``. + Default is 'o'. + - 'jitter_marker_size', int. Marker size. Default is 4. + - 'jitter_fc', MPL color. Jitter marker face color. Default is None. + - 'bean_legend_text', str. If given, add a legend with given text. + + Returns + ------- + Figure + If `ax` is None, the created figure. Otherwise the figure to which + `ax` is connected. + + See Also + -------- + violinplot : Violin plot, also used internally in `beanplot`. + matplotlib.pyplot.boxplot : Standard boxplot. + + References + ---------- + P. Kampstra, "Beanplot: A Boxplot Alternative for Visual Comparison of + Distributions", J. Stat. Soft., Vol. 28, pp. 1-9, 2008. + + Examples + -------- + We use the American National Election Survey 1996 dataset, which has Party + Identification of respondents as independent variable and (among other + data) age as dependent variable. + + >>> data = sm.datasets.anes96.load_pandas() + >>> party_ID = np.arange(7) + >>> labels = ["Strong Democrat", "Weak Democrat", "Independent-Democrat", + ... "Independent-Indpendent", "Independent-Republican", + ... "Weak Republican", "Strong Republican"] + + Group age by party ID, and create a violin plot with it: + + >>> plt.rcParams['figure.subplot.bottom'] = 0.23 # keep labels visible + >>> age = [data.exog['age'][data.endog == id] for id in party_ID] + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111) + >>> sm.graphics.beanplot(age, ax=ax, labels=labels, + ... plot_opts={'cutoff_val':5, 'cutoff_type':'abs', + ... 'label_fontsize':'small', + ... 'label_rotation':30}) + >>> ax.set_xlabel("Party identification of respondent.") + >>> ax.set_ylabel("Age") + >>> plt.show() + + .. plot:: plots/graphics_boxplot_beanplot.py + """ + fig, ax = utils.create_mpl_ax(ax) + + data = list(map(np.asarray, data)) + if positions is None: + positions = np.arange(len(data)) + 1 + + # Determine available horizontal space for each individual violin. + pos_span = np.max(positions) - np.min(positions) + violin_width = np.min([0.15 * np.max([pos_span, 1.]), + plot_opts.get('violin_width', 0.8) / 2.]) + bean_width = np.min([0.15 * np.max([pos_span, 1.]), + plot_opts.get('bean_size', 0.5) / 2.]) + bean_mean_width = np.min([0.15 * np.max([pos_span, 1.]), + plot_opts.get('bean_mean_size', 0.5) / 2.]) + + legend_txt = plot_opts.get('bean_legend_text', None) + for pos_data, pos in zip(data, positions): + # Draw violins. + xvals, violin = _single_violin(ax, pos, pos_data, violin_width, side, plot_opts) + + if jitter: + # Draw data points at random coordinates within violin envelope. + jitter_coord = pos + _jitter_envelope(pos_data, xvals, violin, side) + ax.plot(jitter_coord, pos_data, ls='', + marker=plot_opts.get('jitter_marker', 'o'), + ms=plot_opts.get('jitter_marker_size', 4), + mec=plot_opts.get('bean_color', 'k'), + mew=1, mfc=plot_opts.get('jitter_fc', 'none'), + label=legend_txt) + else: + # Draw bean lines. + ax.hlines(pos_data, pos - bean_width, pos + bean_width, + lw=plot_opts.get('bean_lw', 0.5), + color=plot_opts.get('bean_color', 'k'), + label=legend_txt) + + # Show legend if required. + if legend_txt is not None: + _show_legend(ax) + legend_txt = None # ensure we get one entry per call to beanplot + + # Draw mean line. + if plot_opts.get('bean_show_mean', True): + ax.hlines(np.mean(pos_data), pos - bean_mean_width, pos + bean_mean_width, + lw=plot_opts.get('bean_mean_lw', 2.), + color=plot_opts.get('bean_mean_color', 'b')) + + # Draw median marker. + if plot_opts.get('bean_show_median', True): + ax.plot(pos, np.median(pos_data), + marker=plot_opts.get('bean_median_marker', '+'), + color=plot_opts.get('bean_median_color', 'r')) + + # Set ticks and tick labels of horizontal axis. + _set_ticks_labels(ax, data, labels, positions, plot_opts) + + return fig + + +def _jitter_envelope(pos_data, xvals, violin, side): + """Determine envelope for jitter markers.""" + if side == 'both': + low, high = (-1., 1.) + elif side == 'right': + low, high = (0, 1.) + elif side == 'left': + low, high = (-1., 0) + else: + raise ValueError("`side` input incorrect: %s" % side) + + jitter_envelope = np.interp(pos_data, xvals, violin) + jitter_coord = jitter_envelope * np.random.uniform(low=low, high=high, + size=pos_data.size) + + return jitter_coord + + +def _show_legend(ax): + """Utility function to show legend.""" + leg = ax.legend(loc=1, shadow=True, fancybox=True, labelspacing=0.2, + borderpad=0.15) + ltext = leg.get_texts() + llines = leg.get_lines() + frame = leg.get_frame() + + from matplotlib.artist import setp + setp(ltext, fontsize='small') + setp(llines, linewidth=1) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/correlation.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/correlation.py new file mode 100644 index 0000000000000000000000000000000000000000..43746673f2fd2ed2e62dec64fd45dd1f7ec5470f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/correlation.py @@ -0,0 +1,221 @@ +'''correlation plots + +Author: Josef Perktold +License: BSD-3 + +example for usage with different options in +statsmodels/sandbox/examples/thirdparty/ex_ratereturn.py + +''' +import numpy as np + +from . import utils + + +def plot_corr(dcorr, xnames=None, ynames=None, title=None, normcolor=False, + ax=None, cmap='RdYlBu_r'): + """Plot correlation of many variables in a tight color grid. + + Parameters + ---------- + dcorr : ndarray + Correlation matrix, square 2-D array. + xnames : list[str], optional + Labels for the horizontal axis. If not given (None), then the + matplotlib defaults (integers) are used. If it is an empty list, [], + then no ticks and labels are added. + ynames : list[str], optional + Labels for the vertical axis. Works the same way as `xnames`. + If not given, the same names as for `xnames` are re-used. + title : str, optional + The figure title. If None, the default ('Correlation Matrix') is used. + If ``title=''``, then no title is added. + normcolor : bool or tuple of scalars, optional + If False (default), then the color coding range corresponds to the + range of `dcorr`. If True, then the color range is normalized to + (-1, 1). If this is a tuple of two numbers, then they define the range + for the color bar. + ax : AxesSubplot, optional + If `ax` is None, then a figure is created. If an axis instance is + given, then only the main plot but not the colorbar is created. + cmap : str or Matplotlib Colormap instance, optional + The colormap for the plot. Can be any valid Matplotlib Colormap + instance or name. + + Returns + ------- + Figure + If `ax` is None, the created figure. Otherwise the figure to which + `ax` is connected. + + Examples + -------- + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> import statsmodels.graphics.api as smg + + >>> hie_data = sm.datasets.randhie.load_pandas() + >>> corr_matrix = np.corrcoef(hie_data.data.T) + >>> smg.plot_corr(corr_matrix, xnames=hie_data.names) + >>> plt.show() + + .. plot:: plots/graphics_correlation_plot_corr.py + """ + if ax is None: + create_colorbar = True + else: + create_colorbar = False + + fig, ax = utils.create_mpl_ax(ax) + + nvars = dcorr.shape[0] + + if ynames is None: + ynames = xnames + if title is None: + title = 'Correlation Matrix' + if isinstance(normcolor, tuple): + vmin, vmax = normcolor + elif normcolor: + vmin, vmax = -1.0, 1.0 + else: + vmin, vmax = None, None + + axim = ax.imshow(dcorr, cmap=cmap, interpolation='nearest', + extent=(0,nvars,0,nvars), vmin=vmin, vmax=vmax) + + # create list of label positions + labelPos = np.arange(0, nvars) + 0.5 + + if isinstance(ynames, list) and len(ynames) == 0: + ax.set_yticks([]) + elif ynames is not None: + ax.set_yticks(labelPos) + ax.set_yticks(labelPos[:-1]+0.5, minor=True) + ax.set_yticklabels(ynames[::-1], fontsize='small', + horizontalalignment='right') + + if isinstance(xnames, list) and len(xnames) == 0: + ax.set_xticks([]) + elif xnames is not None: + ax.set_xticks(labelPos) + ax.set_xticks(labelPos[:-1]+0.5, minor=True) + ax.set_xticklabels(xnames, fontsize='small', rotation=45, + horizontalalignment='right') + + + if not title == '': + ax.set_title(title) + + if create_colorbar: + fig.colorbar(axim, use_gridspec=True) + fig.tight_layout() + + ax.tick_params(which='minor', length=0) + ax.tick_params(direction='out', top=False, right=False) + try: + ax.grid(True, which='minor', linestyle='-', color='w', lw=1) + except AttributeError: + # Seems to fail for axes created with AxesGrid. MPL bug? + pass + + return fig + + +def plot_corr_grid(dcorrs, titles=None, ncols=None, normcolor=False, xnames=None, + ynames=None, fig=None, cmap='RdYlBu_r'): + """ + Create a grid of correlation plots. + + The individual correlation plots are assumed to all have the same + variables, axis labels can be specified only once. + + Parameters + ---------- + dcorrs : list or iterable of ndarrays + List of correlation matrices. + titles : list[str], optional + List of titles for the subplots. By default no title are shown. + ncols : int, optional + Number of columns in the subplot grid. If not given, the number of + columns is determined automatically. + normcolor : bool or tuple, optional + If False (default), then the color coding range corresponds to the + range of `dcorr`. If True, then the color range is normalized to + (-1, 1). If this is a tuple of two numbers, then they define the range + for the color bar. + xnames : list[str], optional + Labels for the horizontal axis. If not given (None), then the + matplotlib defaults (integers) are used. If it is an empty list, [], + then no ticks and labels are added. + ynames : list[str], optional + Labels for the vertical axis. Works the same way as `xnames`. + If not given, the same names as for `xnames` are re-used. + fig : Figure, optional + If given, this figure is simply returned. Otherwise a new figure is + created. + cmap : str or Matplotlib Colormap instance, optional + The colormap for the plot. Can be any valid Matplotlib Colormap + instance or name. + + Returns + ------- + Figure + If `ax` is None, the created figure. Otherwise the figure to which + `ax` is connected. + + Examples + -------- + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> import statsmodels.api as sm + + In this example we just reuse the same correlation matrix several times. + Of course in reality one would show a different correlation (measuring a + another type of correlation, for example Pearson (linear) and Spearman, + Kendall (nonlinear) correlations) for the same variables. + + >>> hie_data = sm.datasets.randhie.load_pandas() + >>> corr_matrix = np.corrcoef(hie_data.data.T) + >>> sm.graphics.plot_corr_grid([corr_matrix] * 8, xnames=hie_data.names) + >>> plt.show() + + .. plot:: plots/graphics_correlation_plot_corr_grid.py + """ + if ynames is None: + ynames = xnames + + if not titles: + titles = ['']*len(dcorrs) + + n_plots = len(dcorrs) + if ncols is not None: + nrows = int(np.ceil(n_plots / float(ncols))) + else: + # Determine number of rows and columns, square if possible, otherwise + # prefer a wide (more columns) over a high layout. + if n_plots < 4: + nrows, ncols = 1, n_plots + else: + nrows = int(np.sqrt(n_plots)) + ncols = int(np.ceil(n_plots / float(nrows))) + + # Create a figure with the correct size + aspect = min(ncols / float(nrows), 1.8) + vsize = np.sqrt(nrows) * 5 + fig = utils.create_mpl_fig(fig, figsize=(vsize * aspect + 1, vsize)) + + for i, c in enumerate(dcorrs): + ax = fig.add_subplot(nrows, ncols, i+1) + # Ensure to only plot labels on bottom row and left column + _xnames = xnames if nrows * ncols - (i+1) < ncols else [] + _ynames = ynames if (i+1) % ncols == 1 else [] + plot_corr(c, xnames=_xnames, ynames=_ynames, title=titles[i], + normcolor=normcolor, ax=ax, cmap=cmap) + + # Adjust figure margins and add a colorbar + fig.subplots_adjust(bottom=0.1, left=0.09, right=0.9, top=0.9) + cax = fig.add_axes([0.92, 0.1, 0.025, 0.8]) + fig.colorbar(fig.axes[0].images[0], cax=cax) + + return fig diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/dotplots.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/dotplots.py new file mode 100644 index 0000000000000000000000000000000000000000..da96b0b3ab89120207318cd927bd0609f3288d27 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/dotplots.py @@ -0,0 +1,489 @@ +import numpy as np + +from . import utils + + +def dot_plot(points, intervals=None, lines=None, sections=None, + styles=None, marker_props=None, line_props=None, + split_names=None, section_order=None, line_order=None, + stacked=False, styles_order=None, striped=False, + horizontal=True, show_names="both", + fmt_left_name=None, fmt_right_name=None, + show_section_titles=None, ax=None): + """ + Dot plotting (also known as forest and blobbogram). + + Produce a dotplot similar in style to those in Cleveland's + "Visualizing Data" book ([1]_). These are also known as "forest plots". + + Parameters + ---------- + points : array_like + The quantitative values to be plotted as markers. + intervals : array_like + The intervals to be plotted around the points. The elements + of `intervals` are either scalars or sequences of length 2. A + scalar indicates the half width of a symmetric interval. A + sequence of length 2 contains the left and right half-widths + (respectively) of a nonsymmetric interval. If None, no + intervals are drawn. + lines : array_like + A grouping variable indicating which points/intervals are + drawn on a common line. If None, each point/interval appears + on its own line. + sections : array_like + A grouping variable indicating which lines are grouped into + sections. If None, everything is drawn in a single section. + styles : array_like + A grouping label defining the plotting style of the markers + and intervals. + marker_props : dict + A dictionary mapping style codes (the values in `styles`) to + dictionaries defining key/value pairs to be passed as keyword + arguments to `plot` when plotting markers. Useful keyword + arguments are "color", "marker", and "ms" (marker size). + line_props : dict + A dictionary mapping style codes (the values in `styles`) to + dictionaries defining key/value pairs to be passed as keyword + arguments to `plot` when plotting interval lines. Useful + keyword arguments are "color", "linestyle", "solid_capstyle", + and "linewidth". + split_names : str + If not None, this is used to split the values of `lines` into + substrings that are drawn in the left and right margins, + respectively. If None, the values of `lines` are drawn in the + left margin. + section_order : array_like + The section labels in the order in which they appear in the + dotplot. + line_order : array_like + The line labels in the order in which they appear in the + dotplot. + stacked : bool + If True, when multiple points or intervals are drawn on the + same line, they are offset from each other. + styles_order : array_like + If stacked=True, this is the order in which the point styles + on a given line are drawn from top to bottom (if horizontal + is True) or from left to right (if horizontal is False). If + None (default), the order is lexical. + striped : bool + If True, every other line is enclosed in a shaded box. + horizontal : bool + If True (default), the lines are drawn horizontally, otherwise + they are drawn vertically. + show_names : str + Determines whether labels (names) are shown in the left and/or + right margins (top/bottom margins if `horizontal` is True). + If `both`, labels are drawn in both margins, if 'left', labels + are drawn in the left or top margin. If `right`, labels are + drawn in the right or bottom margin. + fmt_left_name : callable + The left/top margin names are passed through this function + before drawing on the plot. + fmt_right_name : callable + The right/bottom marginnames are passed through this function + before drawing on the plot. + show_section_titles : bool or None + If None, section titles are drawn only if there is more than + one section. If False/True, section titles are never/always + drawn, respectively. + ax : matplotlib.axes + The axes on which the dotplot is drawn. If None, a new axes + is created. + + Returns + ------- + fig : Figure + The figure given by `ax.figure` or a new instance. + + Notes + ----- + `points`, `intervals`, `lines`, `sections`, `styles` must all have + the same length whenever present. + + References + ---------- + .. [1] Cleveland, William S. (1993). "Visualizing Data". Hobart Press. + .. [2] Jacoby, William G. (2006) "The Dot Plot: A Graphical Display + for Labeled Quantitative Values." The Political Methodologist + 14(1): 6-14. + + Examples + -------- + This is a simple dotplot with one point per line: + + >>> dot_plot(points=point_values) + + This dotplot has labels on the lines (if elements in + `label_values` are repeated, the corresponding points appear on + the same line): + + >>> dot_plot(points=point_values, lines=label_values) + """ + + import matplotlib.transforms as transforms + + fig, ax = utils.create_mpl_ax(ax) + + # Convert to numpy arrays if that is not what we are given. + points = np.asarray(points) + asarray_or_none = lambda x : None if x is None else np.asarray(x) + intervals = asarray_or_none(intervals) + lines = asarray_or_none(lines) + sections = asarray_or_none(sections) + styles = asarray_or_none(styles) + + # Total number of points + npoint = len(points) + + # Set default line values if needed + if lines is None: + lines = np.arange(npoint) + + # Set default section values if needed + if sections is None: + sections = np.zeros(npoint) + + # Set default style values if needed + if styles is None: + styles = np.zeros(npoint) + + # The vertical space (in inches) for a section title + section_title_space = 0.5 + + # The number of sections + nsect = len(set(sections)) + if section_order is not None: + nsect = len(set(section_order)) + + # The number of section titles + if show_section_titles is False: + draw_section_titles = False + nsect_title = 0 + elif show_section_titles is True: + draw_section_titles = True + nsect_title = nsect + else: + draw_section_titles = nsect > 1 + nsect_title = nsect if nsect > 1 else 0 + + # The total vertical space devoted to section titles. + section_space_total = section_title_space * nsect_title + + # Add a bit of room so that points that fall at the axis limits + # are not cut in half. + ax.set_xmargin(0.02) + ax.set_ymargin(0.02) + + if section_order is None: + lines0 = list(set(sections)) + lines0.sort() + else: + lines0 = section_order + + if line_order is None: + lines1 = list(set(lines)) + lines1.sort() + else: + lines1 = line_order + + # A map from (section,line) codes to index positions. + lines_map = {} + for i in range(npoint): + if section_order is not None and sections[i] not in section_order: + continue + if line_order is not None and lines[i] not in line_order: + continue + ky = (sections[i], lines[i]) + if ky not in lines_map: + lines_map[ky] = [] + lines_map[ky].append(i) + + # Get the size of the axes on the parent figure in inches + bbox = ax.get_window_extent().transformed( + fig.dpi_scale_trans.inverted()) + awidth, aheight = bbox.width, bbox.height + + # The number of lines in the plot. + nrows = len(lines_map) + + # The positions of the lowest and highest guideline in axes + # coordinates (for horizontal dotplots), or the leftmost and + # rightmost guidelines (for vertical dotplots). + bottom, top = 0, 1 + + if horizontal: + # x coordinate is data, y coordinate is axes + trans = transforms.blended_transform_factory(ax.transData, + ax.transAxes) + else: + # x coordinate is axes, y coordinate is data + trans = transforms.blended_transform_factory(ax.transAxes, + ax.transData) + + # Space used for a section title, in axes coordinates + title_space_axes = section_title_space / aheight + + # Space between lines + if horizontal: + dpos = (top - bottom - nsect_title*title_space_axes) /\ + float(nrows) + else: + dpos = (top - bottom) / float(nrows) + + # Determine the spacing for stacked points + if styles_order is not None: + style_codes = styles_order + else: + style_codes = list(set(styles)) + style_codes.sort() + # Order is top to bottom for horizontal plots, so need to + # flip. + if horizontal: + style_codes = style_codes[::-1] + # nval is the maximum number of points on one line. + nval = len(style_codes) + if nval > 1: + stackd = dpos / (2.5*(float(nval)-1)) + else: + stackd = 0. + + # Map from style code to its integer position + style_codes_map = {x: style_codes.index(x) for x in style_codes} + + # Setup default marker styles + colors = ["r", "g", "b", "y", "k", "purple", "orange"] + if marker_props is None: + marker_props = {x: {} for x in style_codes} + for j in range(nval): + sc = style_codes[j] + if "color" not in marker_props[sc]: + marker_props[sc]["color"] = colors[j % len(colors)] + if "marker" not in marker_props[sc]: + marker_props[sc]["marker"] = "o" + if "ms" not in marker_props[sc]: + marker_props[sc]["ms"] = 10 if stackd == 0 else 6 + + # Setup default line styles + if line_props is None: + line_props = {x: {} for x in style_codes} + for j in range(nval): + sc = style_codes[j] + if "color" not in line_props[sc]: + line_props[sc]["color"] = "grey" + if "linewidth" not in line_props[sc]: + line_props[sc]["linewidth"] = 2 if stackd > 0 else 8 + + if horizontal: + # The vertical position of the first line. + pos = top - dpos/2 if nsect == 1 else top + else: + # The horizontal position of the first line. + pos = bottom + dpos/2 + + # Points that have already been labeled + labeled = set() + + # Positions of the y axis grid lines + ticks = [] + + # Loop through the sections + for k0 in lines0: + + # Draw a section title + if draw_section_titles: + + if horizontal: + + y0 = pos + dpos/2 if k0 == lines0[0] else pos + + ax.fill_between((0, 1), (y0,y0), + (pos-0.7*title_space_axes, + pos-0.7*title_space_axes), + color='darkgrey', + transform=ax.transAxes, + zorder=1) + + txt = ax.text(0.5, pos - 0.35*title_space_axes, k0, + horizontalalignment='center', + verticalalignment='center', + transform=ax.transAxes) + txt.set_fontweight("bold") + pos -= title_space_axes + + else: + + m = len([k for k in lines_map if k[0] == k0]) + + ax.fill_between((pos-dpos/2+0.01, + pos+(m-1)*dpos+dpos/2-0.01), + (1.01,1.01), (1.06,1.06), + color='darkgrey', + transform=ax.transAxes, + zorder=1, clip_on=False) + + txt = ax.text(pos + (m-1)*dpos/2, 1.02, k0, + horizontalalignment='center', + verticalalignment='bottom', + transform=ax.transAxes) + txt.set_fontweight("bold") + + jrow = 0 + for k1 in lines1: + + # No data to plot + if (k0, k1) not in lines_map: + continue + + # Draw the guideline + if horizontal: + ax.axhline(pos, color='grey') + else: + ax.axvline(pos, color='grey') + + # Set up the labels + if split_names is not None: + us = k1.split(split_names) + if len(us) >= 2: + left_label, right_label = us[0], us[1] + else: + left_label, right_label = k1, None + else: + left_label, right_label = k1, None + + if fmt_left_name is not None: + left_label = fmt_left_name(left_label) + + if fmt_right_name is not None: + right_label = fmt_right_name(right_label) + + # Draw the stripe + if striped and jrow % 2 == 0: + if horizontal: + ax.fill_between((0, 1), (pos-dpos/2, pos-dpos/2), + (pos+dpos/2, pos+dpos/2), + color='lightgrey', + transform=ax.transAxes, + zorder=0) + else: + ax.fill_between((pos-dpos/2, pos+dpos/2), + (0, 0), (1, 1), + color='lightgrey', + transform=ax.transAxes, + zorder=0) + + jrow += 1 + + # Draw the left margin label + if show_names.lower() in ("left", "both"): + if horizontal: + ax.text(-0.1/awidth, pos, left_label, + horizontalalignment="right", + verticalalignment='center', + transform=ax.transAxes, + family='monospace') + else: + ax.text(pos, -0.1/aheight, left_label, + horizontalalignment="center", + verticalalignment='top', + transform=ax.transAxes, + family='monospace') + + # Draw the right margin label + if show_names.lower() in ("right", "both"): + if right_label is not None: + if horizontal: + ax.text(1 + 0.1/awidth, pos, right_label, + horizontalalignment="left", + verticalalignment='center', + transform=ax.transAxes, + family='monospace') + else: + ax.text(pos, 1 + 0.1/aheight, right_label, + horizontalalignment="center", + verticalalignment='bottom', + transform=ax.transAxes, + family='monospace') + + # Save the vertical position so that we can place the + # tick marks + ticks.append(pos) + + # Loop over the points in one line + for ji,jp in enumerate(lines_map[(k0,k1)]): + + # Calculate the vertical offset + yo = 0 + if stacked: + yo = -dpos/5 + style_codes_map[styles[jp]]*stackd + + pt = points[jp] + + # Plot the interval + if intervals is not None: + + # Symmetric interval + if np.isscalar(intervals[jp]): + lcb, ucb = pt - intervals[jp],\ + pt + intervals[jp] + + # Nonsymmetric interval + else: + lcb, ucb = pt - intervals[jp][0],\ + pt + intervals[jp][1] + + # Draw the interval + if horizontal: + ax.plot([lcb, ucb], [pos+yo, pos+yo], '-', + transform=trans, + **line_props[styles[jp]]) + else: + ax.plot([pos+yo, pos+yo], [lcb, ucb], '-', + transform=trans, + **line_props[styles[jp]]) + + + # Plot the point + sl = styles[jp] + sll = sl if sl not in labeled else None + labeled.add(sl) + if horizontal: + ax.plot([pt,], [pos+yo,], ls='None', + transform=trans, label=sll, + **marker_props[sl]) + else: + ax.plot([pos+yo,], [pt,], ls='None', + transform=trans, label=sll, + **marker_props[sl]) + + if horizontal: + pos -= dpos + else: + pos += dpos + + # Set up the axis + if horizontal: + ax.xaxis.set_ticks_position("bottom") + ax.yaxis.set_ticks_position("none") + ax.set_yticklabels([]) + ax.spines['left'].set_color('none') + ax.spines['right'].set_color('none') + ax.spines['top'].set_color('none') + ax.spines['bottom'].set_position(('axes', -0.1/aheight)) + ax.set_ylim(0, 1) + ax.yaxis.set_ticks(ticks) + ax.autoscale_view(scaley=False, tight=True) + else: + ax.yaxis.set_ticks_position("left") + ax.xaxis.set_ticks_position("none") + ax.set_xticklabels([]) + ax.spines['bottom'].set_color('none') + ax.spines['right'].set_color('none') + ax.spines['top'].set_color('none') + ax.spines['left'].set_position(('axes', -0.1/awidth)) + ax.set_xlim(0, 1) + ax.xaxis.set_ticks(ticks) + ax.autoscale_view(scalex=False, tight=True) + + return fig diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/factorplots.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/factorplots.py new file mode 100644 index 0000000000000000000000000000000000000000..3439d29ef4606f9eee9cc4417a64efe695ca6d48 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/factorplots.py @@ -0,0 +1,235 @@ +""" +Authors: Josef Perktold, Skipper Seabold, Denis A. Engemann +""" + +from statsmodels.compat.python import lrange + +import numpy as np + +from statsmodels.graphics.plottools import rainbow +import statsmodels.graphics.utils as utils + + +def interaction_plot( + x, + trace, + response, + func="mean", + ax=None, + plottype="b", + xlabel=None, + ylabel=None, + colors=None, + markers=None, + linestyles=None, + legendloc="best", + legendtitle=None, + **kwargs, +): + """ + Interaction plot for factor level statistics. + + Note. If categorial factors are supplied levels will be internally + recoded to integers. This ensures matplotlib compatibility. Uses + a DataFrame to calculate an `aggregate` statistic for each level of the + factor or group given by `trace`. + + Parameters + ---------- + x : array_like + The `x` factor levels constitute the x-axis. If a `pandas.Series` is + given its name will be used in `xlabel` if `xlabel` is None. + trace : array_like + The `trace` factor levels will be drawn as lines in the plot. + If `trace` is a `pandas.Series` its name will be used as the + `legendtitle` if `legendtitle` is None. + response : array_like + The reponse or dependent variable. If a `pandas.Series` is given + its name will be used in `ylabel` if `ylabel` is None. + func : function + Anything accepted by `pandas.DataFrame.aggregate`. This is applied to + the response variable grouped by the trace levels. + ax : axes, optional + Matplotlib axes instance + plottype : str {'line', 'scatter', 'both'}, optional + The type of plot to return. Can be 'l', 's', or 'b' + xlabel : str, optional + Label to use for `x`. Default is 'X'. If `x` is a `pandas.Series` it + will use the series names. + ylabel : str, optional + Label to use for `response`. Default is 'func of response'. If + `response` is a `pandas.Series` it will use the series names. + colors : list, optional + If given, must have length == number of levels in trace. + markers : list, optional + If given, must have length == number of levels in trace + linestyles : list, optional + If given, must have length == number of levels in trace. + legendloc : {None, str, int} + Location passed to the legend command. + legendtitle : {None, str} + Title of the legend. + **kwargs + These will be passed to the plot command used either plot or scatter. + If you want to control the overall plotting options, use kwargs. + + Returns + ------- + Figure + The figure given by `ax.figure` or a new instance. + + Examples + -------- + >>> import numpy as np + >>> np.random.seed(12345) + >>> weight = np.random.randint(1,4,size=60) + >>> duration = np.random.randint(1,3,size=60) + >>> days = np.log(np.random.randint(1,30, size=60)) + >>> fig = interaction_plot(weight, duration, days, + ... colors=['red','blue'], markers=['D','^'], ms=10) + >>> import matplotlib.pyplot as plt + >>> plt.show() + + .. plot:: + + import numpy as np + from statsmodels.graphics.factorplots import interaction_plot + np.random.seed(12345) + weight = np.random.randint(1,4,size=60) + duration = np.random.randint(1,3,size=60) + days = np.log(np.random.randint(1,30, size=60)) + fig = interaction_plot(weight, duration, days, + colors=['red','blue'], markers=['D','^'], ms=10) + import matplotlib.pyplot as plt + #plt.show() + """ + + from pandas import DataFrame + + fig, ax = utils.create_mpl_ax(ax) + + response_name = ylabel or getattr(response, "name", "response") + func_name = getattr(func, "__name__", str(func)) + ylabel = f"{func_name} of {response_name}" + xlabel = xlabel or getattr(x, "name", "X") + legendtitle = legendtitle or getattr(trace, "name", "Trace") + + ax.set_ylabel(ylabel) + ax.set_xlabel(xlabel) + + x_values = x_levels = None + if isinstance(x[0], str): + x_levels = [l for l in np.unique(x)] + x_values = lrange(len(x_levels)) + x = _recode(x, dict(zip(x_levels, x_values))) + + data = DataFrame(dict(x=x, trace=trace, response=response)) + plot_data = data.groupby(["trace", "x"]).aggregate(func).reset_index() + + # return data + # check plot args + n_trace = len(plot_data["trace"].unique()) + + linestyles = ["-"] * n_trace if linestyles is None else linestyles + markers = ["."] * n_trace if markers is None else markers + colors = rainbow(n_trace) if colors is None else colors + + if len(linestyles) != n_trace: + raise ValueError("Must be a linestyle for each trace level") + if len(markers) != n_trace: + raise ValueError("Must be a marker for each trace level") + if len(colors) != n_trace: + raise ValueError("Must be a color for each trace level") + + if plottype == "both" or plottype == "b": + for i, (values, group) in enumerate(plot_data.groupby("trace")): + # trace label + label = str(group["trace"].values[0]) + ax.plot( + group["x"], + group["response"], + color=colors[i], + marker=markers[i], + label=label, + linestyle=linestyles[i], + **kwargs, + ) + elif plottype == "line" or plottype == "l": + for i, (values, group) in enumerate(plot_data.groupby("trace")): + # trace label + label = str(group["trace"].values[0]) + ax.plot( + group["x"], + group["response"], + color=colors[i], + label=label, + linestyle=linestyles[i], + **kwargs, + ) + elif plottype == "scatter" or plottype == "s": + for i, (values, group) in enumerate(plot_data.groupby("trace")): + # trace label + label = str(group["trace"].values[0]) + ax.scatter( + group["x"], + group["response"], + color=colors[i], + label=label, + marker=markers[i], + **kwargs, + ) + + else: + raise ValueError("Plot type %s not understood" % plottype) + ax.legend(loc=legendloc, title=legendtitle) + ax.margins(0.1) + + if all([x_levels, x_values]): + ax.set_xticks(x_values) + ax.set_xticklabels(x_levels) + return fig + + +def _recode(x, levels): + """Recode categorial data to int factor. + + Parameters + ---------- + x : array_like + array like object supporting with numpy array methods of categorially + coded data. + levels : dict + mapping of labels to integer-codings + + Returns + ------- + out : instance numpy.ndarray + """ + from pandas import Series + + name = None + index = None + + if isinstance(x, Series): + name = x.name + index = x.index + x = x.values + + if x.dtype.type not in [np.str_, np.object_, str]: + raise ValueError("This is not a categorial factor. Array of str type required.") + + elif not isinstance(levels, dict): + raise ValueError("This is not a valid value for levels." " Dict required.") + + elif not (np.unique(x) == np.unique(list(levels.keys()))).all(): + raise ValueError("The levels do not match the array values.") + + else: + out = np.empty(x.shape[0], dtype=int) + for level, coding in levels.items(): + out[x == level] = coding + + if name: + out = Series(out, name=name, index=index) + + return out diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/functional.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/functional.py new file mode 100644 index 0000000000000000000000000000000000000000..9b601f2248fb06270a21f79ab6afdcae5e5d73c1 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/functional.py @@ -0,0 +1,853 @@ +"""Module for functional boxplots.""" +from statsmodels.compat.numpy import NP_LT_123 + +import numpy as np +from scipy.special import comb + +from statsmodels.graphics.utils import _import_mpl +from statsmodels.multivariate.pca import PCA +from statsmodels.nonparametric.kernel_density import KDEMultivariate + +try: + from scipy.optimize import brute, differential_evolution, fmin + have_de_optim = True +except ImportError: + from scipy.optimize import brute, fmin + have_de_optim = False +import itertools +from multiprocessing import Pool + +from . import utils + +__all__ = ['hdrboxplot', 'fboxplot', 'rainbowplot', 'banddepth'] + + +class HdrResults: + """Wrap results and pretty print them.""" + + def __init__(self, kwds): + self.__dict__.update(kwds) + + def __repr__(self): + msg = ("HDR boxplot summary:\n" + "-> median:\n{}\n" + "-> 50% HDR (max, min):\n{}\n" + "-> 90% HDR (max, min):\n{}\n" + "-> Extra quantiles (max, min):\n{}\n" + "-> Outliers:\n{}\n" + "-> Outliers indices:\n{}\n" + ).format(self.median, self.hdr_50, self.hdr_90, + self.extra_quantiles, self.outliers, self.outliers_idx) + + return msg + + +def _inverse_transform(pca, data): + """ + Inverse transform on PCA. + + Use PCA's `project` method by temporary replacing its factors with + `data`. + + Parameters + ---------- + pca : statsmodels Principal Component Analysis instance + The PCA object to use. + data : sequence of ndarrays or 2-D ndarray + The vectors of functions to create a functional boxplot from. If a + sequence of 1-D arrays, these should all be the same size. + The first axis is the function index, the second axis the one along + which the function is defined. So ``data[0, :]`` is the first + functional curve. + + Returns + ------- + projection : ndarray + nobs by nvar array of the projection onto ncomp factors + """ + factors = pca.factors + pca.factors = data.reshape(-1, factors.shape[1]) + projection = pca.project() + pca.factors = factors + return projection + + +def _curve_constrained(x, idx, sign, band, pca, ks_gaussian): + """Find out if the curve is within the band. + + The curve value at :attr:`idx` for a given PDF is only returned if + within bounds defined by the band. Otherwise, 1E6 is returned. + + Parameters + ---------- + x : float + Curve in reduced space. + idx : int + Index value of the components to compute. + sign : int + Return positive or negative value. + band : list of float + PDF values `[min_pdf, max_pdf]` to be within. + pca : statsmodels Principal Component Analysis instance + The PCA object to use. + ks_gaussian : KDEMultivariate instance + + Returns + ------- + value : float + Curve value at `idx`. + """ + x = x.reshape(1, -1) + pdf = ks_gaussian.pdf(x) + if band[0] < pdf < band[1]: + value = sign * _inverse_transform(pca, x)[0][idx] + else: + value = 1E6 + return value + + +def _min_max_band(args): + """ + Min and max values at `idx`. + + Global optimization to find the extrema per component. + + Parameters + ---------- + args: list + It is a list of an idx and other arguments as a tuple: + idx : int + Index value of the components to compute + The tuple contains: + band : list of float + PDF values `[min_pdf, max_pdf]` to be within. + pca : statsmodels Principal Component Analysis instance + The PCA object to use. + bounds : sequence + ``(min, max)`` pair for each components + ks_gaussian : KDEMultivariate instance + + Returns + ------- + band : tuple of float + ``(max, min)`` curve values at `idx` + """ + idx, (band, pca, bounds, ks_gaussian, use_brute, seed) = args + if have_de_optim and not use_brute: + max_ = differential_evolution(_curve_constrained, bounds=bounds, + args=(idx, -1, band, pca, ks_gaussian), + maxiter=7, seed=seed).x + min_ = differential_evolution(_curve_constrained, bounds=bounds, + args=(idx, 1, band, pca, ks_gaussian), + maxiter=7, seed=seed).x + else: + max_ = brute(_curve_constrained, ranges=bounds, finish=fmin, + args=(idx, -1, band, pca, ks_gaussian)) + + min_ = brute(_curve_constrained, ranges=bounds, finish=fmin, + args=(idx, 1, band, pca, ks_gaussian)) + + band = (_inverse_transform(pca, max_)[0][idx], + _inverse_transform(pca, min_)[0][idx]) + return band + + +def hdrboxplot(data, ncomp=2, alpha=None, threshold=0.95, bw=None, + xdata=None, labels=None, ax=None, use_brute=False, seed=None): + """ + High Density Region boxplot + + Parameters + ---------- + data : sequence of ndarrays or 2-D ndarray + The vectors of functions to create a functional boxplot from. If a + sequence of 1-D arrays, these should all be the same size. + The first axis is the function index, the second axis the one along + which the function is defined. So ``data[0, :]`` is the first + functional curve. + ncomp : int, optional + Number of components to use. If None, returns the as many as the + smaller of the number of rows or columns in data. + alpha : list of floats between 0 and 1, optional + Extra quantile values to compute. Default is None + threshold : float between 0 and 1, optional + Percentile threshold value for outliers detection. High value means + a lower sensitivity to outliers. Default is `0.95`. + bw : array_like or str, optional + If an array, it is a fixed user-specified bandwidth. If `None`, set to + `normal_reference`. If a string, should be one of: + + - normal_reference: normal reference rule of thumb (default) + - cv_ml: cross validation maximum likelihood + - cv_ls: cross validation least squares + + xdata : ndarray, optional + The independent variable for the data. If not given, it is assumed to + be an array of integers 0..N-1 with N the length of the vectors in + `data`. + labels : sequence of scalar or str, optional + The labels or identifiers of the curves in `data`. If not given, + outliers are labeled in the plot with array indices. + ax : AxesSubplot, optional + If given, this subplot is used to plot in instead of a new figure being + created. + use_brute : bool + Use the brute force optimizer instead of the default differential + evolution to find the curves. Default is False. + seed : {None, int, np.random.RandomState} + Seed value to pass to scipy.optimize.differential_evolution. Can be an + integer or RandomState instance. If None, then the default RandomState + provided by np.random is used. + + Returns + ------- + fig : Figure + If `ax` is None, the created figure. Otherwise the figure to which + `ax` is connected. + hdr_res : HdrResults instance + An `HdrResults` instance with the following attributes: + + - 'median', array. Median curve. + - 'hdr_50', array. 50% quantile band. [sup, inf] curves + - 'hdr_90', list of array. 90% quantile band. [sup, inf] + curves. + - 'extra_quantiles', list of array. Extra quantile band. + [sup, inf] curves. + - 'outliers', ndarray. Outlier curves. + + See Also + -------- + banddepth, rainbowplot, fboxplot + + Notes + ----- + The median curve is the curve with the highest probability on the reduced + space of a Principal Component Analysis (PCA). + + Outliers are defined as curves that fall outside the band corresponding + to the quantile given by `threshold`. + + The non-outlying region is defined as the band made up of all the + non-outlying curves. + + Behind the scene, the dataset is represented as a matrix. Each line + corresponding to a 1D curve. This matrix is then decomposed using Principal + Components Analysis (PCA). This allows to represent the data using a finite + number of modes, or components. This compression process allows to turn the + functional representation into a scalar representation of the matrix. In + other words, you can visualize each curve from its components. Each curve + is thus a point in this reduced space. With 2 components, this is called a + bivariate plot (2D plot). + + In this plot, if some points are adjacent (similar components), it means + that back in the original space, the curves are similar. Then, finding the + median curve means finding the higher density region (HDR) in the reduced + space. Moreover, the more you get away from this HDR, the more the curve is + unlikely to be similar to the other curves. + + Using a kernel smoothing technique, the probability density function (PDF) + of the multivariate space can be recovered. From this PDF, it is possible + to compute the density probability linked to the cluster of points and plot + its contours. + + Finally, using these contours, the different quantiles can be extracted + along with the median curve and the outliers. + + Steps to produce the HDR boxplot include: + + 1. Compute a multivariate kernel density estimation + 2. Compute contour lines for quantiles 90%, 50% and `alpha` % + 3. Plot the bivariate plot + 4. Compute median curve along with quantiles and outliers curves. + + References + ---------- + [1] R.J. Hyndman and H.L. Shang, "Rainbow Plots, Bagplots, and Boxplots for + Functional Data", vol. 19, pp. 29-45, 2010. + + Examples + -------- + Load the El Nino dataset. Consists of 60 years worth of Pacific Ocean sea + surface temperature data. + + >>> import matplotlib.pyplot as plt + >>> import statsmodels.api as sm + >>> data = sm.datasets.elnino.load() + + Create a functional boxplot. We see that the years 1982-83 and 1997-98 are + outliers; these are the years where El Nino (a climate pattern + characterized by warming up of the sea surface and higher air pressures) + occurred with unusual intensity. + + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111) + >>> res = sm.graphics.hdrboxplot(data.raw_data[:, 1:], + ... labels=data.raw_data[:, 0].astype(int), + ... ax=ax) + + >>> ax.set_xlabel("Month of the year") + >>> ax.set_ylabel("Sea surface temperature (C)") + >>> ax.set_xticks(np.arange(13, step=3) - 1) + >>> ax.set_xticklabels(["", "Mar", "Jun", "Sep", "Dec"]) + >>> ax.set_xlim([-0.2, 11.2]) + + >>> plt.show() + + .. plot:: plots/graphics_functional_hdrboxplot.py + """ + fig, ax = utils.create_mpl_ax(ax) + + if labels is None: + # For use with pandas, get the labels + if hasattr(data, 'index'): + labels = data.index + else: + labels = np.arange(len(data)) + + data = np.asarray(data) + if xdata is None: + xdata = np.arange(data.shape[1]) + + n_samples, dim = data.shape + # PCA and bivariate plot + pca = PCA(data, ncomp=ncomp) + data_r = pca.factors + + # Create gaussian kernel + ks_gaussian = KDEMultivariate(data_r, bw=bw, + var_type='c' * data_r.shape[1]) + + # Boundaries of the n-variate space + bounds = np.array([data_r.min(axis=0), data_r.max(axis=0)]).T + + # Compute contour line of pvalue linked to a given probability level + if alpha is None: + alpha = [threshold, 0.9, 0.5] + else: + alpha.extend([threshold, 0.9, 0.5]) + alpha = list(set(alpha)) + alpha.sort(reverse=True) + + n_quantiles = len(alpha) + pdf_r = ks_gaussian.pdf(data_r).flatten() + if NP_LT_123: + pvalues = [np.percentile(pdf_r, (1 - alpha[i]) * 100, + interpolation='linear') + for i in range(n_quantiles)] + else: + pvalues = [np.percentile(pdf_r, (1 - alpha[i]) * 100, + method='midpoint') + for i in range(n_quantiles)] + + # Find mean, outliers curves + if have_de_optim and not use_brute: + median = differential_evolution(lambda x: - ks_gaussian.pdf(x), + bounds=bounds, maxiter=5, seed=seed).x + else: + median = brute(lambda x: - ks_gaussian.pdf(x), + ranges=bounds, finish=fmin) + + outliers_idx = np.where(pdf_r < pvalues[alpha.index(threshold)])[0] + labels_outlier = [labels[i] for i in outliers_idx] + outliers = data[outliers_idx] + + # Find HDR given some quantiles + + def _band_quantiles(band, use_brute=use_brute, seed=seed): + """ + Find extreme curves for a quantile band. + + From the `band` of quantiles, the associated PDF extrema values + are computed. If `min_alpha` is not provided (single quantile value), + `max_pdf` is set to `1E6` in order not to constrain the problem on high + values. + + An optimization is performed per component in order to find the min and + max curves. This is done by comparing the PDF value of a given curve + with the band PDF. + + Parameters + ---------- + band : array_like + alpha values ``(max_alpha, min_alpha)`` ex: ``[0.9, 0.5]`` + use_brute : bool + Use the brute force optimizer instead of the default differential + evolution to find the curves. Default is False. + seed : {None, int, np.random.RandomState} + Seed value to pass to scipy.optimize.differential_evolution. Can + be an integer or RandomState instance. If None, then the default + RandomState provided by np.random is used. + + + Returns + ------- + band_quantiles : list of 1-D array + ``(max_quantile, min_quantile)`` (2, n_features) + """ + min_pdf = pvalues[alpha.index(band[0])] + try: + max_pdf = pvalues[alpha.index(band[1])] + except IndexError: + max_pdf = 1E6 + band = [min_pdf, max_pdf] + + pool = Pool() + data = zip(range(dim), itertools.repeat((band, pca, + bounds, ks_gaussian, + seed, use_brute))) + band_quantiles = pool.map(_min_max_band, data) + pool.terminate() + pool.close() + + band_quantiles = list(zip(*band_quantiles)) + + return band_quantiles + + extra_alpha = [i for i in alpha + if 0.5 != i and 0.9 != i and threshold != i] + if len(extra_alpha) > 0: + extra_quantiles = [] + for x in extra_alpha: + for y in _band_quantiles([x], use_brute=use_brute, seed=seed): + extra_quantiles.append(y) + else: + extra_quantiles = [] + + # Inverse transform from n-variate plot to dataset dataset's shape + median = _inverse_transform(pca, median)[0] + hdr_90 = _band_quantiles([0.9, 0.5], use_brute=use_brute, seed=seed) + hdr_50 = _band_quantiles([0.5], use_brute=use_brute, seed=seed) + + hdr_res = HdrResults({ + "median": median, + "hdr_50": hdr_50, + "hdr_90": hdr_90, + "extra_quantiles": extra_quantiles, + "outliers": outliers, + "outliers_idx": outliers_idx + }) + + # Plots + ax.plot(np.array([xdata] * n_samples).T, data.T, + c='c', alpha=.1, label=None) + ax.plot(xdata, median, c='k', label='Median') + fill_betweens = [] + fill_betweens.append(ax.fill_between(xdata, *hdr_50, color='gray', + alpha=.4, label='50% HDR')) + fill_betweens.append(ax.fill_between(xdata, *hdr_90, color='gray', + alpha=.3, label='90% HDR')) + + if len(extra_quantiles) != 0: + ax.plot(np.array([xdata] * len(extra_quantiles)).T, + np.array(extra_quantiles).T, + c='y', ls='-.', alpha=.4, label='Extra quantiles') + + if len(outliers) != 0: + for ii, outlier in enumerate(outliers): + if labels_outlier is None: + label = 'Outliers' + else: + label = str(labels_outlier[ii]) + ax.plot(xdata, outlier, ls='--', alpha=0.7, label=label) + + handles, labels = ax.get_legend_handles_labels() + + # Proxy artist for fill_between legend entry + # See https://matplotlib.org/1.3.1/users/legend_guide.html + plt = _import_mpl() + for label, fill_between in zip(['50% HDR', '90% HDR'], fill_betweens): + p = plt.Rectangle((0, 0), 1, 1, + fc=fill_between.get_facecolor()[0]) + handles.append(p) + labels.append(label) + + by_label = dict(zip(labels, handles)) + if len(outliers) != 0: + by_label.pop('Median') + by_label.pop('50% HDR') + by_label.pop('90% HDR') + + ax.legend(by_label.values(), by_label.keys(), loc='best') + + return fig, hdr_res + + +def fboxplot(data, xdata=None, labels=None, depth=None, method='MBD', + wfactor=1.5, ax=None, plot_opts=None): + """ + Plot functional boxplot. + + A functional boxplot is the analog of a boxplot for functional data. + Functional data is any type of data that varies over a continuum, i.e. + curves, probability distributions, seasonal data, etc. + + The data is first ordered, the order statistic used here is `banddepth`. + Plotted are then the median curve, the envelope of the 50% central region, + the maximum non-outlying envelope and the outlier curves. + + Parameters + ---------- + data : sequence of ndarrays or 2-D ndarray + The vectors of functions to create a functional boxplot from. If a + sequence of 1-D arrays, these should all be the same size. + The first axis is the function index, the second axis the one along + which the function is defined. So ``data[0, :]`` is the first + functional curve. + xdata : ndarray, optional + The independent variable for the data. If not given, it is assumed to + be an array of integers 0..N-1 with N the length of the vectors in + `data`. + labels : sequence of scalar or str, optional + The labels or identifiers of the curves in `data`. If given, outliers + are labeled in the plot. + depth : ndarray, optional + A 1-D array of band depths for `data`, or equivalent order statistic. + If not given, it will be calculated through `banddepth`. + method : {'MBD', 'BD2'}, optional + The method to use to calculate the band depth. Default is 'MBD'. + wfactor : float, optional + Factor by which the central 50% region is multiplied to find the outer + region (analog of "whiskers" of a classical boxplot). + ax : AxesSubplot, optional + If given, this subplot is used to plot in instead of a new figure being + created. + plot_opts : dict, optional + A dictionary with plotting options. Any of the following can be + provided, if not present in `plot_opts` the defaults will be used:: + + - 'cmap_outliers', a Matplotlib LinearSegmentedColormap instance. + - 'c_inner', valid MPL color. Color of the central 50% region + - 'c_outer', valid MPL color. Color of the non-outlying region + - 'c_median', valid MPL color. Color of the median. + - 'lw_outliers', scalar. Linewidth for drawing outlier curves. + - 'lw_median', scalar. Linewidth for drawing the median curve. + - 'draw_nonout', bool. If True, also draw non-outlying curves. + + Returns + ------- + fig : Figure + If `ax` is None, the created figure. Otherwise the figure to which + `ax` is connected. + depth : ndarray + A 1-D array containing the calculated band depths of the curves. + ix_depth : ndarray + A 1-D array of indices needed to order curves (or `depth`) from most to + least central curve. + ix_outliers : ndarray + A 1-D array of indices of outlying curves in `data`. + + See Also + -------- + banddepth, rainbowplot + + Notes + ----- + The median curve is the curve with the highest band depth. + + Outliers are defined as curves that fall outside the band created by + multiplying the central region by `wfactor`. Note that the range over + which they fall outside this band does not matter, a single data point + outside the band is enough. If the data is noisy, smoothing may therefore + be required. + + The non-outlying region is defined as the band made up of all the + non-outlying curves. + + References + ---------- + [1] Y. Sun and M.G. Genton, "Functional Boxplots", Journal of Computational + and Graphical Statistics, vol. 20, pp. 1-19, 2011. + [2] R.J. Hyndman and H.L. Shang, "Rainbow Plots, Bagplots, and Boxplots for + Functional Data", vol. 19, pp. 29-45, 2010. + + Examples + -------- + Load the El Nino dataset. Consists of 60 years worth of Pacific Ocean sea + surface temperature data. + + >>> import matplotlib.pyplot as plt + >>> import statsmodels.api as sm + >>> data = sm.datasets.elnino.load() + + Create a functional boxplot. We see that the years 1982-83 and 1997-98 are + outliers; these are the years where El Nino (a climate pattern + characterized by warming up of the sea surface and higher air pressures) + occurred with unusual intensity. + + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111) + >>> res = sm.graphics.fboxplot(data.raw_data[:, 1:], wfactor=2.58, + ... labels=data.raw_data[:, 0].astype(int), + ... ax=ax) + + >>> ax.set_xlabel("Month of the year") + >>> ax.set_ylabel("Sea surface temperature (C)") + >>> ax.set_xticks(np.arange(13, step=3) - 1) + >>> ax.set_xticklabels(["", "Mar", "Jun", "Sep", "Dec"]) + >>> ax.set_xlim([-0.2, 11.2]) + + >>> plt.show() + + .. plot:: plots/graphics_functional_fboxplot.py + """ + fig, ax = utils.create_mpl_ax(ax) + + plot_opts = {} if plot_opts is None else plot_opts + if plot_opts.get('cmap_outliers') is None: + from matplotlib.cm import rainbow_r + plot_opts['cmap_outliers'] = rainbow_r + + data = np.asarray(data) + if xdata is None: + xdata = np.arange(data.shape[1]) + + # Calculate band depth if required. + if depth is None: + if method not in ['MBD', 'BD2']: + raise ValueError("Unknown value for parameter `method`.") + + depth = banddepth(data, method=method) + else: + if depth.size != data.shape[0]: + raise ValueError("Provided `depth` array is not of correct size.") + + # Inner area is 25%-75% region of band-depth ordered curves. + ix_depth = np.argsort(depth)[::-1] + median_curve = data[ix_depth[0], :] + ix_IQR = data.shape[0] // 2 + lower = data[ix_depth[0:ix_IQR], :].min(axis=0) + upper = data[ix_depth[0:ix_IQR], :].max(axis=0) + + # Determine region for outlier detection + inner_median = np.median(data[ix_depth[0:ix_IQR], :], axis=0) + lower_fence = inner_median - (inner_median - lower) * wfactor + upper_fence = inner_median + (upper - inner_median) * wfactor + + # Find outliers. + ix_outliers = [] + ix_nonout = [] + for ii in range(data.shape[0]): + if (np.any(data[ii, :] > upper_fence) or + np.any(data[ii, :] < lower_fence)): + ix_outliers.append(ii) + else: + ix_nonout.append(ii) + + ix_outliers = np.asarray(ix_outliers) + + # Plot envelope of all non-outlying data + lower_nonout = data[ix_nonout, :].min(axis=0) + upper_nonout = data[ix_nonout, :].max(axis=0) + ax.fill_between(xdata, lower_nonout, upper_nonout, + color=plot_opts.get('c_outer', (0.75, 0.75, 0.75))) + + # Plot central 50% region + ax.fill_between(xdata, lower, upper, + color=plot_opts.get('c_inner', (0.5, 0.5, 0.5))) + + # Plot median curve + ax.plot(xdata, median_curve, color=plot_opts.get('c_median', 'k'), + lw=plot_opts.get('lw_median', 2)) + + # Plot outliers + cmap = plot_opts.get('cmap_outliers') + for ii, ix in enumerate(ix_outliers): + label = str(labels[ix]) if labels is not None else None + ax.plot(xdata, data[ix, :], + color=cmap(float(ii) / (len(ix_outliers)-1)), label=label, + lw=plot_opts.get('lw_outliers', 1)) + + if plot_opts.get('draw_nonout', False): + for ix in ix_nonout: + ax.plot(xdata, data[ix, :], 'k-', lw=0.5) + + if labels is not None: + ax.legend() + + return fig, depth, ix_depth, ix_outliers + + +def rainbowplot(data, xdata=None, depth=None, method='MBD', ax=None, + cmap=None): + """ + Create a rainbow plot for a set of curves. + + A rainbow plot contains line plots of all curves in the dataset, colored in + order of functional depth. The median curve is shown in black. + + Parameters + ---------- + data : sequence of ndarrays or 2-D ndarray + The vectors of functions to create a functional boxplot from. If a + sequence of 1-D arrays, these should all be the same size. + The first axis is the function index, the second axis the one along + which the function is defined. So ``data[0, :]`` is the first + functional curve. + xdata : ndarray, optional + The independent variable for the data. If not given, it is assumed to + be an array of integers 0..N-1 with N the length of the vectors in + `data`. + depth : ndarray, optional + A 1-D array of band depths for `data`, or equivalent order statistic. + If not given, it will be calculated through `banddepth`. + method : {'MBD', 'BD2'}, optional + The method to use to calculate the band depth. Default is 'MBD'. + ax : AxesSubplot, optional + If given, this subplot is used to plot in instead of a new figure being + created. + cmap : Matplotlib LinearSegmentedColormap instance, optional + The colormap used to color curves with. Default is a rainbow colormap, + with red used for the most central and purple for the least central + curves. + + Returns + ------- + Figure + If `ax` is None, the created figure. Otherwise the figure to which + `ax` is connected. + + See Also + -------- + banddepth, fboxplot + + References + ---------- + [1] R.J. Hyndman and H.L. Shang, "Rainbow Plots, Bagplots, and Boxplots for + Functional Data", vol. 19, pp. 29-25, 2010. + + Examples + -------- + Load the El Nino dataset. Consists of 60 years worth of Pacific Ocean sea + surface temperature data. + + >>> import matplotlib.pyplot as plt + >>> import statsmodels.api as sm + >>> data = sm.datasets.elnino.load() + + Create a rainbow plot: + + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111) + >>> res = sm.graphics.rainbowplot(data.raw_data[:, 1:], ax=ax) + + >>> ax.set_xlabel("Month of the year") + >>> ax.set_ylabel("Sea surface temperature (C)") + >>> ax.set_xticks(np.arange(13, step=3) - 1) + >>> ax.set_xticklabels(["", "Mar", "Jun", "Sep", "Dec"]) + >>> ax.set_xlim([-0.2, 11.2]) + >>> plt.show() + + .. plot:: plots/graphics_functional_rainbowplot.py + """ + fig, ax = utils.create_mpl_ax(ax) + + if cmap is None: + from matplotlib.cm import rainbow_r + cmap = rainbow_r + + data = np.asarray(data) + if xdata is None: + xdata = np.arange(data.shape[1]) + + # Calculate band depth if required. + if depth is None: + if method not in ['MBD', 'BD2']: + raise ValueError("Unknown value for parameter `method`.") + + depth = banddepth(data, method=method) + else: + if depth.size != data.shape[0]: + raise ValueError("Provided `depth` array is not of correct size.") + + ix_depth = np.argsort(depth)[::-1] + + # Plot all curves, colored by depth + num_curves = data.shape[0] + for ii in range(num_curves): + ax.plot(xdata, data[ix_depth[ii], :], c=cmap(ii / (num_curves - 1.))) + + # Plot the median curve + median_curve = data[ix_depth[0], :] + ax.plot(xdata, median_curve, 'k-', lw=2) + + return fig + + +def banddepth(data, method='MBD'): + """ + Calculate the band depth for a set of functional curves. + + Band depth is an order statistic for functional data (see `fboxplot`), with + a higher band depth indicating larger "centrality". In analog to scalar + data, the functional curve with highest band depth is called the median + curve, and the band made up from the first N/2 of N curves is the 50% + central region. + + Parameters + ---------- + data : ndarray + The vectors of functions to create a functional boxplot from. + The first axis is the function index, the second axis the one along + which the function is defined. So ``data[0, :]`` is the first + functional curve. + method : {'MBD', 'BD2'}, optional + Whether to use the original band depth (with J=2) of [1]_ or the + modified band depth. See Notes for details. + + Returns + ------- + ndarray + Depth values for functional curves. + + Notes + ----- + Functional band depth as an order statistic for functional data was + proposed in [1]_ and applied to functional boxplots and bagplots in [2]_. + + The method 'BD2' checks for each curve whether it lies completely inside + bands constructed from two curves. All permutations of two curves in the + set of curves are used, and the band depth is normalized to one. Due to + the complete curve having to fall within the band, this method yields a lot + of ties. + + The method 'MBD' is similar to 'BD2', but checks the fraction of the curve + falling within the bands. It therefore generates very few ties. + + The algorithm uses the efficient implementation proposed in [3]_. + + References + ---------- + .. [1] S. Lopez-Pintado and J. Romo, "On the Concept of Depth for + Functional Data", Journal of the American Statistical Association, + vol. 104, pp. 718-734, 2009. + .. [2] Y. Sun and M.G. Genton, "Functional Boxplots", Journal of + Computational and Graphical Statistics, vol. 20, pp. 1-19, 2011. + .. [3] Y. Sun, M. G. Gentonb and D. W. Nychkac, "Exact fast computation + of band depth for large functional datasets: How quickly can one + million curves be ranked?", Journal for the Rapid Dissemination + of Statistics Research, vol. 1, pp. 68-74, 2012. + """ + n, p = data.shape + rv = np.argsort(data, axis=0) + rmat = np.argsort(rv, axis=0) + 1 + + # band depth + def _fbd2(): + down = np.min(rmat, axis=1) - 1 + up = n - np.max(rmat, axis=1) + return (up * down + n - 1) / comb(n, 2) + + # modified band depth + def _fmbd(): + down = rmat - 1 + up = n - rmat + return ((np.sum(up * down, axis=1) / p) + n - 1) / comb(n, 2) + + if method == 'BD2': + depth = _fbd2() + elif method == 'MBD': + depth = _fmbd() + else: + raise ValueError("Unknown input value for parameter `method`.") + + return depth diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/gofplots.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/gofplots.py new file mode 100644 index 0000000000000000000000000000000000000000..53ba1cc6a20f173169b46e01a1ba006c68f7f8b9 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/gofplots.py @@ -0,0 +1,1054 @@ +from statsmodels.compat.python import lzip + +import numpy as np +from scipy import stats + +from statsmodels.distributions import ECDF +from statsmodels.regression.linear_model import OLS +from statsmodels.tools.decorators import cache_readonly +from statsmodels.tools.tools import add_constant + +from . import utils + +__all__ = ["qqplot", "qqplot_2samples", "qqline", "ProbPlot"] + + +class ProbPlot: + """ + Q-Q and P-P Probability Plots + + Can take arguments specifying the parameters for dist or fit them + automatically. (See fit under kwargs.) + + Parameters + ---------- + data : array_like + A 1d data array + dist : callable + Compare x against dist. A scipy.stats or statsmodels distribution. The + default is scipy.stats.distributions.norm (a standard normal). Can be + a SciPy frozen distribution. + fit : bool + If fit is false, loc, scale, and distargs are passed to the + distribution. If fit is True then the parameters for dist are fit + automatically using dist.fit. The quantiles are formed from the + standardized data, after subtracting the fitted loc and dividing by + the fitted scale. fit cannot be used if dist is a SciPy frozen + distribution. + distargs : tuple + A tuple of arguments passed to dist to specify it fully so dist.ppf + may be called. distargs must not contain loc or scale. These values + must be passed using the loc or scale inputs. distargs cannot be used + if dist is a SciPy frozen distribution. + a : float + Offset for the plotting position of an expected order statistic, for + example. The plotting positions are given by + (i - a)/(nobs - 2*a + 1) for i in range(0,nobs+1) + loc : float + Location parameter for dist. Cannot be used if dist is a SciPy frozen + distribution. + scale : float + Scale parameter for dist. Cannot be used if dist is a SciPy frozen + distribution. + + See Also + -------- + scipy.stats.probplot + + Notes + ----- + 1) Depends on matplotlib. + 2) If `fit` is True then the parameters are fit using the + distribution's `fit()` method. + 3) The call signatures for the `qqplot`, `ppplot`, and `probplot` + methods are similar, so examples 1 through 4 apply to all + three methods. + 4) The three plotting methods are summarized below: + ppplot : Probability-Probability plot + Compares the sample and theoretical probabilities (percentiles). + qqplot : Quantile-Quantile plot + Compares the sample and theoretical quantiles + probplot : Probability plot + Same as a Q-Q plot, however probabilities are shown in the scale of + the theoretical distribution (x-axis) and the y-axis contains + unscaled quantiles of the sample data. + + Examples + -------- + The first example shows a Q-Q plot for regression residuals + + >>> # example 1 + >>> import statsmodels.api as sm + >>> from matplotlib import pyplot as plt + >>> data = sm.datasets.longley.load() + >>> data.exog = sm.add_constant(data.exog) + >>> model = sm.OLS(data.endog, data.exog) + >>> mod_fit = model.fit() + >>> res = mod_fit.resid # residuals + >>> pplot = sm.ProbPlot(res) + >>> fig = pplot.qqplot() + >>> h = plt.title("Ex. 1 - qqplot - residuals of OLS fit") + >>> plt.show() + + qqplot of the residuals against quantiles of t-distribution with 4 + degrees of freedom: + + >>> # example 2 + >>> import scipy.stats as stats + >>> pplot = sm.ProbPlot(res, stats.t, distargs=(4,)) + >>> fig = pplot.qqplot() + >>> h = plt.title("Ex. 2 - qqplot - residuals against quantiles of t-dist") + >>> plt.show() + + qqplot against same as above, but with mean 3 and std 10: + + >>> # example 3 + >>> pplot = sm.ProbPlot(res, stats.t, distargs=(4,), loc=3, scale=10) + >>> fig = pplot.qqplot() + >>> h = plt.title("Ex. 3 - qqplot - resids vs quantiles of t-dist") + >>> plt.show() + + Automatically determine parameters for t distribution including the + loc and scale: + + >>> # example 4 + >>> pplot = sm.ProbPlot(res, stats.t, fit=True) + >>> fig = pplot.qqplot(line="45") + >>> h = plt.title("Ex. 4 - qqplot - resids vs. quantiles of fitted t-dist") + >>> plt.show() + + A second `ProbPlot` object can be used to compare two separate sample + sets by using the `other` kwarg in the `qqplot` and `ppplot` methods. + + >>> # example 5 + >>> import numpy as np + >>> x = np.random.normal(loc=8.25, scale=2.75, size=37) + >>> y = np.random.normal(loc=8.75, scale=3.25, size=37) + >>> pp_x = sm.ProbPlot(x, fit=True) + >>> pp_y = sm.ProbPlot(y, fit=True) + >>> fig = pp_x.qqplot(line="45", other=pp_y) + >>> h = plt.title("Ex. 5 - qqplot - compare two sample sets") + >>> plt.show() + + In qqplot, sample size of `other` can be equal or larger than the first. + In case of larger, size of `other` samples will be reduced to match the + size of the first by interpolation + + >>> # example 6 + >>> x = np.random.normal(loc=8.25, scale=2.75, size=37) + >>> y = np.random.normal(loc=8.75, scale=3.25, size=57) + >>> pp_x = sm.ProbPlot(x, fit=True) + >>> pp_y = sm.ProbPlot(y, fit=True) + >>> fig = pp_x.qqplot(line="45", other=pp_y) + >>> title = "Ex. 6 - qqplot - compare different sample sizes" + >>> h = plt.title(title) + >>> plt.show() + + In ppplot, sample size of `other` and the first can be different. `other` + will be used to estimate an empirical cumulative distribution function + (ECDF). ECDF(x) will be plotted against p(x)=0.5/n, 1.5/n, ..., (n-0.5)/n + where x are sorted samples from the first. + + >>> # example 7 + >>> x = np.random.normal(loc=8.25, scale=2.75, size=37) + >>> y = np.random.normal(loc=8.75, scale=3.25, size=57) + >>> pp_x = sm.ProbPlot(x, fit=True) + >>> pp_y = sm.ProbPlot(y, fit=True) + >>> pp_y.ppplot(line="45", other=pp_x) + >>> plt.title("Ex. 7A- ppplot - compare two sample sets, other=pp_x") + >>> pp_x.ppplot(line="45", other=pp_y) + >>> plt.title("Ex. 7B- ppplot - compare two sample sets, other=pp_y") + >>> plt.show() + + The following plot displays some options, follow the link to see the + code. + + .. plot:: plots/graphics_gofplots_qqplot.py + """ + + def __init__( + self, + data, + dist=stats.norm, + fit=False, + distargs=(), + a=0, + loc=0, + scale=1, + ): + + self.data = data + self.a = a + self.nobs = data.shape[0] + self.distargs = distargs + self.fit = fit + + self._is_frozen = isinstance(dist, stats.distributions.rv_frozen) + if self._is_frozen and ( + fit or loc != 0 or scale != 1 or distargs != () + ): + raise ValueError( + "Frozen distributions cannot be combined with fit, loc, scale" + " or distargs." + ) + # propertes + self._cache = {} + if self._is_frozen: + self.dist = dist + dist_gen = dist.dist + shapes = dist_gen.shapes + if shapes is not None: + shape_args = tuple(map(str.strip, shapes.split(","))) + else: + shape_args = () + numargs = len(shape_args) + args = dist.args + if len(args) >= numargs + 1: + self.loc = args[numargs] + else: + self.loc = dist.kwds.get("loc", loc) + if len(args) >= numargs + 2: + self.scale = args[numargs + 1] + else: + self.scale = dist.kwds.get("scale", scale) + fit_params = [] + for i, arg in enumerate(shape_args): + if arg in dist.kwds: + value = dist.kwds[arg] + else: + value = dist.args[i] + fit_params.append(value) + self.fit_params = np.r_[fit_params, self.loc, self.scale] + elif fit: + self.fit_params = dist.fit(data) + self.loc = self.fit_params[-2] + self.scale = self.fit_params[-1] + if len(self.fit_params) > 2: + self.dist = dist(*self.fit_params[:-2], **dict(loc=0, scale=1)) + else: + self.dist = dist(loc=0, scale=1) + elif distargs or loc != 0 or scale != 1: + try: + self.dist = dist(*distargs, **dict(loc=loc, scale=scale)) + except Exception: + distargs = ", ".join([str(da) for da in distargs]) + cmd = "dist({distargs}, loc={loc}, scale={scale})" + cmd = cmd.format(distargs=distargs, loc=loc, scale=scale) + raise TypeError( + "Initializing the distribution failed. This " + "can occur if distargs contains loc or scale. " + "The distribution initialization command " + "is:\n{cmd}".format(cmd=cmd) + ) + self.loc = loc + self.scale = scale + self.fit_params = np.r_[distargs, loc, scale] + else: + self.dist = dist + self.loc = loc + self.scale = scale + self.fit_params = np.r_[loc, scale] + + @cache_readonly + def theoretical_percentiles(self): + """Theoretical percentiles""" + return plotting_pos(self.nobs, self.a) + + @cache_readonly + def theoretical_quantiles(self): + """Theoretical quantiles""" + try: + return self.dist.ppf(self.theoretical_percentiles) + except TypeError: + msg = f"{self.dist.name} requires more parameters to compute ppf" + raise TypeError(msg) + except Exception as exc: + msg = f"failed to compute the ppf of {self.dist.name}" + raise type(exc)(msg) + + @cache_readonly + def sorted_data(self): + """sorted data""" + return np.sort(np.array(self.data)) + + @cache_readonly + def sample_quantiles(self): + """sample quantiles""" + if self.fit and self.loc != 0 and self.scale != 1: + return (self.sorted_data - self.loc) / self.scale + else: + return self.sorted_data + + @cache_readonly + def sample_percentiles(self): + """Sample percentiles""" + _check_for(self.dist, "cdf") + if self._is_frozen: + return self.dist.cdf(self.sorted_data) + quantiles = (self.sorted_data - self.fit_params[-2]) / self.fit_params[ + -1 + ] + return self.dist.cdf(quantiles) + + def ppplot( + self, + xlabel=None, + ylabel=None, + line=None, + other=None, + ax=None, + **plotkwargs, + ): + """ + Plot of the percentiles of x versus the percentiles of a distribution. + + Parameters + ---------- + xlabel : str or None, optional + User-provided labels for the x-axis. If None (default), + other values are used depending on the status of the kwarg `other`. + ylabel : str or None, optional + User-provided labels for the y-axis. If None (default), + other values are used depending on the status of the kwarg `other`. + line : {None, "45", "s", "r", q"}, optional + Options for the reference line to which the data is compared: + + - "45": 45-degree line + - "s": standardized line, the expected order statistics are + scaled by the standard deviation of the given sample and have + the mean added to them + - "r": A regression line is fit + - "q": A line is fit through the quartiles. + - None: by default no reference line is added to the plot. + + other : ProbPlot, array_like, or None, optional + If provided, ECDF(x) will be plotted against p(x) where x are + sorted samples from `self`. ECDF is an empirical cumulative + distribution function estimated from `other` and + p(x) = 0.5/n, 1.5/n, ..., (n-0.5)/n where n is the number of + samples in `self`. If an array-object is provided, it will be + turned into a `ProbPlot` instance default parameters. If not + provided (default), `self.dist(x)` is be plotted against p(x). + + ax : AxesSubplot, optional + If given, this subplot is used to plot in instead of a new figure + being created. + **plotkwargs + Additional arguments to be passed to the `plot` command. + + Returns + ------- + Figure + If `ax` is None, the created figure. Otherwise the figure to which + `ax` is connected. + """ + if other is not None: + check_other = isinstance(other, ProbPlot) + if not check_other: + other = ProbPlot(other) + + p_x = self.theoretical_percentiles + ecdf_x = ECDF(other.sample_quantiles)(self.sample_quantiles) + + fig, ax = _do_plot( + p_x, ecdf_x, self.dist, ax=ax, line=line, **plotkwargs + ) + + if xlabel is None: + xlabel = "Probabilities of 2nd Sample" + if ylabel is None: + ylabel = "Probabilities of 1st Sample" + + else: + fig, ax = _do_plot( + self.theoretical_percentiles, + self.sample_percentiles, + self.dist, + ax=ax, + line=line, + **plotkwargs, + ) + if xlabel is None: + xlabel = "Theoretical Probabilities" + if ylabel is None: + ylabel = "Sample Probabilities" + + ax.set_xlabel(xlabel) + ax.set_ylabel(ylabel) + + ax.set_xlim([0.0, 1.0]) + ax.set_ylim([0.0, 1.0]) + + return fig + + def qqplot( + self, + xlabel=None, + ylabel=None, + line=None, + other=None, + ax=None, + swap: bool = False, + **plotkwargs, + ): + """ + Plot of the quantiles of x versus the quantiles/ppf of a distribution. + + Can also be used to plot against the quantiles of another `ProbPlot` + instance. + + Parameters + ---------- + xlabel : {None, str} + User-provided labels for the x-axis. If None (default), + other values are used depending on the status of the kwarg `other`. + ylabel : {None, str} + User-provided labels for the y-axis. If None (default), + other values are used depending on the status of the kwarg `other`. + line : {None, "45", "s", "r", q"}, optional + Options for the reference line to which the data is compared: + + - "45" - 45-degree line + - "s" - standardized line, the expected order statistics are scaled + by the standard deviation of the given sample and have the mean + added to them + - "r" - A regression line is fit + - "q" - A line is fit through the quartiles. + - None - by default no reference line is added to the plot. + + other : {ProbPlot, array_like, None}, optional + If provided, the sample quantiles of this `ProbPlot` instance are + plotted against the sample quantiles of the `other` `ProbPlot` + instance. Sample size of `other` must be equal or larger than + this `ProbPlot` instance. If the sample size is larger, sample + quantiles of `other` will be interpolated to match the sample size + of this `ProbPlot` instance. If an array-like object is provided, + it will be turned into a `ProbPlot` instance using default + parameters. If not provided (default), the theoretical quantiles + are used. + ax : AxesSubplot, optional + If given, this subplot is used to plot in instead of a new figure + being created. + swap : bool, optional + Flag indicating to swap the x and y labels. + **plotkwargs + Additional arguments to be passed to the `plot` command. + + Returns + ------- + Figure + If `ax` is None, the created figure. Otherwise the figure to which + `ax` is connected. + """ + if other is not None: + check_other = isinstance(other, ProbPlot) + if not check_other: + other = ProbPlot(other) + + s_self = self.sample_quantiles + s_other = other.sample_quantiles + + if len(s_self) > len(s_other): + raise ValueError( + "Sample size of `other` must be equal or " + + "larger than this `ProbPlot` instance" + ) + elif len(s_self) < len(s_other): + # Use quantiles of the smaller set and interpolate quantiles of + # the larger data set + p = plotting_pos(self.nobs, self.a) + s_other = stats.mstats.mquantiles(s_other, p) + fig, ax = _do_plot( + s_other, s_self, self.dist, ax=ax, line=line, **plotkwargs + ) + + if xlabel is None: + xlabel = "Quantiles of 2nd Sample" + if ylabel is None: + ylabel = "Quantiles of 1st Sample" + if swap: + xlabel, ylabel = ylabel, xlabel + + else: + fig, ax = _do_plot( + self.theoretical_quantiles, + self.sample_quantiles, + self.dist, + ax=ax, + line=line, + **plotkwargs, + ) + if xlabel is None: + xlabel = "Theoretical Quantiles" + if ylabel is None: + ylabel = "Sample Quantiles" + + ax.set_xlabel(xlabel) + ax.set_ylabel(ylabel) + + return fig + + def probplot( + self, + xlabel=None, + ylabel=None, + line=None, + exceed=False, + ax=None, + **plotkwargs, + ): + """ + Plot of unscaled quantiles of x against the prob of a distribution. + + The x-axis is scaled linearly with the quantiles, but the probabilities + are used to label the axis. + + Parameters + ---------- + xlabel : {None, str}, optional + User-provided labels for the x-axis. If None (default), + other values are used depending on the status of the kwarg `other`. + ylabel : {None, str}, optional + User-provided labels for the y-axis. If None (default), + other values are used depending on the status of the kwarg `other`. + line : {None, "45", "s", "r", q"}, optional + Options for the reference line to which the data is compared: + + - "45" - 45-degree line + - "s" - standardized line, the expected order statistics are scaled + by the standard deviation of the given sample and have the mean + added to them + - "r" - A regression line is fit + - "q" - A line is fit through the quartiles. + - None - by default no reference line is added to the plot. + + exceed : bool, optional + If False (default) the raw sample quantiles are plotted against + the theoretical quantiles, show the probability that a sample will + not exceed a given value. If True, the theoretical quantiles are + flipped such that the figure displays the probability that a + sample will exceed a given value. + ax : AxesSubplot, optional + If given, this subplot is used to plot in instead of a new figure + being created. + **plotkwargs + Additional arguments to be passed to the `plot` command. + + Returns + ------- + Figure + If `ax` is None, the created figure. Otherwise the figure to which + `ax` is connected. + """ + if exceed: + fig, ax = _do_plot( + self.theoretical_quantiles[::-1], + self.sorted_data, + self.dist, + ax=ax, + line=line, + **plotkwargs, + ) + if xlabel is None: + xlabel = "Probability of Exceedance (%)" + + else: + fig, ax = _do_plot( + self.theoretical_quantiles, + self.sorted_data, + self.dist, + ax=ax, + line=line, + **plotkwargs, + ) + if xlabel is None: + xlabel = "Non-exceedance Probability (%)" + + if ylabel is None: + ylabel = "Sample Quantiles" + + ax.set_xlabel(xlabel) + ax.set_ylabel(ylabel) + _fmt_probplot_axis(ax, self.dist, self.nobs) + + return fig + + +def qqplot( + data, + dist=stats.norm, + distargs=(), + a=0, + loc=0, + scale=1, + fit=False, + line=None, + ax=None, + **plotkwargs, +): + """ + Q-Q plot of the quantiles of x versus the quantiles/ppf of a distribution. + + Can take arguments specifying the parameters for dist or fit them + automatically. (See fit under Parameters.) + + Parameters + ---------- + data : array_like + A 1d data array. + dist : callable + Comparison distribution. The default is + scipy.stats.distributions.norm (a standard normal). + distargs : tuple + A tuple of arguments passed to dist to specify it fully + so dist.ppf may be called. + a : float + Offset for the plotting position of an expected order statistic, for + example. The plotting positions are given by (i - a)/(nobs - 2*a + 1) + for i in range(0,nobs+1) + loc : float + Location parameter for dist + scale : float + Scale parameter for dist + fit : bool + If fit is false, loc, scale, and distargs are passed to the + distribution. If fit is True then the parameters for dist + are fit automatically using dist.fit. The quantiles are formed + from the standardized data, after subtracting the fitted loc + and dividing by the fitted scale. + line : {None, "45", "s", "r", "q"} + Options for the reference line to which the data is compared: + + - "45" - 45-degree line + - "s" - standardized line, the expected order statistics are scaled + by the standard deviation of the given sample and have the mean + added to them + - "r" - A regression line is fit + - "q" - A line is fit through the quartiles. + - None - by default no reference line is added to the plot. + + ax : AxesSubplot, optional + If given, this subplot is used to plot in instead of a new figure being + created. + **plotkwargs + Additional matplotlib arguments to be passed to the `plot` command. + + Returns + ------- + Figure + If `ax` is None, the created figure. Otherwise the figure to which + `ax` is connected. + + See Also + -------- + scipy.stats.probplot + + Notes + ----- + Depends on matplotlib. If `fit` is True then the parameters are fit using + the distribution's fit() method. + + Examples + -------- + >>> import statsmodels.api as sm + >>> from matplotlib import pyplot as plt + >>> data = sm.datasets.longley.load() + >>> exog = sm.add_constant(data.exog) + >>> mod_fit = sm.OLS(data.endog, exog).fit() + >>> res = mod_fit.resid # residuals + >>> fig = sm.qqplot(res) + >>> plt.show() + + qqplot of the residuals against quantiles of t-distribution with 4 degrees + of freedom: + + >>> import scipy.stats as stats + >>> fig = sm.qqplot(res, stats.t, distargs=(4,)) + >>> plt.show() + + qqplot against same as above, but with mean 3 and std 10: + + >>> fig = sm.qqplot(res, stats.t, distargs=(4,), loc=3, scale=10) + >>> plt.show() + + Automatically determine parameters for t distribution including the + loc and scale: + + >>> fig = sm.qqplot(res, stats.t, fit=True, line="45") + >>> plt.show() + + The following plot displays some options, follow the link to see the code. + + .. plot:: plots/graphics_gofplots_qqplot.py + """ + probplot = ProbPlot( + data, dist=dist, distargs=distargs, fit=fit, a=a, loc=loc, scale=scale + ) + fig = probplot.qqplot(ax=ax, line=line, **plotkwargs) + return fig + + +def qqplot_2samples( + data1, data2, xlabel=None, ylabel=None, line=None, ax=None +): + """ + Q-Q Plot of two samples' quantiles. + + Can take either two `ProbPlot` instances or two array-like objects. In the + case of the latter, both inputs will be converted to `ProbPlot` instances + using only the default values - so use `ProbPlot` instances if + finer-grained control of the quantile computations is required. + + Parameters + ---------- + data1 : {array_like, ProbPlot} + Data to plot along x axis. If the sample sizes are unequal, the longer + series is always plotted along the x-axis. + data2 : {array_like, ProbPlot} + Data to plot along y axis. Does not need to have the same number of + observations as data 1. If the sample sizes are unequal, the longer + series is always plotted along the x-axis. + xlabel : {None, str} + User-provided labels for the x-axis. If None (default), + other values are used. + ylabel : {None, str} + User-provided labels for the y-axis. If None (default), + other values are used. + line : {None, "45", "s", "r", q"} + Options for the reference line to which the data is compared: + + - "45" - 45-degree line + - "s" - standardized line, the expected order statistics are scaled + by the standard deviation of the given sample and have the mean + added to them + - "r" - A regression line is fit + - "q" - A line is fit through the quartiles. + - None - by default no reference line is added to the plot. + + ax : AxesSubplot, optional + If given, this subplot is used to plot in instead of a new figure being + created. + + Returns + ------- + Figure + If `ax` is None, the created figure. Otherwise the figure to which + `ax` is connected. + + See Also + -------- + scipy.stats.probplot + + Notes + ----- + 1) Depends on matplotlib. + 2) If `data1` and `data2` are not `ProbPlot` instances, instances will be + created using the default parameters. Therefore, it is recommended to use + `ProbPlot` instance if fine-grained control is needed in the computation + of the quantiles. + + Examples + -------- + >>> import statsmodels.api as sm + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from statsmodels.graphics.gofplots import qqplot_2samples + >>> x = np.random.normal(loc=8.5, scale=2.5, size=37) + >>> y = np.random.normal(loc=8.0, scale=3.0, size=37) + >>> pp_x = sm.ProbPlot(x) + >>> pp_y = sm.ProbPlot(y) + >>> qqplot_2samples(pp_x, pp_y) + >>> plt.show() + + .. plot:: plots/graphics_gofplots_qqplot_2samples.py + + >>> fig = qqplot_2samples(pp_x, pp_y, xlabel=None, ylabel=None, + ... line=None, ax=None) + """ + if not isinstance(data1, ProbPlot): + data1 = ProbPlot(data1) + + if not isinstance(data2, ProbPlot): + data2 = ProbPlot(data2) + if data2.data.shape[0] > data1.data.shape[0]: + fig = data1.qqplot( + xlabel=ylabel, ylabel=xlabel, line=line, other=data2, ax=ax + ) + else: + fig = data2.qqplot( + xlabel=ylabel, + ylabel=xlabel, + line=line, + other=data1, + ax=ax, + swap=True, + ) + + return fig + + +def qqline(ax, line, x=None, y=None, dist=None, fmt="r-", **lineoptions): + """ + Plot a reference line for a qqplot. + + Parameters + ---------- + ax : matplotlib axes instance + The axes on which to plot the line + line : str {"45","r","s","q"} + Options for the reference line to which the data is compared.: + + - "45" - 45-degree line + - "s" - standardized line, the expected order statistics are scaled by + the standard deviation of the given sample and have the mean + added to them + - "r" - A regression line is fit + - "q" - A line is fit through the quartiles. + - None - By default no reference line is added to the plot. + + x : ndarray + X data for plot. Not needed if line is "45". + y : ndarray + Y data for plot. Not needed if line is "45". + dist : scipy.stats.distribution + A scipy.stats distribution, needed if line is "q". + fmt : str, optional + Line format string passed to `plot`. + **lineoptions + Additional arguments to be passed to the `plot` command. + + Notes + ----- + There is no return value. The line is plotted on the given `ax`. + + Examples + -------- + Import the food expenditure dataset. Plot annual food expenditure on x-axis + and household income on y-axis. Use qqline to add regression line into the + plot. + + >>> import statsmodels.api as sm + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from statsmodels.graphics.gofplots import qqline + + >>> foodexp = sm.datasets.engel.load() + >>> x = foodexp.exog + >>> y = foodexp.endog + >>> ax = plt.subplot(111) + >>> plt.scatter(x, y) + >>> ax.set_xlabel(foodexp.exog_name[0]) + >>> ax.set_ylabel(foodexp.endog_name) + >>> qqline(ax, "r", x, y) + >>> plt.show() + + .. plot:: plots/graphics_gofplots_qqplot_qqline.py + """ + lineoptions = lineoptions.copy() + for ls in ("-", "--", "-.", ":"): + if ls in fmt: + lineoptions.setdefault("linestyle", ls) + fmt = fmt.replace(ls, "") + break + for marker in ( + ".", + ",", + "o", + "v", + "^", + "<", + ">", + "1", + "2", + "3", + "4", + "8", + "s", + "p", + "P", + "*", + "h", + "H", + "+", + "x", + "X", + "D", + "d", + "|", + "_", + ): + if marker in fmt: + lineoptions.setdefault("marker", marker) + fmt = fmt.replace(marker, "") + break + if fmt: + lineoptions.setdefault("color", fmt) + + if line == "45": + end_pts = lzip(ax.get_xlim(), ax.get_ylim()) + end_pts[0] = min(end_pts[0]) + end_pts[1] = max(end_pts[1]) + ax.plot(end_pts, end_pts, **lineoptions) + ax.set_xlim(end_pts) + ax.set_ylim(end_pts) + return # does this have any side effects? + if x is None or y is None: + raise ValueError("If line is not 45, x and y cannot be None.") + x = np.array(x) + y = np.array(y) + if line == "r": + # could use ax.lines[0].get_xdata(), get_ydata(), + # but don't know axes are "clean" + y = OLS(y, add_constant(x)).fit().fittedvalues + ax.plot(x, y, **lineoptions) + elif line == "s": + m, b = np.std(y), np.mean(y) + ref_line = x * m + b + ax.plot(x, ref_line, **lineoptions) + elif line == "q": + _check_for(dist, "ppf") + q25 = stats.scoreatpercentile(y, 25) + q75 = stats.scoreatpercentile(y, 75) + theoretical_quartiles = dist.ppf([0.25, 0.75]) + m = (q75 - q25) / np.diff(theoretical_quartiles) + b = q25 - m * theoretical_quartiles[0] + ax.plot(x, m * x + b, **lineoptions) + + +# about 10x faster than plotting_position in sandbox and mstats +def plotting_pos(nobs, a=0.0, b=None): + """ + Generates sequence of plotting positions + + Parameters + ---------- + nobs : int + Number of probability points to plot + a : float, default 0.0 + alpha parameter for the plotting position of an expected order + statistic + b : float, default None + beta parameter for the plotting position of an expected order + statistic. If None, then b is set to a. + + Returns + ------- + ndarray + The plotting positions + + Notes + ----- + The plotting positions are given by (i - a)/(nobs + 1 - a - b) for i in + range(1, nobs+1) + + See Also + -------- + scipy.stats.mstats.plotting_positions + Additional information on alpha and beta + """ + b = a if b is None else b + return (np.arange(1.0, nobs + 1) - a) / (nobs + 1 - a - b) + + +def _fmt_probplot_axis(ax, dist, nobs): + """ + Formats a theoretical quantile axis to display the corresponding + probabilities on the quantiles' scale. + + Parameters + ---------- + ax : AxesSubplot, optional + The axis to be formatted + nobs : scalar + Number of observations in the sample + dist : scipy.stats.distribution + A scipy.stats distribution sufficiently specified to implement its + ppf() method. + + Returns + ------- + There is no return value. This operates on `ax` in place + """ + _check_for(dist, "ppf") + axis_probs = np.linspace(10, 90, 9, dtype=float) + small = np.array([1.0, 2, 5]) + axis_probs = np.r_[small, axis_probs, 100 - small[::-1]] + if nobs >= 50: + axis_probs = np.r_[small / 10, axis_probs, 100 - small[::-1] / 10] + if nobs >= 500: + axis_probs = np.r_[small / 100, axis_probs, 100 - small[::-1] / 100] + axis_probs /= 100.0 + axis_qntls = dist.ppf(axis_probs) + ax.set_xticks(axis_qntls) + ax.set_xticklabels( + [str(lbl) for lbl in (axis_probs * 100)], + rotation=45, + rotation_mode="anchor", + horizontalalignment="right", + verticalalignment="center", + ) + ax.set_xlim([axis_qntls.min(), axis_qntls.max()]) + + +def _do_plot( + x, y, dist=None, line=None, ax=None, fmt="b", step=False, **kwargs +): + """ + Boiler plate plotting function for the `ppplot`, `qqplot`, and + `probplot` methods of the `ProbPlot` class + + Parameters + ---------- + x : array_like + X-axis data to be plotted + y : array_like + Y-axis data to be plotted + dist : scipy.stats.distribution + A scipy.stats distribution, needed if `line` is "q". + line : {"45", "s", "r", "q", None}, default None + Options for the reference line to which the data is compared. + ax : AxesSubplot, optional + If given, this subplot is used to plot in instead of a new figure being + created. + fmt : str, optional + matplotlib-compatible formatting string for the data markers + kwargs : keywords + These are passed to matplotlib.plot + + Returns + ------- + fig : Figure + The figure containing `ax`. + ax : AxesSubplot + The original axes if provided. Otherwise a new instance. + """ + plot_style = { + "marker": "o", + "markerfacecolor": "C0", + "markeredgecolor": "C0", + "linestyle": "none", + } + + plot_style.update(**kwargs) + where = plot_style.pop("where", "pre") + + fig, ax = utils.create_mpl_ax(ax) + ax.set_xmargin(0.02) + + if step: + ax.step(x, y, fmt, where=where, **plot_style) + else: + ax.plot(x, y, fmt, **plot_style) + if line: + if line not in ["r", "q", "45", "s"]: + msg = "%s option for line not understood" % line + raise ValueError(msg) + + qqline(ax, line, x=x, y=y, dist=dist) + + return fig, ax + + +def _check_for(dist, attr="ppf"): + if not hasattr(dist, attr): + raise AttributeError(f"distribution must have a {attr} method") diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/mosaicplot.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/mosaicplot.py new file mode 100644 index 0000000000000000000000000000000000000000..8009854d61ebdf3a6b998a611780ca5f46b62aa0 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/mosaicplot.py @@ -0,0 +1,669 @@ +"""Create a mosaic plot from a contingency table. + +It allows to visualize multivariate categorical data in a rigorous +and informative way. + +see the docstring of the mosaic function for more informations. +""" +# Author: Enrico Giampieri - 21 Jan 2013 + +from statsmodels.compat.python import lrange, lzip + +from itertools import product + +import numpy as np +from numpy import array, cumsum, iterable, r_ +from pandas import DataFrame + +from statsmodels.graphics import utils + +__all__ = ["mosaic"] + + +def _normalize_split(proportion): + """ + return a list of proportions of the available space given the division + if only a number is given, it will assume a split in two pieces + """ + if not iterable(proportion): + if proportion == 0: + proportion = array([0.0, 1.0]) + elif proportion >= 1: + proportion = array([1.0, 0.0]) + elif proportion < 0: + raise ValueError("proportions should be positive," + "given value: {}".format(proportion)) + else: + proportion = array([proportion, 1.0 - proportion]) + proportion = np.asarray(proportion, dtype=float) + if np.any(proportion < 0): + raise ValueError("proportions should be positive," + "given value: {}".format(proportion)) + if np.allclose(proportion, 0): + raise ValueError( + "at least one proportion should be greater than zero" + "given value: {}".format(proportion) + ) + # ok, data are meaningful, so go on + if len(proportion) < 2: + return array([0.0, 1.0]) + left = r_[0, cumsum(proportion)] + left /= left[-1] * 1.0 + return left + + +def _split_rect(x, y, width, height, proportion, horizontal=True, gap=0.05): + """ + Split the given rectangle in n segments whose proportion is specified + along the given axis if a gap is inserted, they will be separated by a + certain amount of space, retaining the relative proportion between them + a gap of 1 correspond to a plot that is half void and the remaining half + space is proportionally divided among the pieces. + """ + x, y, w, h = float(x), float(y), float(width), float(height) + if (w < 0) or (h < 0): + raise ValueError("dimension of the square less than" + "zero w={} h={}".format(w, h)) + proportions = _normalize_split(proportion) + + # extract the starting point and the dimension of each subdivision + # in respect to the unit square + starting = proportions[:-1] + amplitude = proportions[1:] - starting + + # how much each extrema is going to be displaced due to gaps + starting += gap * np.arange(len(proportions) - 1) + + # how much the squares plus the gaps are extended + extension = starting[-1] + amplitude[-1] - starting[0] + + # normalize everything for fit again in the original dimension + starting /= extension + amplitude /= extension + + # bring everything to the original square + starting = (x if horizontal else y) + starting * (w if horizontal else h) + amplitude = amplitude * (w if horizontal else h) + + # create each 4-tuple for each new block + results = [(s, y, a, h) if horizontal else (x, s, w, a) + for s, a in zip(starting, amplitude)] + return results + + +def _reduce_dict(count_dict, partial_key): + """ + Make partial sum on a counter dict. + Given a match for the beginning of the category, it will sum each value. + """ + L = len(partial_key) + count = sum(v for k, v in count_dict.items() if k[:L] == partial_key) + return count + + +def _key_splitting(rect_dict, keys, values, key_subset, horizontal, gap): + """ + Given a dictionary where each entry is a rectangle, a list of key and + value (count of elements in each category) it split each rect accordingly, + as long as the key start with the tuple key_subset. The other keys are + returned without modification. + """ + result = {} + L = len(key_subset) + for name, (x, y, w, h) in rect_dict.items(): + if key_subset == name[:L]: + # split base on the values given + divisions = _split_rect(x, y, w, h, values, horizontal, gap) + for key, rect in zip(keys, divisions): + result[name + (key,)] = rect + else: + result[name] = (x, y, w, h) + return result + + +def _tuplify(obj): + """convert an object in a tuple of strings (even if it is not iterable, + like a single integer number, but keep the string healthy) + """ + if np.iterable(obj) and not isinstance(obj, str): + res = tuple(str(o) for o in obj) + else: + res = (str(obj),) + return res + + +def _categories_level(keys): + """use the Ordered dict to implement a simple ordered set + return each level of each category + [[key_1_level_1,key_2_level_1],[key_1_level_2,key_2_level_2]] + """ + res = [] + for i in zip(*(keys)): + tuplefied = _tuplify(i) + res.append(list({j: None for j in tuplefied})) + return res + + +def _hierarchical_split(count_dict, horizontal=True, gap=0.05): + """ + Split a square in a hierarchical way given a contingency table. + + Hierarchically split the unit square in alternate directions + in proportion to the subdivision contained in the contingency table + count_dict. This is the function that actually perform the tiling + for the creation of the mosaic plot. If the gap array has been specified + it will insert a corresponding amount of space (proportional to the + unit length), while retaining the proportionality of the tiles. + + Parameters + ---------- + count_dict : dict + Dictionary containing the contingency table. + Each category should contain a non-negative number + with a tuple as index. It expects that all the combination + of keys to be represents; if that is not true, will + automatically consider the missing values as 0 + horizontal : bool + The starting direction of the split (by default along + the horizontal axis) + gap : float or array of floats + The list of gaps to be applied on each subdivision. + If the length of the given array is less of the number + of subcategories (or if it's a single number) it will extend + it with exponentially decreasing gaps + + Returns + ------- + base_rect : dict + A dictionary containing the result of the split. + To each key is associated a 4-tuple of coordinates + that are required to create the corresponding rectangle: + + 0 - x position of the lower left corner + 1 - y position of the lower left corner + 2 - width of the rectangle + 3 - height of the rectangle + """ + # this is the unit square that we are going to divide + base_rect = dict([(tuple(), (0, 0, 1, 1))]) + # get the list of each possible value for each level + categories_levels = _categories_level(list(count_dict.keys())) + L = len(categories_levels) + + # recreate the gaps vector starting from an int + if not np.iterable(gap): + gap = [gap / 1.5 ** idx for idx in range(L)] + # extend if it's too short + if len(gap) < L: + last = gap[-1] + gap = list(*gap) + [last / 1.5 ** idx for idx in range(L)] + # trim if it's too long + gap = gap[:L] + # put the count dictionay in order for the keys + # this will allow some code simplification + count_ordered = {k: count_dict[k] + for k in list(product(*categories_levels))} + for cat_idx, cat_enum in enumerate(categories_levels): + # get the partial key up to the actual level + base_keys = list(product(*categories_levels[:cat_idx])) + for key in base_keys: + # for each partial and each value calculate how many + # observation we have in the counting dictionary + part_count = [_reduce_dict(count_ordered, key + (partial,)) + for partial in cat_enum] + # reduce the gap for subsequents levels + new_gap = gap[cat_idx] + # split the given subkeys in the rectangle dictionary + base_rect = _key_splitting(base_rect, cat_enum, part_count, key, + horizontal, new_gap) + horizontal = not horizontal + return base_rect + + +def _single_hsv_to_rgb(hsv): + """Transform a color from the hsv space to the rgb.""" + from matplotlib.colors import hsv_to_rgb + return hsv_to_rgb(array(hsv).reshape(1, 1, 3)).reshape(3) + + +def _create_default_properties(data): + """"Create the default properties of the mosaic given the data + first it will varies the color hue (first category) then the color + saturation (second category) and then the color value + (third category). If a fourth category is found, it will put + decoration on the rectangle. Does not manage more than four + level of categories + """ + categories_levels = _categories_level(list(data.keys())) + Nlevels = len(categories_levels) + # first level, the hue + L = len(categories_levels[0]) + # hue = np.linspace(1.0, 0.0, L+1)[:-1] + hue = np.linspace(0.0, 1.0, L + 2)[:-2] + # second level, the saturation + L = len(categories_levels[1]) if Nlevels > 1 else 1 + saturation = np.linspace(0.5, 1.0, L + 1)[:-1] + # third level, the value + L = len(categories_levels[2]) if Nlevels > 2 else 1 + value = np.linspace(0.5, 1.0, L + 1)[:-1] + # fourth level, the hatch + L = len(categories_levels[3]) if Nlevels > 3 else 1 + hatch = ['', '/', '-', '|', '+'][:L + 1] + # convert in list and merge with the levels + hue = lzip(list(hue), categories_levels[0]) + saturation = lzip(list(saturation), + categories_levels[1] if Nlevels > 1 else ['']) + value = lzip(list(value), + categories_levels[2] if Nlevels > 2 else ['']) + hatch = lzip(list(hatch), + categories_levels[3] if Nlevels > 3 else ['']) + # create the properties dictionary + properties = {} + for h, s, v, t in product(hue, saturation, value, hatch): + hv, hn = h + sv, sn = s + vv, vn = v + tv, tn = t + level = (hn,) + ((sn,) if sn else tuple()) + level = level + ((vn,) if vn else tuple()) + level = level + ((tn,) if tn else tuple()) + hsv = array([hv, sv, vv]) + prop = {'color': _single_hsv_to_rgb(hsv), 'hatch': tv, 'lw': 0} + properties[level] = prop + return properties + + +def _normalize_data(data, index): + """normalize the data to a dict with tuples of strings as keys + right now it works with: + + 0 - dictionary (or equivalent mappable) + 1 - pandas.Series with simple or hierarchical indexes + 2 - numpy.ndarrays + 3 - everything that can be converted to a numpy array + 4 - pandas.DataFrame (via the _normalize_dataframe function) + """ + # if data is a dataframe we need to take a completely new road + # before coming back here. Use the hasattr to avoid importing + # pandas explicitly + if hasattr(data, 'pivot') and hasattr(data, 'groupby'): + data = _normalize_dataframe(data, index) + index = None + # can it be used as a dictionary? + try: + items = list(data.items()) + except AttributeError: + # ok, I cannot use the data as a dictionary + # Try to convert it to a numpy array, or die trying + data = np.asarray(data) + temp = {} + for idx in np.ndindex(data.shape): + name = tuple(i for i in idx) + temp[name] = data[idx] + data = temp + items = list(data.items()) + # make all the keys a tuple, even if simple numbers + data = {_tuplify(k): v for k, v in items} + categories_levels = _categories_level(list(data.keys())) + # fill the void in the counting dictionary + indexes = product(*categories_levels) + contingency = {k: data.get(k, 0) for k in indexes} + data = contingency + # reorder the keys order according to the one specified by the user + # or if the index is None convert it into a simple list + # right now it does not do any check, but can be modified in the future + index = lrange(len(categories_levels)) if index is None else index + contingency = {} + for key, value in data.items(): + new_key = tuple(key[i] for i in index) + contingency[new_key] = value + data = contingency + return data + + +def _normalize_dataframe(dataframe, index): + """Take a pandas DataFrame and count the element present in the + given columns, return a hierarchical index on those columns + """ + #groupby the given keys, extract the same columns and count the element + # then collapse them with a mean + data = dataframe[index].dropna() + grouped = data.groupby(index, sort=False, observed=False) + counted = grouped[index].count() + averaged = counted.mean(axis=1) + # Fill empty missing with 0, see GH5639 + averaged = averaged.fillna(0.0) + return averaged + + +def _statistical_coloring(data): + """evaluate colors from the indipendence properties of the matrix + It will encounter problem if one category has all zeros + """ + data = _normalize_data(data, None) + categories_levels = _categories_level(list(data.keys())) + Nlevels = len(categories_levels) + total = 1.0 * sum(v for v in data.values()) + # count the proportion of observation + # for each level that has the given name + # at each level + levels_count = [] + for level_idx in range(Nlevels): + proportion = {} + for level in categories_levels[level_idx]: + proportion[level] = 0.0 + for key, value in data.items(): + if level == key[level_idx]: + proportion[level] += value + proportion[level] /= total + levels_count.append(proportion) + # for each key I obtain the expected value + # and it's standard deviation from a binomial distribution + # under the hipothesys of independence + expected = {} + for key, value in data.items(): + base = 1.0 + for i, k in enumerate(key): + base *= levels_count[i][k] + expected[key] = base * total, np.sqrt(total * base * (1.0 - base)) + # now we have the standard deviation of distance from the + # expected value for each tile. We create the colors from this + sigmas = {k: (data[k] - m) / s for k, (m, s) in expected.items()} + props = {} + for key, dev in sigmas.items(): + red = 0.0 if dev < 0 else (dev / (1 + dev)) + blue = 0.0 if dev > 0 else (dev / (-1 + dev)) + green = (1.0 - red - blue) / 2.0 + hatch = 'x' if dev > 2 else 'o' if dev < -2 else '' + props[key] = {'color': [red, green, blue], 'hatch': hatch} + return props + + +def _get_position(x, w, h, W): + if W == 0: + return x + return (x + w / 2.0) * w * h / W + + +def _create_labels(rects, horizontal, ax, rotation): + """find the position of the label for each value of each category + + right now it supports only up to the four categories + + ax: the axis on which the label should be applied + rotation: the rotation list for each side + """ + categories = _categories_level(list(rects.keys())) + if len(categories) > 4: + msg = ("maximum of 4 level supported for axes labeling... and 4" + "is already a lot of levels, are you sure you need them all?") + raise ValueError(msg) + labels = {} + #keep it fixed as will be used a lot of times + items = list(rects.items()) + vertical = not horizontal + + #get the axis ticks and labels locator to put the correct values! + ax2 = ax.twinx() + ax3 = ax.twiny() + #this is the order of execution for horizontal disposition + ticks_pos = [ax.set_xticks, ax.set_yticks, ax3.set_xticks, ax2.set_yticks] + ticks_lab = [ax.set_xticklabels, ax.set_yticklabels, + ax3.set_xticklabels, ax2.set_yticklabels] + #for the vertical one, rotate it by one + if vertical: + ticks_pos = ticks_pos[1:] + ticks_pos[:1] + ticks_lab = ticks_lab[1:] + ticks_lab[:1] + #clean them + for pos, lab in zip(ticks_pos, ticks_lab): + pos([]) + lab([]) + #for each level, for each value in the level, take the mean of all + #the sublevel that correspond to that partial key + for level_idx, level in enumerate(categories): + #this dictionary keep the labels only for this level + level_ticks = dict() + for value in level: + #to which level it should refer to get the preceding + #values of labels? it's rather a tricky question... + #this is dependent on the side. It's a very crude management + #but I couldn't think a more general way... + if horizontal: + if level_idx == 3: + index_select = [-1, -1, -1] + else: + index_select = [+0, -1, -1] + else: + if level_idx == 3: + index_select = [+0, -1, +0] + else: + index_select = [-1, -1, -1] + #now I create the base key name and append the current value + #It will search on all the rects to find the corresponding one + #and use them to evaluate the mean position + basekey = tuple(categories[i][index_select[i]] + for i in range(level_idx)) + basekey = basekey + (value,) + subset = {k: v for k, v in items + if basekey == k[:level_idx + 1]} + #now I extract the center of all the tiles and make a weighted + #mean of all these center on the area of the tile + #this should give me the (more or less) correct position + #of the center of the category + + vals = list(subset.values()) + W = sum(w * h for (x, y, w, h) in vals) + x_lab = sum(_get_position(x, w, h, W) for (x, y, w, h) in vals) + y_lab = sum(_get_position(y, h, w, W) for (x, y, w, h) in vals) + #now base on the ordering, select which position to keep + #needs to be written in a more general form of 4 level are enough? + #should give also the horizontal and vertical alignment + side = (level_idx + vertical) % 4 + level_ticks[value] = y_lab if side % 2 else x_lab + #now we add the labels of this level to the correct axis + + ticks_pos[level_idx](list(level_ticks.values())) + ticks_lab[level_idx](list(level_ticks.keys()), + rotation=rotation[level_idx]) + return labels + + +def mosaic(data, index=None, ax=None, horizontal=True, gap=0.005, + properties=lambda key: None, labelizer=None, + title='', statistic=False, axes_label=True, + label_rotation=0.0): + """Create a mosaic plot from a contingency table. + + It allows to visualize multivariate categorical data in a rigorous + and informative way. + + Parameters + ---------- + data : {dict, Series, ndarray, DataFrame} + The contingency table that contains the data. + Each category should contain a non-negative number + with a tuple as index. It expects that all the combination + of keys to be represents; if that is not true, will + automatically consider the missing values as 0. The order + of the keys will be the same as the one of insertion. + If a dict of a Series (or any other dict like object) + is used, it will take the keys as labels. If a + np.ndarray is provided, it will generate a simple + numerical labels. + index : list, optional + Gives the preferred order for the category ordering. If not specified + will default to the given order. It does not support named indexes + for hierarchical Series. If a DataFrame is provided, it expects + a list with the name of the columns. + ax : Axes, optional + The graph where display the mosaic. If not given, will + create a new figure + horizontal : bool, optional + The starting direction of the split (by default along + the horizontal axis) + gap : {float, sequence[float]} + The list of gaps to be applied on each subdivision. + If the length of the given array is less of the number + of subcategories (or if it's a single number) it will extend + it with exponentially decreasing gaps + properties : dict[str, callable], optional + A function that for each tile in the mosaic take the key + of the tile and returns the dictionary of properties + of the generated Rectangle, like color, hatch or similar. + A default properties set will be provided fot the keys whose + color has not been defined, and will use color variation to help + visually separates the various categories. It should return None + to indicate that it should use the default property for the tile. + A dictionary of the properties for each key can be passed, + and it will be internally converted to the correct function + labelizer : dict[str, callable], optional + A function that generate the text to display at the center of + each tile base on the key of that tile + title : str, optional + The title of the axis + statistic : bool, optional + If true will use a crude statistical model to give colors to the plot. + If the tile has a constraint that is more than 2 standard deviation + from the expected value under independence hypothesis, it will + go from green to red (for positive deviations, blue otherwise) and + will acquire an hatching when crosses the 3 sigma. + axes_label : bool, optional + Show the name of each value of each category + on the axis (default) or hide them. + label_rotation : {float, list[float]} + The rotation of the axis label (if present). If a list is given + each axis can have a different rotation + + Returns + ------- + fig : Figure + The figure containing the plot. + rects : dict + A dictionary that has the same keys of the original + dataset, that holds a reference to the coordinates of the + tile and the Rectangle that represent it. + + References + ---------- + A Brief History of the Mosaic Display + Michael Friendly, York University, Psychology Department + Journal of Computational and Graphical Statistics, 2001 + + Mosaic Displays for Loglinear Models. + Michael Friendly, York University, Psychology Department + Proceedings of the Statistical Graphics Section, 1992, 61-68. + + Mosaic displays for multi-way contingency tables. + Michael Friendly, York University, Psychology Department + Journal of the american statistical association + March 1994, Vol. 89, No. 425, Theory and Methods + + Examples + -------- + >>> import numpy as np + >>> import pandas as pd + >>> import matplotlib.pyplot as plt + >>> from statsmodels.graphics.mosaicplot import mosaic + + The most simple use case is to take a dictionary and plot the result + + >>> data = {'a': 10, 'b': 15, 'c': 16} + >>> mosaic(data, title='basic dictionary') + >>> plt.show() + + A more useful example is given by a dictionary with multiple indices. + In this case we use a wider gap to a better visual separation of the + resulting plot + + >>> data = {('a', 'b'): 1, ('a', 'c'): 2, ('d', 'b'): 3, ('d', 'c'): 4} + >>> mosaic(data, gap=0.05, title='complete dictionary') + >>> plt.show() + + The same data can be given as a simple or hierarchical indexed Series + + >>> rand = np.random.random + >>> from itertools import product + >>> tuples = list(product(['bar', 'baz', 'foo', 'qux'], ['one', 'two'])) + >>> index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second']) + >>> data = pd.Series(rand(8), index=index) + >>> mosaic(data, title='hierarchical index series') + >>> plt.show() + + The third accepted data structure is the np array, for which a + very simple index will be created. + + >>> rand = np.random.random + >>> data = 1+rand((2,2)) + >>> mosaic(data, title='random non-labeled array') + >>> plt.show() + + If you need to modify the labeling and the coloring you can give + a function tocreate the labels and one with the graphical properties + starting from the key tuple + + >>> data = {'a': 10, 'b': 15, 'c': 16} + >>> props = lambda key: {'color': 'r' if 'a' in key else 'gray'} + >>> labelizer = lambda k: {('a',): 'first', ('b',): 'second', + ... ('c',): 'third'}[k] + >>> mosaic(data, title='colored dictionary', properties=props, + ... labelizer=labelizer) + >>> plt.show() + + Using a DataFrame as source, specifying the name of the columns of interest + + >>> gender = ['male', 'male', 'male', 'female', 'female', 'female'] + >>> pet = ['cat', 'dog', 'dog', 'cat', 'dog', 'cat'] + >>> data = pd.DataFrame({'gender': gender, 'pet': pet}) + >>> mosaic(data, ['pet', 'gender'], title='DataFrame as Source') + >>> plt.show() + + .. plot :: plots/graphics_mosaicplot_mosaic.py + """ + if isinstance(data, DataFrame) and index is None: + raise ValueError("You must pass an index if data is a DataFrame." + " See examples.") + + from matplotlib.patches import Rectangle + + #from pylab import Rectangle + fig, ax = utils.create_mpl_ax(ax) + # normalize the data to a dict with tuple of strings as keys + data = _normalize_data(data, index) + # split the graph into different areas + rects = _hierarchical_split(data, horizontal=horizontal, gap=gap) + # if there is no specified way to create the labels + # create a default one + if labelizer is None: + labelizer = lambda k: "\n".join(k) + if statistic: + default_props = _statistical_coloring(data) + else: + default_props = _create_default_properties(data) + if isinstance(properties, dict): + color_dict = properties + properties = lambda key: color_dict.get(key, None) + for k, v in rects.items(): + # create each rectangle and put a label on it + x, y, w, h = v + conf = properties(k) + props = conf if conf else default_props[k] + text = labelizer(k) + Rect = Rectangle((x, y), w, h, label=text, **props) + ax.add_patch(Rect) + ax.text(x + w / 2, y + h / 2, text, ha='center', + va='center', size='smaller') + #creating the labels on the axis + #o clearing it + if axes_label: + if np.iterable(label_rotation): + rotation = label_rotation + else: + rotation = [label_rotation] * 4 + labels = _create_labels(rects, horizontal, ax, rotation) + else: + ax.set_xticks([]) + ax.set_xticklabels([]) + ax.set_yticks([]) + ax.set_yticklabels([]) + ax.set_title(title) + return fig, rects diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/plot_grids.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/plot_grids.py new file mode 100644 index 0000000000000000000000000000000000000000..bc67a2e230286769f24454b874c54834cf2b845f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/plot_grids.py @@ -0,0 +1,177 @@ +'''create scatterplot with confidence ellipsis + +Author: Josef Perktold +License: BSD-3 + +TODO: update script to use sharex, sharey, and visible=False + see https://www.scipy.org/Cookbook/Matplotlib/Multiple_Subplots_with_One_Axis_Label + for sharex I need to have the ax of the last_row when editing the earlier + rows. Or you axes_grid1, imagegrid + http://matplotlib.sourceforge.net/mpl_toolkits/axes_grid/users/overview.html +''' + + +import numpy as np +from scipy import stats + +from . import utils + +__all__ = ['scatter_ellipse'] + + +def _make_ellipse(mean, cov, ax, level=0.95, color=None): + """Support function for scatter_ellipse.""" + from matplotlib.patches import Ellipse + + v, w = np.linalg.eigh(cov) + u = w[0] / np.linalg.norm(w[0]) + angle = np.arctan(u[1]/u[0]) + angle = 180 * angle / np.pi # convert to degrees + v = 2 * np.sqrt(v * stats.chi2.ppf(level, 2)) #get size corresponding to level + ell = Ellipse(mean[:2], v[0], v[1], angle=180 + angle, facecolor='none', + edgecolor=color, + #ls='dashed', #for debugging + lw=1.5) + ell.set_clip_box(ax.bbox) + ell.set_alpha(0.5) + ax.add_artist(ell) + + +def scatter_ellipse(data, level=0.9, varnames=None, ell_kwds=None, + plot_kwds=None, add_titles=False, keep_ticks=False, + fig=None): + """Create a grid of scatter plots with confidence ellipses. + + ell_kwds, plot_kdes not used yet + + looks ok with 5 or 6 variables, too crowded with 8, too empty with 1 + + Parameters + ---------- + data : array_like + Input data. + level : scalar, optional + Default is 0.9. + varnames : list[str], optional + Variable names. Used for y-axis labels, and if `add_titles` is True + also for titles. If not given, integers 1..data.shape[1] are used. + ell_kwds : dict, optional + UNUSED + plot_kwds : dict, optional + UNUSED + add_titles : bool, optional + Whether or not to add titles to each subplot. Default is False. + Titles are constructed from `varnames`. + keep_ticks : bool, optional + If False (default), remove all axis ticks. + fig : Figure, optional + If given, this figure is simply returned. Otherwise a new figure is + created. + + Returns + ------- + Figure + If `fig` is None, the created figure. Otherwise `fig` itself. + + Examples + -------- + >>> import statsmodels.api as sm + >>> import matplotlib.pyplot as plt + >>> import numpy as np + + >>> from statsmodels.graphics.plot_grids import scatter_ellipse + >>> data = sm.datasets.statecrime.load_pandas().data + >>> fig = plt.figure(figsize=(8,8)) + >>> scatter_ellipse(data, varnames=data.columns, fig=fig) + >>> plt.show() + + .. plot:: plots/graphics_plot_grids_scatter_ellipse.py + """ + fig = utils.create_mpl_fig(fig) + import matplotlib.ticker as mticker + + data = np.asanyarray(data) #needs mean and cov + nvars = data.shape[1] + if varnames is None: + #assuming single digit, nvars<=10 else use 'var%2d' + varnames = ['var%d' % i for i in range(nvars)] + + plot_kwds_ = dict(ls='none', marker='.', color='k', alpha=0.5) + if plot_kwds: + plot_kwds_.update(plot_kwds) + + ell_kwds_= dict(color='k') + if ell_kwds: + ell_kwds_.update(ell_kwds) + + dmean = data.mean(0) + dcov = np.cov(data, rowvar=0) + + for i in range(1, nvars): + #print '---' + ax_last=None + for j in range(i): + #print i,j, i*(nvars-1)+j+1 + ax = fig.add_subplot(nvars-1, nvars-1, (i-1)*(nvars-1)+j+1) +## #sharey=ax_last) #sharey does not allow empty ticks? +## if j == 0: +## print 'new ax_last', j +## ax_last = ax +## ax.set_ylabel(varnames[i]) + #TODO: make sure we have same xlim and ylim + + formatter = mticker.FormatStrFormatter('% 3.1f') + ax.yaxis.set_major_formatter(formatter) + ax.xaxis.set_major_formatter(formatter) + + idx = np.array([j,i]) + ax.plot(*data[:,idx].T, **plot_kwds_) + + if np.isscalar(level): + level = [level] + for alpha in level: + _make_ellipse(dmean[idx], dcov[idx[:,None], idx], ax, level=alpha, + **ell_kwds_) + + if add_titles: + ax.set_title(f'{varnames[i]}-{varnames[j]}') + if not ax.get_subplotspec().is_first_col(): + if not keep_ticks: + ax.set_yticks([]) + else: + ax.yaxis.set_major_locator(mticker.MaxNLocator(3)) + else: + ax.set_ylabel(varnames[i]) + if ax.get_subplotspec().is_last_row(): + ax.set_xlabel(varnames[j]) + else: + if not keep_ticks: + ax.set_xticks([]) + else: + ax.xaxis.set_major_locator(mticker.MaxNLocator(3)) + + dcorr = np.corrcoef(data, rowvar=0) + dc = dcorr[idx[:,None], idx] + xlim = ax.get_xlim() + ylim = ax.get_ylim() +## xt = xlim[0] + 0.1 * (xlim[1] - xlim[0]) +## yt = ylim[0] + 0.1 * (ylim[1] - ylim[0]) +## if dc[1,0] < 0 : +## yt = ylim[0] + 0.1 * (ylim[1] - ylim[0]) +## else: +## yt = ylim[1] - 0.2 * (ylim[1] - ylim[0]) + yrangeq = ylim[0] + 0.4 * (ylim[1] - ylim[0]) + if dc[1,0] < -0.25 or (dc[1,0] < 0.25 and dmean[idx][1] > yrangeq): + yt = ylim[0] + 0.1 * (ylim[1] - ylim[0]) + else: + yt = ylim[1] - 0.2 * (ylim[1] - ylim[0]) + xt = xlim[0] + 0.1 * (xlim[1] - xlim[0]) + ax.text(xt, yt, '$\\rho=%0.2f$'% dc[1,0]) + + for ax in fig.axes: + if ax.get_subplotspec().is_last_row(): # or ax.is_first_col(): + ax.xaxis.set_major_locator(mticker.MaxNLocator(3)) + if ax.get_subplotspec().is_first_col(): + ax.yaxis.set_major_locator(mticker.MaxNLocator(3)) + + return fig diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/plottools.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/plottools.py new file mode 100644 index 0000000000000000000000000000000000000000..516b85606d7a0c540c1185a623e3a80bb600f0a5 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/plottools.py @@ -0,0 +1,27 @@ +import numpy as np + + +def rainbow(n): + """ + Returns a list of colors sampled at equal intervals over the spectrum. + + Parameters + ---------- + n : int + The number of colors to return + + Returns + ------- + R : (n,3) array + An of rows of RGB color values + + Notes + ----- + Converts from HSV coordinates (0, 1, 1) to (1, 1, 1) to RGB. Based on + the Sage function of the same name. + """ + from matplotlib import colors + R = np.ones((1,n,3)) + R[0,:,0] = np.linspace(0, 1, n, endpoint=False) + #Note: could iterate and use colorsys.hsv_to_rgb + return colors.hsv_to_rgb(R).squeeze() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/regressionplots.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/regressionplots.py new file mode 100644 index 0000000000000000000000000000000000000000..a9d5d04c2fc10582915b090c22b6fdb2a849f198 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/regressionplots.py @@ -0,0 +1,1296 @@ +'''Partial Regression plot and residual plots to find misspecification + + +Author: Josef Perktold +License: BSD-3 +Created: 2011-01-23 + +update +2011-06-05 : start to convert example to usable functions +2011-10-27 : docstrings + +''' +from statsmodels.compat.pandas import Appender +from statsmodels.compat.python import lrange, lzip + +import numpy as np +import pandas as pd +from patsy import dmatrix + +from statsmodels.genmod.generalized_estimating_equations import GEE +from statsmodels.genmod.generalized_linear_model import GLM +from statsmodels.graphics import utils +from statsmodels.nonparametric.smoothers_lowess import lowess +from statsmodels.regression.linear_model import GLS, OLS, WLS +from statsmodels.sandbox.regression.predstd import wls_prediction_std +from statsmodels.tools.tools import maybe_unwrap_results + +from ._regressionplots_doc import ( + _plot_added_variable_doc, + _plot_ceres_residuals_doc, + _plot_influence_doc, + _plot_leverage_resid2_doc, + _plot_partial_residuals_doc, +) + +__all__ = ['plot_fit', 'plot_regress_exog', 'plot_partregress', 'plot_ccpr', + 'plot_regress_exog', 'plot_partregress_grid', 'plot_ccpr_grid', + 'add_lowess', 'abline_plot', 'influence_plot', + 'plot_leverage_resid2', 'added_variable_resids', + 'partial_resids', 'ceres_resids', 'plot_added_variable', + 'plot_partial_residuals', 'plot_ceres_residuals'] + +#TODO: consider moving to influence module +def _high_leverage(results): + #TODO: replace 1 with k_constant + return 2. * (results.df_model + 1)/results.nobs + + +def add_lowess(ax, lines_idx=0, frac=.2, **lowess_kwargs): + """ + Add Lowess line to a plot. + + Parameters + ---------- + ax : AxesSubplot + The Axes to which to add the plot + lines_idx : int + This is the line on the existing plot to which you want to add + a smoothed lowess line. + frac : float + The fraction of the points to use when doing the lowess fit. + lowess_kwargs + Additional keyword arguments are passes to lowess. + + Returns + ------- + Figure + The figure that holds the instance. + """ + y0 = ax.get_lines()[lines_idx]._y + x0 = ax.get_lines()[lines_idx]._x + lres = lowess(y0, x0, frac=frac, **lowess_kwargs) + ax.plot(lres[:, 0], lres[:, 1], 'r', lw=1.5) + return ax.figure + + +def plot_fit(results, exog_idx, y_true=None, ax=None, vlines=True, **kwargs): + """ + Plot fit against one regressor. + + This creates one graph with the scatterplot of observed values + compared to fitted values. + + Parameters + ---------- + results : Results + A result instance with resid, model.endog and model.exog as + attributes. + exog_idx : {int, str} + Name or index of regressor in exog matrix. + y_true : array_like. optional + If this is not None, then the array is added to the plot. + ax : AxesSubplot, optional + If given, this subplot is used to plot in instead of a new figure being + created. + vlines : bool, optional + If this not True, then the uncertainty (pointwise prediction intervals) of the fit is not + plotted. + **kwargs + The keyword arguments are passed to the plot command for the fitted + values points. + + Returns + ------- + Figure + If `ax` is None, the created figure. Otherwise the figure to which + `ax` is connected. + + Examples + -------- + Load the Statewide Crime data set and perform linear regression with + `poverty` and `hs_grad` as variables and `murder` as the response + + >>> import statsmodels.api as sm + >>> import matplotlib.pyplot as plt + + >>> data = sm.datasets.statecrime.load_pandas().data + >>> murder = data['murder'] + >>> X = data[['poverty', 'hs_grad']] + + >>> X["constant"] = 1 + >>> y = murder + >>> model = sm.OLS(y, X) + >>> results = model.fit() + + Create a plot just for the variable 'Poverty.' + Note that vertical bars representing uncertainty are plotted since vlines is true + + >>> fig, ax = plt.subplots() + >>> fig = sm.graphics.plot_fit(results, 0, ax=ax) + >>> ax.set_ylabel("Murder Rate") + >>> ax.set_xlabel("Poverty Level") + >>> ax.set_title("Linear Regression") + + >>> plt.show() + + .. plot:: plots/graphics_plot_fit_ex.py + """ + + fig, ax = utils.create_mpl_ax(ax) + + exog_name, exog_idx = utils.maybe_name_or_idx(exog_idx, results.model) + results = maybe_unwrap_results(results) + + #maybe add option for wendog, wexog + y = results.model.endog + x1 = results.model.exog[:, exog_idx] + x1_argsort = np.argsort(x1) + y = y[x1_argsort] + x1 = x1[x1_argsort] + + ax.plot(x1, y, 'bo', label=results.model.endog_names) + if y_true is not None: + ax.plot(x1, y_true[x1_argsort], 'b-', label='True values') + title = 'Fitted values versus %s' % exog_name + + ax.plot(x1, results.fittedvalues[x1_argsort], 'D', color='r', + label='fitted', **kwargs) + if vlines is True: + _, iv_l, iv_u = wls_prediction_std(results) + ax.vlines(x1, iv_l[x1_argsort], iv_u[x1_argsort], linewidth=1, + color='k', alpha=.7) + #ax.fill_between(x1, iv_l[x1_argsort], iv_u[x1_argsort], alpha=0.1, + # color='k') + ax.set_title(title) + ax.set_xlabel(exog_name) + ax.set_ylabel(results.model.endog_names) + ax.legend(loc='best', numpoints=1) + + return fig + + +def plot_regress_exog(results, exog_idx, fig=None): + """Plot regression results against one regressor. + + This plots four graphs in a 2 by 2 figure: 'endog versus exog', + 'residuals versus exog', 'fitted versus exog' and + 'fitted plus residual versus exog' + + Parameters + ---------- + results : result instance + A result instance with resid, model.endog and model.exog as attributes. + exog_idx : int or str + Name or index of regressor in exog matrix. + fig : Figure, optional + If given, this figure is simply returned. Otherwise a new figure is + created. + + Returns + ------- + Figure + The value of `fig` if provided. Otherwise a new instance. + + Examples + -------- + Load the Statewide Crime data set and build a model with regressors + including the rate of high school graduation (hs_grad), population in urban + areas (urban), households below poverty line (poverty), and single person + households (single). Outcome variable is the murder rate (murder). + + Build a 2 by 2 figure based on poverty showing fitted versus actual murder + rate, residuals versus the poverty rate, partial regression plot of poverty, + and CCPR plot for poverty rate. + + >>> import statsmodels.api as sm + >>> import matplotlib.pyplot as plt + >>> import statsmodels.formula.api as smf + + >>> fig = plt.figure(figsize=(8, 6)) + >>> crime_data = sm.datasets.statecrime.load_pandas() + >>> results = smf.ols('murder ~ hs_grad + urban + poverty + single', + ... data=crime_data.data).fit() + >>> sm.graphics.plot_regress_exog(results, 'poverty', fig=fig) + >>> plt.show() + + .. plot:: plots/graphics_regression_regress_exog.py + """ + + fig = utils.create_mpl_fig(fig) + + exog_name, exog_idx = utils.maybe_name_or_idx(exog_idx, results.model) + results = maybe_unwrap_results(results) + + #maybe add option for wendog, wexog + y_name = results.model.endog_names + x1 = results.model.exog[:, exog_idx] + prstd, iv_l, iv_u = wls_prediction_std(results) + + ax = fig.add_subplot(2, 2, 1) + ax.plot(x1, results.model.endog, 'o', color='b', alpha=0.9, label=y_name) + ax.plot(x1, results.fittedvalues, 'D', color='r', label='fitted', + alpha=.5) + ax.vlines(x1, iv_l, iv_u, linewidth=1, color='k', alpha=.7) + ax.set_title('Y and Fitted vs. X', fontsize='large') + ax.set_xlabel(exog_name) + ax.set_ylabel(y_name) + ax.legend(loc='best') + + ax = fig.add_subplot(2, 2, 2) + ax.plot(x1, results.resid, 'o') + ax.axhline(y=0, color='black') + ax.set_title('Residuals versus %s' % exog_name, fontsize='large') + ax.set_xlabel(exog_name) + ax.set_ylabel("resid") + + ax = fig.add_subplot(2, 2, 3) + exog_noti = np.ones(results.model.exog.shape[1], bool) + exog_noti[exog_idx] = False + exog_others = results.model.exog[:, exog_noti] + from pandas import Series + fig = plot_partregress(results.model.data.orig_endog, + Series(x1, name=exog_name, + index=results.model.data.row_labels), + exog_others, obs_labels=False, ax=ax) + ax.set_title('Partial regression plot', fontsize='large') + #ax.set_ylabel("Fitted values") + #ax.set_xlabel(exog_name) + + ax = fig.add_subplot(2, 2, 4) + fig = plot_ccpr(results, exog_idx, ax=ax) + ax.set_title('CCPR Plot', fontsize='large') + #ax.set_xlabel(exog_name) + #ax.set_ylabel("Fitted values + resids") + + fig.suptitle('Regression Plots for %s' % exog_name, fontsize="large") + + fig.tight_layout() + + fig.subplots_adjust(top=.90) + return fig + + +def _partial_regression(endog, exog_i, exog_others): + """Partial regression. + + regress endog on exog_i conditional on exog_others + + uses OLS + + Parameters + ---------- + endog : array_like + exog : array_like + exog_others : array_like + + Returns + ------- + res1c : OLS results instance + + (res1a, res1b) : tuple of OLS results instances + results from regression of endog on exog_others and of exog_i on + exog_others + """ + #FIXME: This function does not appear to be used. + res1a = OLS(endog, exog_others).fit() + res1b = OLS(exog_i, exog_others).fit() + res1c = OLS(res1a.resid, res1b.resid).fit() + + return res1c, (res1a, res1b) + + +def plot_partregress(endog, exog_i, exog_others, data=None, + title_kwargs={}, obs_labels=True, label_kwargs={}, + ax=None, ret_coords=False, eval_env=1, **kwargs): + """Plot partial regression for a single regressor. + + Parameters + ---------- + endog : {ndarray, str} + The endogenous or response variable. If string is given, you can use a + arbitrary translations as with a formula. + exog_i : {ndarray, str} + The exogenous, explanatory variable. If string is given, you can use a + arbitrary translations as with a formula. + exog_others : {ndarray, list[str]} + Any other exogenous, explanatory variables. If a list of strings is + given, each item is a term in formula. You can use a arbitrary + translations as with a formula. The effect of these variables will be + removed by OLS regression. + data : {DataFrame, dict} + Some kind of data structure with names if the other variables are + given as strings. + title_kwargs : dict + Keyword arguments to pass on for the title. The key to control the + fonts is fontdict. + obs_labels : {bool, array_like} + Whether or not to annotate the plot points with their observation + labels. If obs_labels is a boolean, the point labels will try to do + the right thing. First it will try to use the index of data, then + fall back to the index of exog_i. Alternatively, you may give an + array-like object corresponding to the observation numbers. + label_kwargs : dict + Keyword arguments that control annotate for the observation labels. + ax : AxesSubplot, optional + If given, this subplot is used to plot in instead of a new figure being + created. + ret_coords : bool + If True will return the coordinates of the points in the plot. You + can use this to add your own annotations. + eval_env : int + Patsy eval environment if user functions and formulas are used in + defining endog or exog. + **kwargs + The keyword arguments passed to plot for the points. + + Returns + ------- + fig : Figure + If `ax` is None, the created figure. Otherwise the figure to which + `ax` is connected. + coords : list, optional + If ret_coords is True, return a tuple of arrays (x_coords, y_coords). + + See Also + -------- + plot_partregress_grid : Plot partial regression for a set of regressors. + + Notes + ----- + The slope of the fitted line is the that of `exog_i` in the full + multiple regression. The individual points can be used to assess the + influence of points on the estimated coefficient. + + Examples + -------- + Load the Statewide Crime data set and plot partial regression of the rate + of high school graduation (hs_grad) on the murder rate(murder). + + The effects of the percent of the population living in urban areas (urban), + below the poverty line (poverty) , and in a single person household (single) + are removed by OLS regression. + + >>> import statsmodels.api as sm + >>> import matplotlib.pyplot as plt + + >>> crime_data = sm.datasets.statecrime.load_pandas() + >>> sm.graphics.plot_partregress(endog='murder', exog_i='hs_grad', + ... exog_others=['urban', 'poverty', 'single'], + ... data=crime_data.data, obs_labels=False) + >>> plt.show() + + .. plot:: plots/graphics_regression_partregress.py + + More detailed examples can be found in the Regression Plots notebook + on the examples page. + """ + #NOTE: there is no interaction between possible missing data and + #obs_labels yet, so this will need to be tweaked a bit for this case + fig, ax = utils.create_mpl_ax(ax) + + # strings, use patsy to transform to data + if isinstance(endog, str): + endog = dmatrix(endog + "-1", data, eval_env=eval_env) + + if isinstance(exog_others, str): + RHS = dmatrix(exog_others, data, eval_env=eval_env) + elif isinstance(exog_others, list): + RHS = "+".join(exog_others) + RHS = dmatrix(RHS, data, eval_env=eval_env) + else: + RHS = exog_others + RHS_isemtpy = False + if isinstance(RHS, np.ndarray) and RHS.size==0: + RHS_isemtpy = True + elif isinstance(RHS, pd.DataFrame) and RHS.empty: + RHS_isemtpy = True + if isinstance(exog_i, str): + exog_i = dmatrix(exog_i + "-1", data, eval_env=eval_env) + + # all arrays or pandas-like + + if RHS_isemtpy: + endog = np.asarray(endog) + exog_i = np.asarray(exog_i) + ax.plot(endog, exog_i, 'o', **kwargs) + fitted_line = OLS(endog, exog_i).fit() + x_axis_endog_name = 'x' if isinstance(exog_i, np.ndarray) else exog_i.name + y_axis_endog_name = 'y' if isinstance(endog, np.ndarray) else endog.design_info.column_names[0] + else: + res_yaxis = OLS(endog, RHS).fit() + res_xaxis = OLS(exog_i, RHS).fit() + xaxis_resid = res_xaxis.resid + yaxis_resid = res_yaxis.resid + x_axis_endog_name = res_xaxis.model.endog_names + y_axis_endog_name = res_yaxis.model.endog_names + ax.plot(xaxis_resid, yaxis_resid, 'o', **kwargs) + fitted_line = OLS(yaxis_resid, xaxis_resid).fit() + + fig = abline_plot(0, np.asarray(fitted_line.params)[0], color='k', ax=ax) + + if x_axis_endog_name == 'y': # for no names regression will just get a y + x_axis_endog_name = 'x' # this is misleading, so use x + ax.set_xlabel("e(%s | X)" % x_axis_endog_name) + ax.set_ylabel("e(%s | X)" % y_axis_endog_name) + ax.set_title('Partial Regression Plot', **title_kwargs) + + # NOTE: if we want to get super fancy, we could annotate if a point is + # clicked using this widget + # http://stackoverflow.com/questions/4652439/ + # is-there-a-matplotlib-equivalent-of-matlabs-datacursormode/ + # 4674445#4674445 + if obs_labels is True: + if data is not None: + obs_labels = data.index + elif hasattr(exog_i, "index"): + obs_labels = exog_i.index + else: + obs_labels = res_xaxis.model.data.row_labels + #NOTE: row_labels can be None. + #Maybe we should fix this to never be the case. + if obs_labels is None: + obs_labels = lrange(len(exog_i)) + + if obs_labels is not False: # could be array_like + if len(obs_labels) != len(exog_i): + raise ValueError("obs_labels does not match length of exog_i") + label_kwargs.update(dict(ha="center", va="bottom")) + ax = utils.annotate_axes(lrange(len(obs_labels)), obs_labels, + lzip(res_xaxis.resid, res_yaxis.resid), + [(0, 5)] * len(obs_labels), "x-large", ax=ax, + **label_kwargs) + + if ret_coords: + return fig, (res_xaxis.resid, res_yaxis.resid) + else: + return fig + + +def plot_partregress_grid(results, exog_idx=None, grid=None, fig=None): + """ + Plot partial regression for a set of regressors. + + Parameters + ---------- + results : Results instance + A regression model results instance. + exog_idx : {None, list[int], list[str]} + The indices or column names of the exog used in the plot, default is + all. + grid : {None, tuple[int]} + If grid is given, then it is used for the arrangement of the subplots. + The format of grid is (nrows, ncols). If grid is None, then ncol is + one, if there are only 2 subplots, and the number of columns is two + otherwise. + fig : Figure, optional + If given, this figure is simply returned. Otherwise a new figure is + created. + + Returns + ------- + Figure + If `fig` is None, the created figure. Otherwise `fig` itself. + + See Also + -------- + plot_partregress : Plot partial regression for a single regressor. + plot_ccpr : Plot CCPR against one regressor + + Notes + ----- + A subplot is created for each explanatory variable given by exog_idx. + The partial regression plot shows the relationship between the response + and the given explanatory variable after removing the effect of all other + explanatory variables in exog. + + References + ---------- + See http://www.itl.nist.gov/div898/software/dataplot/refman1/auxillar/partregr.htm + + Examples + -------- + Using the state crime dataset separately plot the effect of the each + variable on the on the outcome, murder rate while accounting for the effect + of all other variables in the model visualized with a grid of partial + regression plots. + + >>> from statsmodels.graphics.regressionplots import plot_partregress_grid + >>> import statsmodels.api as sm + >>> import matplotlib.pyplot as plt + >>> import statsmodels.formula.api as smf + + >>> fig = plt.figure(figsize=(8, 6)) + >>> crime_data = sm.datasets.statecrime.load_pandas() + >>> results = smf.ols('murder ~ hs_grad + urban + poverty + single', + ... data=crime_data.data).fit() + >>> plot_partregress_grid(results, fig=fig) + >>> plt.show() + + .. plot:: plots/graphics_regression_partregress_grid.py + """ + import pandas + fig = utils.create_mpl_fig(fig) + + exog_name, exog_idx = utils.maybe_name_or_idx(exog_idx, results.model) + + # TODO: maybe add option for using wendog, wexog instead + y = pandas.Series(results.model.endog, name=results.model.endog_names) + exog = results.model.exog + + k_vars = exog.shape[1] + # this function does not make sense if k_vars=1 + + nrows = (len(exog_idx) + 1) // 2 + ncols = 1 if nrows == len(exog_idx) else 2 + if grid is not None: + nrows, ncols = grid + if ncols > 1: + title_kwargs = {"fontdict": {"fontsize": 'small'}} + + # for indexing purposes + other_names = np.array(results.model.exog_names) + for i, idx in enumerate(exog_idx): + others = lrange(k_vars) + others.pop(idx) + exog_others = pandas.DataFrame(exog[:, others], + columns=other_names[others]) + ax = fig.add_subplot(nrows, ncols, i + 1) + plot_partregress(y, pandas.Series(exog[:, idx], + name=other_names[idx]), + exog_others, ax=ax, title_kwargs=title_kwargs, + obs_labels=False) + ax.set_title("") + + fig.suptitle("Partial Regression Plot", fontsize="large") + fig.tight_layout() + fig.subplots_adjust(top=.95) + + return fig + + +def plot_ccpr(results, exog_idx, ax=None): + """ + Plot CCPR against one regressor. + + Generates a component and component-plus-residual (CCPR) plot. + + Parameters + ---------- + results : result instance + A regression results instance. + exog_idx : {int, str} + Exogenous, explanatory variable. If string is given, it should + be the variable name that you want to use, and you can use arbitrary + translations as with a formula. + ax : AxesSubplot, optional + If given, it is used to plot in instead of a new figure being + created. + + Returns + ------- + Figure + If `ax` is None, the created figure. Otherwise the figure to which + `ax` is connected. + + See Also + -------- + plot_ccpr_grid : Creates CCPR plot for multiple regressors in a plot grid. + + Notes + ----- + The CCPR plot provides a way to judge the effect of one regressor on the + response variable by taking into account the effects of the other + independent variables. The partial residuals plot is defined as + Residuals + B_i*X_i versus X_i. The component adds the B_i*X_i versus + X_i to show where the fitted line would lie. Care should be taken if X_i + is highly correlated with any of the other independent variables. If this + is the case, the variance evident in the plot will be an underestimate of + the true variance. + + References + ---------- + http://www.itl.nist.gov/div898/software/dataplot/refman1/auxillar/ccpr.htm + + Examples + -------- + Using the state crime dataset plot the effect of the rate of single + households ('single') on the murder rate while accounting for high school + graduation rate ('hs_grad'), percentage of people in an urban area, and rate + of poverty ('poverty'). + + >>> import statsmodels.api as sm + >>> import matplotlib.pyplot as plt + >>> import statsmodels.formula.api as smf + + >>> crime_data = sm.datasets.statecrime.load_pandas() + >>> results = smf.ols('murder ~ hs_grad + urban + poverty + single', + ... data=crime_data.data).fit() + >>> sm.graphics.plot_ccpr(results, 'single') + >>> plt.show() + + .. plot:: plots/graphics_regression_ccpr.py + """ + fig, ax = utils.create_mpl_ax(ax) + + exog_name, exog_idx = utils.maybe_name_or_idx(exog_idx, results.model) + results = maybe_unwrap_results(results) + + x1 = results.model.exog[:, exog_idx] + #namestr = ' for %s' % self.name if self.name else '' + x1beta = x1*results.params[exog_idx] + ax.plot(x1, x1beta + results.resid, 'o') + from statsmodels.tools.tools import add_constant + mod = OLS(x1beta, add_constant(x1)).fit() + params = mod.params + fig = abline_plot(*params, **dict(ax=ax)) + #ax.plot(x1, x1beta, '-') + ax.set_title('Component and component plus residual plot') + ax.set_ylabel("Residual + %s*beta_%d" % (exog_name, exog_idx)) + ax.set_xlabel("%s" % exog_name) + + return fig + + +def plot_ccpr_grid(results, exog_idx=None, grid=None, fig=None): + """ + Generate CCPR plots against a set of regressors, plot in a grid. + + Generates a grid of component and component-plus-residual (CCPR) plots. + + Parameters + ---------- + results : result instance + A results instance with exog and params. + exog_idx : None or list of int + The indices or column names of the exog used in the plot. + grid : None or tuple of int (nrows, ncols) + If grid is given, then it is used for the arrangement of the subplots. + If grid is None, then ncol is one, if there are only 2 subplots, and + the number of columns is two otherwise. + fig : Figure, optional + If given, this figure is simply returned. Otherwise a new figure is + created. + + Returns + ------- + Figure + If `ax` is None, the created figure. Otherwise the figure to which + `ax` is connected. + + See Also + -------- + plot_ccpr : Creates CCPR plot for a single regressor. + + Notes + ----- + Partial residual plots are formed as:: + + Res + Betahat(i)*Xi versus Xi + + and CCPR adds:: + + Betahat(i)*Xi versus Xi + + References + ---------- + See http://www.itl.nist.gov/div898/software/dataplot/refman1/auxillar/ccpr.htm + + Examples + -------- + Using the state crime dataset separately plot the effect of the each + variable on the on the outcome, murder rate while accounting for the effect + of all other variables in the model. + + >>> import statsmodels.api as sm + >>> import matplotlib.pyplot as plt + >>> import statsmodels.formula.api as smf + + >>> fig = plt.figure(figsize=(8, 8)) + >>> crime_data = sm.datasets.statecrime.load_pandas() + >>> results = smf.ols('murder ~ hs_grad + urban + poverty + single', + ... data=crime_data.data).fit() + >>> sm.graphics.plot_ccpr_grid(results, fig=fig) + >>> plt.show() + + .. plot:: plots/graphics_regression_ccpr_grid.py + """ + fig = utils.create_mpl_fig(fig) + + exog_name, exog_idx = utils.maybe_name_or_idx(exog_idx, results.model) + + if grid is not None: + nrows, ncols = grid + else: + if len(exog_idx) > 2: + nrows = int(np.ceil(len(exog_idx)/2.)) + ncols = 2 + else: + nrows = len(exog_idx) + ncols = 1 + + seen_constant = 0 + for i, idx in enumerate(exog_idx): + if results.model.exog[:, idx].var() == 0: + seen_constant = 1 + continue + + ax = fig.add_subplot(nrows, ncols, i+1-seen_constant) + fig = plot_ccpr(results, exog_idx=idx, ax=ax) + ax.set_title("") + + fig.suptitle("Component-Component Plus Residual Plot", fontsize="large") + + fig.tight_layout() + + fig.subplots_adjust(top=.95) + return fig + + +def abline_plot(intercept=None, slope=None, horiz=None, vert=None, + model_results=None, ax=None, **kwargs): + """ + Plot a line given an intercept and slope. + + Parameters + ---------- + intercept : float + The intercept of the line. + slope : float + The slope of the line. + horiz : float or array_like + Data for horizontal lines on the y-axis. + vert : array_like + Data for verterical lines on the x-axis. + model_results : statsmodels results instance + Any object that has a two-value `params` attribute. Assumed that it + is (intercept, slope). + ax : axes, optional + Matplotlib axes instance. + **kwargs + Options passed to matplotlib.pyplot.plt. + + Returns + ------- + Figure + The figure given by `ax.figure` or a new instance. + + Examples + -------- + >>> import numpy as np + >>> import statsmodels.api as sm + + >>> np.random.seed(12345) + >>> X = sm.add_constant(np.random.normal(0, 20, size=30)) + >>> y = np.dot(X, [25, 3.5]) + np.random.normal(0, 30, size=30) + >>> mod = sm.OLS(y,X).fit() + >>> fig = sm.graphics.abline_plot(model_results=mod) + >>> ax = fig.axes[0] + >>> ax.scatter(X[:,1], y) + >>> ax.margins(.1) + >>> import matplotlib.pyplot as plt + >>> plt.show() + + .. plot:: plots/graphics_regression_abline.py + """ + if ax is not None: # get axis limits first thing, do not change these + x = ax.get_xlim() + else: + x = None + + fig, ax = utils.create_mpl_ax(ax) + + if model_results: + intercept, slope = model_results.params + if x is None: + x = [model_results.model.exog[:, 1].min(), + model_results.model.exog[:, 1].max()] + else: + if not (intercept is not None and slope is not None): + raise ValueError("specify slope and intercepty or model_results") + if x is None: + x = ax.get_xlim() + + data_y = [x[0]*slope+intercept, x[1]*slope+intercept] + ax.set_xlim(x) + #ax.set_ylim(y) + + from matplotlib.lines import Line2D + + class ABLine2D(Line2D): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.id_xlim_callback = None + self.id_ylim_callback = None + + def remove(self): + ax = self.axes + if self.id_xlim_callback: + ax.callbacks.disconnect(self.id_xlim_callback) + if self.id_ylim_callback: + ax.callbacks.disconnect(self.id_ylim_callback) + super().remove() + + def update_datalim(self, ax): + ax.set_autoscale_on(False) + children = ax.get_children() + ablines = [child for child in children if child is self] + abline = ablines[0] + x = ax.get_xlim() + y = [x[0] * slope + intercept, x[1] * slope + intercept] + abline.set_data(x, y) + ax.figure.canvas.draw() + + # TODO: how to intercept something like a margins call and adjust? + line = ABLine2D(x, data_y, **kwargs) + ax.add_line(line) + line.id_xlim_callback = ax.callbacks.connect('xlim_changed', line.update_datalim) + line.id_ylim_callback = ax.callbacks.connect('ylim_changed', line.update_datalim) + + if horiz: + ax.hline(horiz) + if vert: + ax.vline(vert) + return fig + + +@Appender(_plot_influence_doc.format(**{ + 'extra_params_doc': "results: object\n" + " Results for a fitted regression model.\n" + " influence: instance\n" + " The instance of Influence for model."})) +def _influence_plot(results, influence, external=True, alpha=.05, + criterion="cooks", size=48, plot_alpha=.75, ax=None, + leverage=None, resid=None, + **kwargs): + # leverage and resid kwds are used only internally for MLEInfluence + infl = influence + fig, ax = utils.create_mpl_ax(ax) + + if criterion.lower().startswith('coo'): + psize = infl.cooks_distance[0] + elif criterion.lower().startswith('dff'): + psize = np.abs(infl.dffits[0]) + else: + raise ValueError("Criterion %s not understood" % criterion) + + # scale the variables + #TODO: what is the correct scaling and the assumption here? + #we want plots to be comparable across different plots + #so we would need to use the expected distribution of criterion probably + old_range = np.ptp(psize) + new_range = size**2 - 8**2 + + psize = (psize - psize.min()) * new_range/old_range + 8**2 + + if leverage is None: + leverage = infl.hat_matrix_diag + if resid is None: + ylabel = "Studentized Residuals" + if external: + resid = infl.resid_studentized_external + else: + resid = infl.resid_studentized + else: + resid = np.asarray(resid) + ylabel = "Residuals" + + from scipy import stats + + cutoff = stats.t.ppf(1.-alpha/2, results.df_resid) + large_resid = np.abs(resid) > cutoff + large_leverage = leverage > _high_leverage(results) + large_points = np.logical_or(large_resid, large_leverage) + + ax.scatter(leverage, resid, s=psize, alpha=plot_alpha) + + # add point labels + labels = results.model.data.row_labels + if labels is None: + labels = lrange(len(resid)) + ax = utils.annotate_axes(np.where(large_points)[0], labels, + lzip(leverage, resid), + lzip(-(psize/2)**.5, (psize/2)**.5), "x-large", + ax) + + # TODO: make configurable or let people do it ex-post? + font = {"fontsize": 16, "color": "black"} + ax.set_ylabel(ylabel, **font) + ax.set_xlabel("Leverage", **font) + ax.set_title("Influence Plot", **font) + return fig + + +@Appender(_plot_influence_doc.format(**{ + 'extra_params_doc': "results : Results\n" + " Results for a fitted regression model."})) +def influence_plot(results, external=True, alpha=.05, criterion="cooks", + size=48, plot_alpha=.75, ax=None, **kwargs): + + infl = results.get_influence() + res = _influence_plot(results, infl, external=external, alpha=alpha, + criterion=criterion, size=size, + plot_alpha=plot_alpha, ax=ax, **kwargs) + return res + + +@Appender(_plot_leverage_resid2_doc.format({ + 'extra_params_doc': "results: object\n" + " Results for a fitted regression model\n" + "influence: instance\n" + " instance of Influence for model"})) +def _plot_leverage_resid2(results, influence, alpha=.05, ax=None, + **kwargs): + + from scipy.stats import norm, zscore + fig, ax = utils.create_mpl_ax(ax) + + infl = influence + leverage = infl.hat_matrix_diag + resid = zscore(infl.resid) + ax.plot(resid**2, leverage, 'o', **kwargs) + ax.set_xlabel("Normalized residuals**2") + ax.set_ylabel("Leverage") + ax.set_title("Leverage vs. Normalized residuals squared") + + large_leverage = leverage > _high_leverage(results) + #norm or t here if standardized? + cutoff = norm.ppf(1.-alpha/2) + large_resid = np.abs(resid) > cutoff + labels = results.model.data.row_labels + if labels is None: + labels = lrange(int(results.nobs)) + index = np.where(np.logical_or(large_leverage, large_resid))[0] + ax = utils.annotate_axes(index, labels, lzip(resid**2, leverage), + [(0, 5)]*int(results.nobs), "large", + ax=ax, ha="center", va="bottom") + ax.margins(.075, .075) + return fig + + +@Appender(_plot_leverage_resid2_doc.format({ + 'extra_params_doc': "results : object\n" + " Results for a fitted regression model"})) +def plot_leverage_resid2(results, alpha=.05, ax=None, **kwargs): + + infl = results.get_influence() + return _plot_leverage_resid2(results, infl, alpha=alpha, ax=ax, **kwargs) + + + +@Appender(_plot_added_variable_doc % { + 'extra_params_doc': "results : object\n" + " Results for a fitted regression model"}) +def plot_added_variable(results, focus_exog, resid_type=None, + use_glm_weights=True, fit_kwargs=None, ax=None): + + model = results.model + + fig, ax = utils.create_mpl_ax(ax) + + endog_resid, focus_exog_resid =\ + added_variable_resids(results, focus_exog, + resid_type=resid_type, + use_glm_weights=use_glm_weights, + fit_kwargs=fit_kwargs) + + ax.plot(focus_exog_resid, endog_resid, 'o', alpha=0.6) + + ax.set_title('Added variable plot', fontsize='large') + + if isinstance(focus_exog, str): + xname = focus_exog + else: + xname = model.exog_names[focus_exog] + ax.set_xlabel(xname, size=15) + ax.set_ylabel(model.endog_names + " residuals", size=15) + + return fig + + +@Appender(_plot_partial_residuals_doc % { + 'extra_params_doc': "results : object\n" + " Results for a fitted regression model"}) +def plot_partial_residuals(results, focus_exog, ax=None): + # Docstring attached below + + model = results.model + + focus_exog, focus_col = utils.maybe_name_or_idx(focus_exog, model) + + pr = partial_resids(results, focus_exog) + focus_exog_vals = results.model.exog[:, focus_col] + + fig, ax = utils.create_mpl_ax(ax) + ax.plot(focus_exog_vals, pr, 'o', alpha=0.6) + + ax.set_title('Partial residuals plot', fontsize='large') + + if isinstance(focus_exog, str): + xname = focus_exog + else: + xname = model.exog_names[focus_exog] + ax.set_xlabel(xname, size=15) + ax.set_ylabel("Component plus residual", size=15) + + return fig + + +@Appender(_plot_ceres_residuals_doc % { + 'extra_params_doc': "results : Results\n" + " Results instance of a fitted regression " + "model."}) +def plot_ceres_residuals(results, focus_exog, frac=0.66, cond_means=None, + ax=None): + + model = results.model + + focus_exog, focus_col = utils.maybe_name_or_idx(focus_exog, model) + + presid = ceres_resids(results, focus_exog, frac=frac, + cond_means=cond_means) + + focus_exog_vals = model.exog[:, focus_col] + + fig, ax = utils.create_mpl_ax(ax) + ax.plot(focus_exog_vals, presid, 'o', alpha=0.6) + + ax.set_title('CERES residuals plot', fontsize='large') + + ax.set_xlabel(focus_exog, size=15) + ax.set_ylabel("Component plus residual", size=15) + + return fig + + +def ceres_resids(results, focus_exog, frac=0.66, cond_means=None): + """ + Calculate the CERES residuals (Conditional Expectation Partial + Residuals) for a fitted model. + + Parameters + ---------- + results : model results instance + The fitted model for which the CERES residuals are calculated. + focus_exog : int + The column of results.model.exog used as the 'focus variable'. + frac : float, optional + Lowess smoothing parameter for estimating the conditional + means. Not used if `cond_means` is provided. + cond_means : array_like, optional + If provided, the columns of this array are the conditional + means E[exog | focus exog], where exog ranges over some + or all of the columns of exog other than focus exog. If + this is an empty nx0 array, the conditional means are + treated as being zero. If None, the conditional means are + estimated. + + Returns + ------- + An array containing the CERES residuals. + + Notes + ----- + If `cond_means` is not provided, it is obtained by smoothing each + column of exog (except the focus column) against the focus column. + + Currently only supports GLM, GEE, and OLS models. + """ + + model = results.model + + if not isinstance(model, (GLM, GEE, OLS)): + raise ValueError("ceres residuals not available for %s" % + model.__class__.__name__) + + focus_exog, focus_col = utils.maybe_name_or_idx(focus_exog, model) + + # Indices of non-focus columns + ix_nf = range(len(results.params)) + ix_nf = list(ix_nf) + ix_nf.pop(focus_col) + nnf = len(ix_nf) + + # Estimate the conditional means if not provided. + if cond_means is None: + + # Below we calculate E[x | focus] where x is each column other + # than the focus column. We do not want the intercept when we do + # this so we remove it here. + pexog = model.exog[:, ix_nf] + pexog -= pexog.mean(0) + u, s, vt = np.linalg.svd(pexog, 0) + ii = np.flatnonzero(s > 1e-6) + pexog = u[:, ii] + + fcol = model.exog[:, focus_col] + cond_means = np.empty((len(fcol), pexog.shape[1])) + for j in range(pexog.shape[1]): + + # Get the fitted values for column i given the other + # columns (skip the intercept). + y0 = pexog[:, j] + + cf = lowess(y0, fcol, frac=frac, return_sorted=False) + + cond_means[:, j] = cf + + new_exog = np.concatenate((model.exog[:, ix_nf], cond_means), axis=1) + + # Refit the model using the adjusted exog values + klass = model.__class__ + init_kwargs = model._get_init_kwds() + new_model = klass(model.endog, new_exog, **init_kwargs) + new_result = new_model.fit() + + # The partial residual, with respect to l(x2) (notation of Cook 1998) + presid = model.endog - new_result.fittedvalues + if isinstance(model, (GLM, GEE)): + presid *= model.family.link.deriv(new_result.fittedvalues) + if new_exog.shape[1] > nnf: + presid += np.dot(new_exog[:, nnf:], new_result.params[nnf:]) + + return presid + +def partial_resids(results, focus_exog): + """ + Returns partial residuals for a fitted model with respect to a + 'focus predictor'. + + Parameters + ---------- + results : results instance + A fitted regression model. + focus col : int + The column index of model.exog with respect to which the + partial residuals are calculated. + + Returns + ------- + An array of partial residuals. + + References + ---------- + RD Cook and R Croos-Dabrera (1998). Partial residual plots in + generalized linear models. Journal of the American Statistical + Association, 93:442. + """ + + # TODO: could be a method of results + # TODO: see Cook et al (1998) for a more general definition + + # The calculation follows equation (8) from Cook's paper. + model = results.model + resid = model.endog - results.predict() + + if isinstance(model, (GLM, GEE)): + resid *= model.family.link.deriv(results.fittedvalues) + elif isinstance(model, (OLS, GLS, WLS)): + pass # No need to do anything + else: + raise ValueError("Partial residuals for '%s' not implemented." + % type(model)) + + if type(focus_exog) is str: + focus_col = model.exog_names.index(focus_exog) + else: + focus_col = focus_exog + + focus_val = results.params[focus_col] * model.exog[:, focus_col] + + return focus_val + resid + +def added_variable_resids(results, focus_exog, resid_type=None, + use_glm_weights=True, fit_kwargs=None): + """ + Residualize the endog variable and a 'focus' exog variable in a + regression model with respect to the other exog variables. + + Parameters + ---------- + results : regression results instance + A fitted model including the focus exog and all other + predictors of interest. + focus_exog : {int, str} + The column of results.model.exog or a variable name that is + to be residualized against the other predictors. + resid_type : str + The type of residuals to use for the dependent variable. If + None, uses `resid_deviance` for GLM/GEE and `resid` otherwise. + use_glm_weights : bool + Only used if the model is a GLM or GEE. If True, the + residuals for the focus predictor are computed using WLS, with + the weights obtained from the IRLS calculations for fitting + the GLM. If False, unweighted regression is used. + fit_kwargs : dict, optional + Keyword arguments to be passed to fit when refitting the + model. + + Returns + ------- + endog_resid : array_like + The residuals for the original exog + focus_exog_resid : array_like + The residuals for the focus predictor + + Notes + ----- + The 'focus variable' residuals are always obtained using linear + regression. + + Currently only GLM, GEE, and OLS models are supported. + """ + + model = results.model + if not isinstance(model, (GEE, GLM, OLS)): + raise ValueError("model type %s not supported for added variable residuals" % + model.__class__.__name__) + + exog = model.exog + endog = model.endog + + focus_exog, focus_col = utils.maybe_name_or_idx(focus_exog, model) + + focus_exog_vals = exog[:, focus_col] + + # Default residuals + if resid_type is None: + if isinstance(model, (GEE, GLM)): + resid_type = "resid_deviance" + else: + resid_type = "resid" + + ii = range(exog.shape[1]) + ii = list(ii) + ii.pop(focus_col) + reduced_exog = exog[:, ii] + start_params = results.params[ii] + + klass = model.__class__ + + kwargs = model._get_init_kwds() + new_model = klass(endog, reduced_exog, **kwargs) + args = {"start_params": start_params} + if fit_kwargs is not None: + args.update(fit_kwargs) + new_result = new_model.fit(**args) + if not getattr(new_result, "converged", True): + raise ValueError("fit did not converge when calculating added variable residuals") + + try: + endog_resid = getattr(new_result, resid_type) + except AttributeError: + raise ValueError("'%s' residual type not available" % resid_type) + + import statsmodels.regression.linear_model as lm + + if isinstance(model, (GLM, GEE)) and use_glm_weights: + weights = model.family.weights(results.fittedvalues) + if hasattr(model, "data_weights"): + weights = weights * model.data_weights + lm_results = lm.WLS(focus_exog_vals, reduced_exog, weights).fit() + else: + lm_results = lm.OLS(focus_exog_vals, reduced_exog).fit() + focus_exog_resid = lm_results.resid + + return endog_resid, focus_exog_resid diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/tsaplots.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/tsaplots.py new file mode 100644 index 0000000000000000000000000000000000000000..f3a8012fafbda961534172b8a38956ee4c955246 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/tsaplots.py @@ -0,0 +1,873 @@ +"""Correlation plot functions.""" +from statsmodels.compat.pandas import deprecate_kwarg + +import calendar + +import numpy as np +import pandas as pd + +from statsmodels.graphics import utils +from statsmodels.tools.validation import array_like +from statsmodels.tsa.stattools import acf, pacf, ccf + + +def _prepare_data_corr_plot(x, lags, zero): + zero = bool(zero) + irregular = False if zero else True + if lags is None: + # GH 4663 - use a sensible default value + nobs = x.shape[0] + lim = min(int(np.ceil(10 * np.log10(nobs))), nobs // 2) + lags = np.arange(not zero, lim + 1) + elif np.isscalar(lags): + lags = np.arange(not zero, int(lags) + 1) # +1 for zero lag + else: + irregular = True + lags = np.asanyarray(lags).astype(int) + nlags = lags.max(0) + + return lags, nlags, irregular + + +def _plot_corr( + ax, + title, + acf_x, + confint, + lags, + irregular, + use_vlines, + vlines_kwargs, + auto_ylims=False, + skip_lag0_confint=True, + **kwargs, +): + if irregular: + acf_x = acf_x[lags] + if confint is not None: + confint = confint[lags] + + if use_vlines: + ax.vlines(lags, [0], acf_x, **vlines_kwargs) + ax.axhline(**kwargs) + + kwargs.setdefault("marker", "o") + kwargs.setdefault("markersize", 5) + if "ls" not in kwargs: + # gh-2369 + kwargs.setdefault("linestyle", "None") + ax.margins(0.05) + ax.plot(lags, acf_x, **kwargs) + ax.set_title(title) + + ax.set_ylim(-1, 1) + if auto_ylims: + ax.set_ylim( + 1.25 * np.minimum(min(acf_x), min(confint[:, 0] - acf_x)), + 1.25 * np.maximum(max(acf_x), max(confint[:, 1] - acf_x)), + ) + + if confint is not None: + if skip_lag0_confint and lags[0] == 0: + lags = lags[1:] + confint = confint[1:] + acf_x = acf_x[1:] + lags = lags.astype(float) + lags[np.argmin(lags)] -= 0.5 + lags[np.argmax(lags)] += 0.5 + ax.fill_between( + lags, confint[:, 0] - acf_x, confint[:, 1] - acf_x, alpha=0.25 + ) + + +@deprecate_kwarg("unbiased", "adjusted") +def plot_acf( + x, + ax=None, + lags=None, + *, + alpha=0.05, + use_vlines=True, + adjusted=False, + fft=False, + missing="none", + title="Autocorrelation", + zero=True, + auto_ylims=False, + bartlett_confint=True, + vlines_kwargs=None, + **kwargs, +): + """ + Plot the autocorrelation function + + Plots lags on the horizontal and the correlations on vertical axis. + + Parameters + ---------- + x : array_like + Array of time-series values + ax : AxesSubplot, optional + If given, this subplot is used to plot in instead of a new figure being + created. + lags : {int, array_like}, optional + An int or array of lag values, used on horizontal axis. Uses + np.arange(lags) when lags is an int. If not provided, + ``lags=np.arange(len(corr))`` is used. + alpha : scalar, optional + If a number is given, the confidence intervals for the given level are + returned. For instance if alpha=.05, 95 % confidence intervals are + returned where the standard deviation is computed according to + Bartlett's formula. If None, no confidence intervals are plotted. + use_vlines : bool, optional + If True, vertical lines and markers are plotted. + If False, only markers are plotted. The default marker is 'o'; it can + be overridden with a ``marker`` kwarg. + adjusted : bool + If True, then denominators for autocovariance are n-k, otherwise n + fft : bool, optional + If True, computes the ACF via FFT. + missing : str, optional + A string in ['none', 'raise', 'conservative', 'drop'] specifying how + the NaNs are to be treated. + title : str, optional + Title to place on plot. Default is 'Autocorrelation' + zero : bool, optional + Flag indicating whether to include the 0-lag autocorrelation. + Default is True. + auto_ylims : bool, optional + If True, adjusts automatically the y-axis limits to ACF values. + bartlett_confint : bool, default True + Confidence intervals for ACF values are generally placed at 2 + standard errors around r_k. The formula used for standard error + depends upon the situation. If the autocorrelations are being used + to test for randomness of residuals as part of the ARIMA routine, + the standard errors are determined assuming the residuals are white + noise. The approximate formula for any lag is that standard error + of each r_k = 1/sqrt(N). See section 9.4 of [1] for more details on + the 1/sqrt(N) result. For more elementary discussion, see section + 5.3.2 in [2]. + For the ACF of raw data, the standard error at a lag k is + found as if the right model was an MA(k-1). This allows the + possible interpretation that if all autocorrelations past a + certain lag are within the limits, the model might be an MA of + order defined by the last significant autocorrelation. In this + case, a moving average model is assumed for the data and the + standard errors for the confidence intervals should be + generated using Bartlett's formula. For more details on + Bartlett formula result, see section 7.2 in [1]. + vlines_kwargs : dict, optional + Optional dictionary of keyword arguments that are passed to vlines. + **kwargs : kwargs, optional + Optional keyword arguments that are directly passed on to the + Matplotlib ``plot`` and ``axhline`` functions. + + Returns + ------- + Figure + If `ax` is None, the created figure. Otherwise the figure to which + `ax` is connected. + + See Also + -------- + matplotlib.pyplot.xcorr + matplotlib.pyplot.acorr + + Notes + ----- + Adapted from matplotlib's `xcorr`. + + Data are plotted as ``plot(lags, corr, **kwargs)`` + + kwargs is used to pass matplotlib optional arguments to both the line + tracing the autocorrelations and for the horizontal line at 0. These + options must be valid for a Line2D object. + + vlines_kwargs is used to pass additional optional arguments to the + vertical lines connecting each autocorrelation to the axis. These options + must be valid for a LineCollection object. + + References + ---------- + [1] Brockwell and Davis, 1987. Time Series Theory and Methods + [2] Brockwell and Davis, 2010. Introduction to Time Series and + Forecasting, 2nd edition. + + Examples + -------- + >>> import pandas as pd + >>> import matplotlib.pyplot as plt + >>> import statsmodels.api as sm + + >>> dta = sm.datasets.sunspots.load_pandas().data + >>> dta.index = pd.Index(sm.tsa.datetools.dates_from_range('1700', '2008')) + >>> del dta["YEAR"] + >>> sm.graphics.tsa.plot_acf(dta.values.squeeze(), lags=40) + >>> plt.show() + + .. plot:: plots/graphics_tsa_plot_acf.py + """ + fig, ax = utils.create_mpl_ax(ax) + + lags, nlags, irregular = _prepare_data_corr_plot(x, lags, zero) + vlines_kwargs = {} if vlines_kwargs is None else vlines_kwargs + + confint = None + # acf has different return type based on alpha + acf_x = acf( + x, + nlags=nlags, + alpha=alpha, + fft=fft, + bartlett_confint=bartlett_confint, + adjusted=adjusted, + missing=missing, + ) + if alpha is not None: + acf_x, confint = acf_x[:2] + + _plot_corr( + ax, + title, + acf_x, + confint, + lags, + irregular, + use_vlines, + vlines_kwargs, + auto_ylims=auto_ylims, + **kwargs, + ) + + return fig + + +def plot_pacf( + x, + ax=None, + lags=None, + alpha=0.05, + method="ywm", + use_vlines=True, + title="Partial Autocorrelation", + zero=True, + vlines_kwargs=None, + **kwargs, +): + """ + Plot the partial autocorrelation function + + Parameters + ---------- + x : array_like + Array of time-series values + ax : AxesSubplot, optional + If given, this subplot is used to plot in instead of a new figure being + created. + lags : {int, array_like}, optional + An int or array of lag values, used on horizontal axis. Uses + np.arange(lags) when lags is an int. If not provided, + ``lags=np.arange(len(corr))`` is used. + alpha : float, optional + If a number is given, the confidence intervals for the given level are + returned. For instance if alpha=.05, 95 % confidence intervals are + returned where the standard deviation is computed according to + 1/sqrt(len(x)) + method : str + Specifies which method for the calculations to use: + + - "ywm" or "ywmle" : Yule-Walker without adjustment. Default. + - "yw" or "ywadjusted" : Yule-Walker with sample-size adjustment in + denominator for acovf. Default. + - "ols" : regression of time series on lags of it and on constant. + - "ols-inefficient" : regression of time series on lags using a single + common sample to estimate all pacf coefficients. + - "ols-adjusted" : regression of time series on lags with a bias + adjustment. + - "ld" or "ldadjusted" : Levinson-Durbin recursion with bias + correction. + - "ldb" or "ldbiased" : Levinson-Durbin recursion without bias + correction. + + use_vlines : bool, optional + If True, vertical lines and markers are plotted. + If False, only markers are plotted. The default marker is 'o'; it can + be overridden with a ``marker`` kwarg. + title : str, optional + Title to place on plot. Default is 'Partial Autocorrelation' + zero : bool, optional + Flag indicating whether to include the 0-lag autocorrelation. + Default is True. + vlines_kwargs : dict, optional + Optional dictionary of keyword arguments that are passed to vlines. + **kwargs : kwargs, optional + Optional keyword arguments that are directly passed on to the + Matplotlib ``plot`` and ``axhline`` functions. + + Returns + ------- + Figure + If `ax` is None, the created figure. Otherwise the figure to which + `ax` is connected. + + See Also + -------- + matplotlib.pyplot.xcorr + matplotlib.pyplot.acorr + + Notes + ----- + Plots lags on the horizontal and the correlations on vertical axis. + Adapted from matplotlib's `xcorr`. + + Data are plotted as ``plot(lags, corr, **kwargs)`` + + kwargs is used to pass matplotlib optional arguments to both the line + tracing the autocorrelations and for the horizontal line at 0. These + options must be valid for a Line2D object. + + vlines_kwargs is used to pass additional optional arguments to the + vertical lines connecting each autocorrelation to the axis. These options + must be valid for a LineCollection object. + + Examples + -------- + >>> import pandas as pd + >>> import matplotlib.pyplot as plt + >>> import statsmodels.api as sm + + >>> dta = sm.datasets.sunspots.load_pandas().data + >>> dta.index = pd.Index(sm.tsa.datetools.dates_from_range('1700', '2008')) + >>> del dta["YEAR"] + >>> sm.graphics.tsa.plot_pacf(dta.values.squeeze(), lags=40, method="ywm") + >>> plt.show() + + .. plot:: plots/graphics_tsa_plot_pacf.py + """ + fig, ax = utils.create_mpl_ax(ax) + vlines_kwargs = {} if vlines_kwargs is None else vlines_kwargs + lags, nlags, irregular = _prepare_data_corr_plot(x, lags, zero) + + confint = None + if alpha is None: + acf_x = pacf(x, nlags=nlags, alpha=alpha, method=method) + else: + acf_x, confint = pacf(x, nlags=nlags, alpha=alpha, method=method) + + _plot_corr( + ax, + title, + acf_x, + confint, + lags, + irregular, + use_vlines, + vlines_kwargs, + **kwargs, + ) + + return fig + + +def plot_ccf( + x, + y, + *, + ax=None, + lags=None, + negative_lags=False, + alpha=0.05, + use_vlines=True, + adjusted=False, + fft=False, + title="Cross-correlation", + auto_ylims=False, + vlines_kwargs=None, + **kwargs, +): + """ + Plot the cross-correlation function + + Correlations between ``x`` and the lags of ``y`` are calculated. + + The lags are shown on the horizontal axis and the correlations + on the vertical axis. + + Parameters + ---------- + x, y : array_like + Arrays of time-series values. + ax : AxesSubplot, optional + If given, this subplot is used to plot in, otherwise a new figure with + one subplot is created. + lags : {int, array_like}, optional + An int or array of lag values, used on the horizontal axis. Uses + ``np.arange(lags)`` when lags is an int. If not provided, + ``lags=np.arange(len(corr))`` is used. + negative_lags: bool, optional + If True, negative lags are shown on the horizontal axis. + alpha : scalar, optional + If a number is given, the confidence intervals for the given level are + plotted, e.g. if alpha=.05, 95 % confidence intervals are shown. + If None, confidence intervals are not shown on the plot. + use_vlines : bool, optional + If True, shows vertical lines and markers for the correlation values. + If False, only shows markers. The default marker is 'o'; it can + be overridden with a ``marker`` kwarg. + adjusted : bool + If True, then denominators for cross-correlations are n-k, otherwise n. + fft : bool, optional + If True, computes the CCF via FFT. + title : str, optional + Title to place on plot. Default is 'Cross-correlation'. + auto_ylims : bool, optional + If True, adjusts automatically the vertical axis limits to CCF values. + vlines_kwargs : dict, optional + Optional dictionary of keyword arguments that are passed to vlines. + **kwargs : kwargs, optional + Optional keyword arguments that are directly passed on to the + Matplotlib ``plot`` and ``axhline`` functions. + + Returns + ------- + Figure + The figure where the plot is drawn. This is either an existing figure + if the `ax` argument is provided, or a newly created figure + if `ax` is None. + + See Also + -------- + statsmodels.graphics.tsaplots.plot_acf + + Examples + -------- + >>> import pandas as pd + >>> import matplotlib.pyplot as plt + >>> import statsmodels.api as sm + + >>> dta = sm.datasets.macrodata.load_pandas().data + >>> diffed = dta.diff().dropna() + >>> sm.graphics.tsa.plot_ccf(diffed["unemp"], diffed["infl"]) + >>> plt.show() + """ + fig, ax = utils.create_mpl_ax(ax) + + lags, nlags, irregular = _prepare_data_corr_plot(x, lags, True) + vlines_kwargs = {} if vlines_kwargs is None else vlines_kwargs + + if negative_lags: + lags = -lags + + ccf_res = ccf( + x, y, adjusted=adjusted, fft=fft, alpha=alpha, nlags=nlags + 1 + ) + if alpha is not None: + ccf_xy, confint = ccf_res + else: + ccf_xy = ccf_res + confint = None + + _plot_corr( + ax, + title, + ccf_xy, + confint, + lags, + irregular, + use_vlines, + vlines_kwargs, + auto_ylims=auto_ylims, + skip_lag0_confint=False, + **kwargs, + ) + + return fig + + +def plot_accf_grid( + x, + *, + varnames=None, + fig=None, + lags=None, + negative_lags=True, + alpha=0.05, + use_vlines=True, + adjusted=False, + fft=False, + missing="none", + zero=True, + auto_ylims=False, + bartlett_confint=False, + vlines_kwargs=None, + **kwargs, +): + """ + Plot auto/cross-correlation grid + + Plots lags on the horizontal axis and the correlations + on the vertical axis of each graph. + + Parameters + ---------- + x : array_like + 2D array of time-series values: rows are observations, + columns are variables. + varnames: sequence of str, optional + Variable names to use in plot titles. If ``x`` is a pandas dataframe + and ``varnames`` is provided, it overrides the column names + of the dataframe. If ``varnames`` is not provided and ``x`` is not + a dataframe, variable names ``x[0]``, ``x[1]``, etc. are generated. + fig : Matplotlib figure instance, optional + If given, this figure is used to plot in, otherwise a new figure + is created. + lags : {int, array_like}, optional + An int or array of lag values, used on horizontal axes. Uses + ``np.arange(lags)`` when lags is an int. If not provided, + ``lags=np.arange(len(corr))`` is used. + negative_lags: bool, optional + If True, negative lags are shown on the horizontal axes of plots + below the main diagonal. + alpha : scalar, optional + If a number is given, the confidence intervals for the given level are + plotted, e.g. if alpha=.05, 95 % confidence intervals are shown. + If None, confidence intervals are not shown on the plot. + use_vlines : bool, optional + If True, shows vertical lines and markers for the correlation values. + If False, only shows markers. The default marker is 'o'; it can + be overridden with a ``marker`` kwarg. + adjusted : bool + If True, then denominators for correlations are n-k, otherwise n. + fft : bool, optional + If True, computes the ACF via FFT. + missing : str, optional + A string in ['none', 'raise', 'conservative', 'drop'] specifying how + NaNs are to be treated. + zero : bool, optional + Flag indicating whether to include the 0-lag autocorrelations + (which are always equal to 1). Default is True. + auto_ylims : bool, optional + If True, adjusts automatically the vertical axis limits + to correlation values. + bartlett_confint : bool, default False + If True, use Bartlett's formula to calculate confidence intervals + in auto-correlation plots. See the description of ``plot_acf`` for + details. This argument does not affect cross-correlation plots. + vlines_kwargs : dict, optional + Optional dictionary of keyword arguments that are passed to vlines. + **kwargs : kwargs, optional + Optional keyword arguments that are directly passed on to the + Matplotlib ``plot`` and ``axhline`` functions. + + Returns + ------- + Figure + If `fig` is None, the created figure. Otherwise, `fig` is returned. + Plots on the grid show the cross-correlation of the row variable + with the lags of the column variable. + + See Also + -------- + statsmodels.graphics.tsaplots + + Examples + -------- + >>> import pandas as pd + >>> import matplotlib.pyplot as plt + >>> import statsmodels.api as sm + + >>> dta = sm.datasets.macrodata.load_pandas().data + >>> diffed = dta.diff().dropna() + >>> sm.graphics.tsa.plot_accf_grid(diffed[["unemp", "infl"]]) + >>> plt.show() + """ + from statsmodels.tools.data import _is_using_pandas + + array_like(x, "x", ndim=2) + m = x.shape[1] + + fig = utils.create_mpl_fig(fig) + gs = fig.add_gridspec(m, m) + + if _is_using_pandas(x, None): + varnames = varnames or list(x.columns) + + def get_var(i): + return x.iloc[:, i] + else: + varnames = varnames or [f'x[{i}]' for i in range(m)] + + x = np.asarray(x) + + def get_var(i): + return x[:, i] + + for i in range(m): + for j in range(m): + ax = fig.add_subplot(gs[i, j]) + if i == j: + plot_acf( + get_var(i), + ax=ax, + title=f'ACF({varnames[i]})', + lags=lags, + alpha=alpha, + use_vlines=use_vlines, + adjusted=adjusted, + fft=fft, + missing=missing, + zero=zero, + auto_ylims=auto_ylims, + bartlett_confint=bartlett_confint, + vlines_kwargs=vlines_kwargs, + **kwargs, + ) + else: + plot_ccf( + get_var(i), + get_var(j), + ax=ax, + title=f'CCF({varnames[i]}, {varnames[j]})', + lags=lags, + negative_lags=negative_lags and i > j, + alpha=alpha, + use_vlines=use_vlines, + adjusted=adjusted, + fft=fft, + auto_ylims=auto_ylims, + vlines_kwargs=vlines_kwargs, + **kwargs, + ) + + return fig + + +def seasonal_plot(grouped_x, xticklabels, ylabel=None, ax=None): + """ + Consider using one of month_plot or quarter_plot unless you need + irregular plotting. + + Parameters + ---------- + grouped_x : iterable of DataFrames + Should be a GroupBy object (or similar pair of group_names and groups + as DataFrames) with a DatetimeIndex or PeriodIndex + xticklabels : list of str + List of season labels, one for each group. + ylabel : str + Lable for y axis + ax : AxesSubplot, optional + If given, this subplot is used to plot in instead of a new figure being + created. + """ + fig, ax = utils.create_mpl_ax(ax) + start = 0 + ticks = [] + for season, df in grouped_x: + df = df.copy() # or sort balks for series. may be better way + df.sort_index() + nobs = len(df) + x_plot = np.arange(start, start + nobs) + ticks.append(x_plot.mean()) + ax.plot(x_plot, df.values, "k") + ax.hlines( + df.values.mean(), x_plot[0], x_plot[-1], colors="r", linewidth=3 + ) + start += nobs + + ax.set_xticks(ticks) + ax.set_xticklabels(xticklabels) + ax.set_ylabel(ylabel) + ax.margins(0.1, 0.05) + return fig + + +def month_plot(x, dates=None, ylabel=None, ax=None): + """ + Seasonal plot of monthly data. + + Parameters + ---------- + x : array_like + Seasonal data to plot. If dates is None, x must be a pandas object + with a PeriodIndex or DatetimeIndex with a monthly frequency. + dates : array_like, optional + If `x` is not a pandas object, then dates must be supplied. + ylabel : str, optional + The label for the y-axis. Will attempt to use the `name` attribute + of the Series. + ax : Axes, optional + Existing axes instance. + + Returns + ------- + Figure + If `ax` is provided, the Figure instance attached to `ax`. Otherwise + a new Figure instance. + + Examples + -------- + >>> import statsmodels.api as sm + >>> import pandas as pd + + >>> dta = sm.datasets.elnino.load_pandas().data + >>> dta['YEAR'] = dta.YEAR.astype(int).astype(str) + >>> dta = dta.set_index('YEAR').T.unstack() + >>> dates = pd.to_datetime(list(map(lambda x: '-'.join(x) + '-1', + ... dta.index.values))) + >>> dta.index = pd.DatetimeIndex(dates, freq='MS') + >>> fig = sm.graphics.tsa.month_plot(dta) + + .. plot:: plots/graphics_tsa_month_plot.py + """ + + if dates is None: + from statsmodels.tools.data import _check_period_index + + _check_period_index(x, freq="M") + else: + x = pd.Series(x, index=pd.PeriodIndex(dates, freq="M")) + + # there's no zero month + xticklabels = list(calendar.month_abbr)[1:] + return seasonal_plot( + x.groupby(lambda y: y.month), xticklabels, ylabel=ylabel, ax=ax + ) + + +def quarter_plot(x, dates=None, ylabel=None, ax=None): + """ + Seasonal plot of quarterly data + + Parameters + ---------- + x : array_like + Seasonal data to plot. If dates is None, x must be a pandas object + with a PeriodIndex or DatetimeIndex with a monthly frequency. + dates : array_like, optional + If `x` is not a pandas object, then dates must be supplied. + ylabel : str, optional + The label for the y-axis. Will attempt to use the `name` attribute + of the Series. + ax : matplotlib.axes, optional + Existing axes instance. + + Returns + ------- + Figure + If `ax` is provided, the Figure instance attached to `ax`. Otherwise + a new Figure instance. + + Examples + -------- + >>> import statsmodels.api as sm + >>> import pandas as pd + + >>> dta = sm.datasets.elnino.load_pandas().data + >>> dta['YEAR'] = dta.YEAR.astype(int).astype(str) + >>> dta = dta.set_index('YEAR').T.unstack() + >>> dates = pd.to_datetime(list(map(lambda x: '-'.join(x) + '-1', + ... dta.index.values))) + >>> dta.index = dates.to_period('Q') + >>> fig = sm.graphics.tsa.quarter_plot(dta) + + .. plot:: plots/graphics_tsa_quarter_plot.py + """ + + if dates is None: + from statsmodels.tools.data import _check_period_index + + _check_period_index(x, freq="Q") + else: + x = pd.Series(x, index=pd.PeriodIndex(dates, freq="Q")) + + xticklabels = ["q1", "q2", "q3", "q4"] + return seasonal_plot( + x.groupby(lambda y: y.quarter), xticklabels, ylabel=ylabel, ax=ax + ) + + +def plot_predict( + result, + start=None, + end=None, + dynamic=False, + alpha=0.05, + ax=None, + **predict_kwargs, +): + """ + + Parameters + ---------- + result : Result + Any model result supporting ``get_prediction``. + start : int, str, or datetime, optional + Zero-indexed observation number at which to start forecasting, + i.e., the first forecast is start. Can also be a date string to + parse or a datetime type. Default is the the zeroth observation. + end : int, str, or datetime, optional + Zero-indexed observation number at which to end forecasting, i.e., + the last forecast is end. Can also be a date string to + parse or a datetime type. However, if the dates index does not + have a fixed frequency, end must be an integer index if you + want out of sample prediction. Default is the last observation in + the sample. + dynamic : bool, int, str, or datetime, optional + Integer offset relative to `start` at which to begin dynamic + prediction. Can also be an absolute date string to parse or a + datetime type (these are not interpreted as offsets). + Prior to this observation, true endogenous values will be used for + prediction; starting with this observation and continuing through + the end of prediction, forecasted endogenous values will be used + instead. + alpha : {float, None} + The tail probability not covered by the confidence interval. Must + be in (0, 1). Confidence interval is constructed assuming normally + distributed shocks. If None, figure will not show the confidence + interval. + ax : AxesSubplot + matplotlib Axes instance to use + **predict_kwargs + Any additional keyword arguments to pass to ``result.get_prediction``. + + Returns + ------- + Figure + matplotlib Figure containing the prediction plot + """ + from statsmodels.graphics.utils import _import_mpl, create_mpl_ax + + _ = _import_mpl() + fig, ax = create_mpl_ax(ax) + from statsmodels.tsa.base.prediction import PredictionResults + + # use predict so you set dates + pred: PredictionResults = result.get_prediction( + start=start, end=end, dynamic=dynamic, **predict_kwargs + ) + mean = pred.predicted_mean + if isinstance(mean, (pd.Series, pd.DataFrame)): + x = mean.index + mean.plot(ax=ax, label="forecast") + else: + x = np.arange(mean.shape[0]) + ax.plot(x, mean, label="forecast") + + if alpha is not None: + label = f"{1-alpha:.0%} confidence interval" + ci = pred.conf_int(alpha) + conf_int = np.asarray(ci) + + ax.fill_between( + x, + conf_int[:, 0], + conf_int[:, 1], + color="gray", + alpha=0.5, + label=label, + ) + + ax.legend(loc="best") + + return fig diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/tukeyplot.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/tukeyplot.py new file mode 100644 index 0000000000000000000000000000000000000000..55a3c69af455cbd06905a997e84dd5da987b0b9a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/tukeyplot.py @@ -0,0 +1,75 @@ +import matplotlib.lines as lines +import matplotlib.pyplot as plt +import numpy as np + + +def tukeyplot(results, dim=None, yticklabels=None): + npairs = len(results) + + fig = plt.figure() + fsp = fig.add_subplot(111) + fsp.axis([-50,50,0.5,10.5]) + fsp.set_title('95 % family-wise confidence level') + fsp.title.set_y(1.025) + fsp.set_yticks(np.arange(1,11)) + fsp.set_yticklabels(['V-T','V-S','T-S','V-P','T-P','S-P','V-M', + 'T-M','S-M','P-M']) + #fsp.yaxis.set_major_locator(mticker.MaxNLocator(npairs)) + fsp.yaxis.grid(True, linestyle='-', color='gray') + fsp.set_xlabel('Differences in mean levels of Var', labelpad=8) + fsp.xaxis.tick_bottom() + fsp.yaxis.tick_left() + + xticklines = fsp.get_xticklines() + for xtickline in xticklines: + xtickline.set_marker(lines.TICKDOWN) + xtickline.set_markersize(10) + + xlabels = fsp.get_xticklabels() + for xlabel in xlabels: + xlabel.set_y(-.04) + + yticklines = fsp.get_yticklines() + for ytickline in yticklines: + ytickline.set_marker(lines.TICKLEFT) + ytickline.set_markersize(10) + + ylabels = fsp.get_yticklabels() + for ylabel in ylabels: + ylabel.set_x(-.04) + + for pair in range(npairs): + data = .5+results[pair]/100. + #fsp.axhline(y=npairs-pair, xmin=data[0], xmax=data[1], linewidth=1.25, + fsp.axhline(y=npairs-pair, xmin=data.mean(), xmax=data[1], linewidth=1.25, + color='blue', marker="|", markevery=1) + + fsp.axhline(y=npairs-pair, xmin=data[0], xmax=data.mean(), linewidth=1.25, + color='blue', marker="|", markevery=1) + + #for pair in range(npairs): + # data = .5+results[pair]/100. + # data = results[pair] + # data = np.r_[data[0],data.mean(),data[1]] + # l = plt.plot(data, [npairs-pair]*len(data), color='black', + # linewidth=.5, marker="|", markevery=1) + + fsp.axvline(x=0, linestyle="--", color='black') + + fig.subplots_adjust(bottom=.125) + + + +results = np.array([[-10.04391794, 26.34391794], + [-21.45225794, 14.93557794], + [ 5.61441206, 42.00224794], + [-13.40225794, 22.98557794], + [-29.60225794, 6.78557794], + [ -2.53558794, 33.85224794], + [-21.55225794, 14.83557794], + [ 8.87275206, 45.26058794], + [-10.14391794, 26.24391794], + [-37.21058794, -0.82275206]]) + + +#plt.show() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/utils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a8bbe99e18ab9be17867687c6cd32ab3cc875f76 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/graphics/utils.py @@ -0,0 +1,147 @@ +"""Helper functions for graphics with Matplotlib.""" +from statsmodels.compat.python import lrange + +__all__ = ['create_mpl_ax', 'create_mpl_fig'] + + +def _import_mpl(): + """This function is not needed outside this utils module.""" + try: + import matplotlib.pyplot as plt + except: + raise ImportError("Matplotlib is not found.") + + return plt + + +def create_mpl_ax(ax=None): + """Helper function for when a single plot axis is needed. + + Parameters + ---------- + ax : AxesSubplot, optional + If given, this subplot is used to plot in instead of a new figure being + created. + + Returns + ------- + fig : Figure + If `ax` is None, the created figure. Otherwise the figure to which + `ax` is connected. + ax : AxesSubplot + The created axis if `ax` is None, otherwise the axis that was passed + in. + + Notes + ----- + This function imports `matplotlib.pyplot`, which should only be done to + create (a) figure(s) with ``plt.figure``. All other functionality exposed + by the pyplot module can and should be imported directly from its + Matplotlib module. + + See Also + -------- + create_mpl_fig + + Examples + -------- + A plotting function has a keyword ``ax=None``. Then calls: + + >>> from statsmodels.graphics import utils + >>> fig, ax = utils.create_mpl_ax(ax) + """ + if ax is None: + plt = _import_mpl() + fig = plt.figure() + ax = fig.add_subplot(111) + else: + fig = ax.figure + + return fig, ax + + +def create_mpl_fig(fig=None, figsize=None): + """Helper function for when multiple plot axes are needed. + + Those axes should be created in the functions they are used in, with + ``fig.add_subplot()``. + + Parameters + ---------- + fig : Figure, optional + If given, this figure is simply returned. Otherwise a new figure is + created. + + Returns + ------- + Figure + If `fig` is None, the created figure. Otherwise the input `fig` is + returned. + + See Also + -------- + create_mpl_ax + """ + if fig is None: + plt = _import_mpl() + fig = plt.figure(figsize=figsize) + + return fig + + +def maybe_name_or_idx(idx, model): + """ + Give a name or an integer and return the name and integer location of the + column in a design matrix. + """ + if idx is None: + idx = lrange(model.exog.shape[1]) + if isinstance(idx, int): + exog_name = model.exog_names[idx] + exog_idx = idx + # anticipate index as list and recurse + elif isinstance(idx, (tuple, list)): + exog_name = [] + exog_idx = [] + for item in idx: + exog_name_item, exog_idx_item = maybe_name_or_idx(item, model) + exog_name.append(exog_name_item) + exog_idx.append(exog_idx_item) + else: # assume we've got a string variable + exog_name = idx + exog_idx = model.exog_names.index(idx) + + return exog_name, exog_idx + + +def get_data_names(series_or_dataframe): + """ + Input can be an array or pandas-like. Will handle 1d array-like but not + 2d. Returns a str for 1d data or a list of strings for 2d data. + """ + names = getattr(series_or_dataframe, 'name', None) + if not names: + names = getattr(series_or_dataframe, 'columns', None) + if not names: + shape = getattr(series_or_dataframe, 'shape', [1]) + nvars = 1 if len(shape) == 1 else series_or_dataframe.shape[1] + names = ["X%d" for _ in range(nvars)] + if nvars == 1: + names = names[0] + else: + names = names.tolist() + return names + + +def annotate_axes(index, labels, points, offset_points, size, ax, **kwargs): + """ + Annotate Axes with labels, points, offset_points according to the + given index. + """ + for i in index: + label = labels[i] + point = points[i] + offset = offset_points[i] + ax.annotate(label, point, xytext=offset, textcoords="offset points", + size=size, **kwargs) + return ax diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/miscmodels/count.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/miscmodels/count.py new file mode 100644 index 0000000000000000000000000000000000000000..fbc07822915bb5c67d3a3720a00bf6670276bd1f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/miscmodels/count.py @@ -0,0 +1,215 @@ +""" +Created on Mon Jul 26 08:34:59 2010 + +Author: josef-pktd + +changes: +added offset and zero-inflated version of Poisson + - kind of ok, need better test cases, + - a nan in ZIP bse, need to check hessian calculations + - found error in ZIP loglike + - all tests pass with + +Issues +------ +* If true model is not zero-inflated then numerical Hessian for ZIP has zeros + for the inflation probability and is not invertible. + -> hessian inverts and bse look ok if row and column are dropped, pinv also works +* GenericMLE: still get somewhere (where?) + "CacheWriteWarning: The attribute 'bse' cannot be overwritten" +* bfgs is too fragile, does not come back +* `nm` is slow but seems to work +* need good start_params and their use in genericmle needs to be checked for + consistency, set as attribute or method (called as attribute) +* numerical hessian needs better scaling + +* check taking parts out of the loop, e.g. factorial(endog) could be precalculated + + +""" +import numpy as np +from scipy import stats +from scipy.special import factorial +from statsmodels.base.model import GenericLikelihoodModel + + +def maxabs(arr1, arr2): + return np.max(np.abs(arr1 - arr2)) + +def maxabsrel(arr1, arr2): + return np.max(np.abs(arr2 / arr1 - 1)) + + + +class PoissonGMLE(GenericLikelihoodModel): + '''Maximum Likelihood Estimation of Poisson Model + + This is an example for generic MLE which has the same + statistical model as discretemod.Poisson. + + Except for defining the negative log-likelihood method, all + methods and results are generic. Gradients and Hessian + and all resulting statistics are based on numerical + differentiation. + + ''' + + # copied from discretemod.Poisson + def nloglikeobs(self, params): + """ + Loglikelihood of Poisson model + + Parameters + ---------- + params : array_like + The parameters of the model. + + Returns + ------- + The log likelihood of the model evaluated at `params` + + Notes + ----- + .. math:: \\ln L=\\sum_{i=1}^{n}\\left[-\\lambda_{i}+y_{i}x_{i}^{\\prime}\\beta-\\ln y_{i}!\\right] + """ + XB = np.dot(self.exog, params) + endog = self.endog + return np.exp(XB) - endog*XB + np.log(factorial(endog)) + + def predict_distribution(self, exog): + '''return frozen scipy.stats distribution with mu at estimated prediction + ''' + if not hasattr(self, "result"): + # TODO: why would this be ValueError instead of AttributeError? + # TODO: Why even make this a Model attribute in the first place? + # It belongs on the Results class + raise ValueError + else: + result = self.result + params = result.params + mu = np.exp(np.dot(exog, params)) + return stats.poisson(mu, loc=0) + + + +class PoissonOffsetGMLE(GenericLikelihoodModel): + '''Maximum Likelihood Estimation of Poisson Model + + This is an example for generic MLE which has the same + statistical model as discretemod.Poisson but adds offset + + Except for defining the negative log-likelihood method, all + methods and results are generic. Gradients and Hessian + and all resulting statistics are based on numerical + differentiation. + + ''' + + def __init__(self, endog, exog=None, offset=None, missing='none', **kwds): + # let them be none in case user wants to use inheritance + if offset is not None: + if offset.ndim == 1: + offset = offset[:,None] #need column + self.offset = offset.ravel() + else: + self.offset = 0. + super().__init__(endog, exog, missing=missing, + **kwds) + +#this was added temporarily for bug-hunting, but should not be needed +# def loglike(self, params): +# return -self.nloglikeobs(params).sum(0) + + # original copied from discretemod.Poisson + def nloglikeobs(self, params): + """ + Loglikelihood of Poisson model + + Parameters + ---------- + params : array_like + The parameters of the model. + + Returns + ------- + The log likelihood of the model evaluated at `params` + + Notes + ----- + .. math:: \\ln L=\\sum_{i=1}^{n}\\left[-\\lambda_{i}+y_{i}x_{i}^{\\prime}\\beta-\\ln y_{i}!\\right] + """ + + XB = self.offset + np.dot(self.exog, params) + endog = self.endog + nloglik = np.exp(XB) - endog*XB + np.log(factorial(endog)) + return nloglik + +class PoissonZiGMLE(GenericLikelihoodModel): + '''Maximum Likelihood Estimation of Poisson Model + + This is an example for generic MLE which has the same statistical model + as discretemod.Poisson but adds offset and zero-inflation. + + Except for defining the negative log-likelihood method, all + methods and results are generic. Gradients and Hessian + and all resulting statistics are based on numerical + differentiation. + + There are numerical problems if there is no zero-inflation. + + ''' + + def __init__(self, endog, exog=None, offset=None, missing='none', **kwds): + # let them be none in case user wants to use inheritance + self.k_extra = 1 + super().__init__(endog, exog, missing=missing, + extra_params_names=["zi"], **kwds) + if offset is not None: + if offset.ndim == 1: + offset = offset[:,None] #need column + self.offset = offset.ravel() #which way? + else: + self.offset = 0. + + #TODO: it's not standard pattern to use default exog + if exog is None: + self.exog = np.ones((self.nobs,1)) + self.nparams = self.exog.shape[1] + #what's the shape in regression for exog if only constant + self.start_params = np.hstack((np.ones(self.nparams), 0)) + # need to add zi params to nparams + self.nparams += 1 + self.cloneattr = ['start_params'] + # needed for t_test and summary + # Note: no added to super __init__ which also adjusts df_resid + # self.exog_names.append('zi') + + + # original copied from discretemod.Poisson + def nloglikeobs(self, params): + """ + Loglikelihood of Poisson model + + Parameters + ---------- + params : array_like + The parameters of the model. + + Returns + ------- + The log likelihood of the model evaluated at `params` + + Notes + ----- + .. math:: \\ln L=\\sum_{i=1}^{n}\\left[-\\lambda_{i}+y_{i}x_{i}^{\\prime}\\beta-\\ln y_{i}!\\right] + """ + beta = params[:-1] + gamm = 1 / (1 + np.exp(params[-1])) #check this + # replace with np.dot(self.exogZ, gamma) + #print(np.shape(self.offset), self.exog.shape, beta.shape + XB = self.offset + np.dot(self.exog, beta) + endog = self.endog + nloglik = -np.log(1-gamm) + np.exp(XB) - endog*XB + np.log(factorial(endog)) + nloglik[endog==0] = - np.log(gamm + np.exp(-nloglik[endog==0])) + + return nloglik diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/miscmodels/nonlinls.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/miscmodels/nonlinls.py new file mode 100644 index 0000000000000000000000000000000000000000..126433a01a7ed6ec56d2b3118bdcecc03c29f7ec --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/miscmodels/nonlinls.py @@ -0,0 +1,309 @@ +'''Non-linear least squares + + + +Author: Josef Perktold based on scipy.optimize.curve_fit + +''' +import numpy as np +from scipy import optimize + +from statsmodels.base.model import Model + + +class Results: + '''just a dummy placeholder for now + most results from RegressionResults can be used here + ''' + pass + + +##def getjaccov(retval, n): +## '''calculate something and raw covariance matrix from return of optimize.leastsq +## +## I cannot figure out how to recover the Jacobian, or whether it is even +## possible +## +## this is a partial copy of scipy.optimize.leastsq +## ''' +## info = retval[-1] +## #n = len(x0) #nparams, where do I get this +## cov_x = None +## if info in [1,2,3,4]: +## from numpy.dual import inv +## from numpy.linalg import LinAlgError +## perm = np.take(np.eye(n), retval[1]['ipvt']-1,0) +## r = np.triu(np.transpose(retval[1]['fjac'])[:n,:]) +## R = np.dot(r, perm) +## try: +## cov_x = inv(np.dot(np.transpose(R),R)) +## except LinAlgError: +## print 'cov_x not available' +## pass +## return r, R, cov_x +## +##def _general_function(params, xdata, ydata, function): +## return function(xdata, *params) - ydata +## +##def _weighted_general_function(params, xdata, ydata, function, weights): +## return weights * (function(xdata, *params) - ydata) +## + + + +class NonlinearLS(Model): #or subclass a model + r'''Base class for estimation of a non-linear model with least squares + + This class is supposed to be subclassed, and the subclass has to provide a method + `_predict` that defines the non-linear function `f(params) that is predicting the endogenous + variable. The model is assumed to be + + :math: y = f(params) + error + + and the estimator minimizes the sum of squares of the estimated error. + + :math: min_parmas \sum (y - f(params))**2 + + f has to return the prediction for each observation. Exogenous or explanatory variables + should be accessed as attributes of the class instance, and can be given as arguments + when the instance is created. + + Warning: + Weights are not correctly handled yet in the results statistics, + but included when estimating the parameters. + + similar to scipy.optimize.curve_fit + API difference: params are array_like not split up, need n_params information + + includes now weights similar to curve_fit + no general sigma yet (OLS and WLS, but no GLS) + + This is currently holding on to intermediate results that are not necessary + but useful for testing. + + Fit returns and instance of RegressionResult, in contrast to the linear + model, results in this case are based on a local approximation, essentially + y = f(X, params) is replaced by y = grad * params where grad is the Gradient + or Jacobian with the shape (nobs, nparams). See for example Greene + + Examples + -------- + + class Myfunc(NonlinearLS): + + def _predict(self, params): + x = self.exog + a, b, c = params + return a*np.exp(-b*x) + c + + Ff we have data (y, x), we can create an instance and fit it with + + mymod = Myfunc(y, x) + myres = mymod.fit(nparams=3) + + and use the non-linear regression results, for example + + myres.params + myres.bse + myres.tvalues + + + ''' + #NOTE: This needs to call super for data checking + def __init__(self, endog=None, exog=None, weights=None, sigma=None, + missing='none'): + self.endog = endog + self.exog = exog + if sigma is not None: + sigma = np.asarray(sigma) + if sigma.ndim < 2: + self.sigma = sigma + self.weights = 1./sigma + else: + raise ValueError('correlated errors are not handled yet') + else: + self.weights = None + + def predict(self, exog, params=None): + #copied from GLS, Model has different signature + return self._predict(params) + + + def _predict(self, params): + pass + + def start_value(self): + return None + + def geterrors(self, params, weights=None): + if weights is None: + if self.weights is None: + return self.endog - self._predict(params) + else: + weights = self.weights + return weights * (self.endog - self._predict(params)) + + def errorsumsquares(self, params): + return (self.geterrors(params)**2).sum() + + + def fit(self, start_value=None, nparams=None, **kw): + #if hasattr(self, 'start_value'): + #I added start_value even if it's empty, not sure about it + #but it makes a visible placeholder + + if start_value is not None: + p0 = start_value + else: + #nesting so that start_value is only calculated if it is needed + p0 = self.start_value() + if p0 is not None: + pass + elif nparams is not None: + p0 = 0.1 * np.ones(nparams) + else: + raise ValueError('need information about start values for' + + 'optimization') + + func = self.geterrors + res = optimize.leastsq(func, p0, full_output=1, **kw) + (popt, pcov, infodict, errmsg, ier) = res + + if ier not in [1,2,3,4]: + msg = "Optimal parameters not found: " + errmsg + raise RuntimeError(msg) + + err = infodict['fvec'] + + ydata = self.endog + if (len(ydata) > len(p0)) and pcov is not None: + #this can use the returned errors instead of recalculating + + s_sq = (err**2).sum()/(len(ydata)-len(p0)) + pcov = pcov * s_sq + else: + pcov = None + + self.df_resid = len(ydata)-len(p0) + self.df_model = len(p0) + fitres = Results() + fitres.params = popt + fitres.pcov = pcov + fitres.rawres = res + self.wendog = self.endog #add weights + self.wexog = self.jac_predict(popt) + pinv_wexog = np.linalg.pinv(self.wexog) + self.normalized_cov_params = np.dot(pinv_wexog, + np.transpose(pinv_wexog)) + + #TODO: check effect of `weights` on result statistics + #I think they are correctly included in cov_params + #maybe not anymore, I'm not using pcov of leastsq + #direct calculation with jac_predict misses the weights + +## if not weights is None +## fitres.wexogw = self.weights * self.jacpredict(popt) + from statsmodels.regression import RegressionResults + results = RegressionResults + + beta = popt + lfit = RegressionResults(self, beta, + normalized_cov_params=self.normalized_cov_params) + + lfit.fitres = fitres #mainly for testing + self._results = lfit + return lfit + + def fit_minimal(self, start_value, **kwargs): + '''minimal fitting with no extra calculations''' + func = self.geterrors + res = optimize.leastsq(func, start_value, full_output=0, **kwargs) + return res + + def fit_random(self, ntries=10, rvs_generator=None, nparams=None): + '''fit with random starting values + + this could be replaced with a global fitter + + ''' + + if nparams is None: + nparams = self.nparams + if rvs_generator is None: + rvs = np.random.uniform(low=-10, high=10, size=(ntries, nparams)) + else: + rvs = rvs_generator(size=(ntries, nparams)) + + results = np.array([np.r_[self.fit_minimal(rv), rv] for rv in rvs]) + #selct best results and check how many solutions are within 1e-6 of best + #not sure what leastsq returns + return results + + def jac_predict(self, params): + '''jacobian of prediction function using complex step derivative + + This assumes that the predict function does not use complex variable + but is designed to do so. + + ''' + from statsmodels.tools.numdiff import approx_fprime_cs + + jaccs_err = approx_fprime_cs(params, self._predict) + return jaccs_err + + +class Myfunc(NonlinearLS): + + #predict model.Model has a different signature +## def predict(self, params, exog=None): +## if not exog is None: +## x = exog +## else: +## x = self.exog +## a, b, c = params +## return a*np.exp(-b*x) + c + + def _predict(self, params): + x = self.exog + a, b, c = params + return a*np.exp(-b*x) + c + + + + + +if __name__ == '__main__': + def func0(x, a, b, c): + return a*np.exp(-b*x) + c + + def func(params, x): + a, b, c = params + return a*np.exp(-b*x) + c + + def error(params, x, y): + return y - func(params, x) + + def error2(params, x, y): + return (y - func(params, x))**2 + + + + + x = np.linspace(0,4,50) + params = np.array([2.5, 1.3, 0.5]) + y0 = func(params, x) + y = y0 + 0.2*np.random.normal(size=len(x)) + + res = optimize.leastsq(error, params, args=(x, y), full_output=True) +## r, R, c = getjaccov(res[1:], 3) + + mod = Myfunc(y, x) + resmy = mod.fit(nparams=3) + + cf_params, cf_pcov = optimize.curve_fit(func0, x, y) + cf_bse = np.sqrt(np.diag(cf_pcov)) + print(res[0]) + print(cf_params) + print(resmy.params) + print(cf_bse) + print(resmy.bse) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/robust/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/robust/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a02632942e82e0f631516420938479b0d1ca037a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/robust/__init__.py @@ -0,0 +1,10 @@ +""" +Robust statistical models +""" +__all__ = ["norms", "mad", "Huber", "HuberScale", "hubers_scale", "test"] +from . import norms +from .scale import mad, Huber, HuberScale, hubers_scale + +from statsmodels.tools._test_runner import PytestTester + +test = PytestTester() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/robust/norms.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/robust/norms.py new file mode 100644 index 0000000000000000000000000000000000000000..a00e519714505fc4176f957b021623c2c85381ea --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/robust/norms.py @@ -0,0 +1,1068 @@ +import numpy as np + +# TODO: add plots to weighting functions for online docs. + + +def _cabs(x): + """absolute value function that changes complex sign based on real sign + + This could be useful for complex step derivatives of functions that + need abs. Not yet used. + """ + sign = (x.real >= 0) * 2 - 1 + return sign * x + + +class RobustNorm: + """ + The parent class for the norms used for robust regression. + + Lays out the methods expected of the robust norms to be used + by statsmodels.RLM. + + See Also + -------- + statsmodels.rlm + + Notes + ----- + Currently only M-estimators are available. + + References + ---------- + PJ Huber. 'Robust Statistics' John Wiley and Sons, Inc., New York, 1981. + + DC Montgomery, EA Peck. 'Introduction to Linear Regression Analysis', + John Wiley and Sons, Inc., New York, 2001. + + R Venables, B Ripley. 'Modern Applied Statistics in S' + Springer, New York, 2002. + """ + + def rho(self, z): + """ + The robust criterion estimator function. + + Abstract method: + + -2 loglike used in M-estimator + """ + raise NotImplementedError + + def psi(self, z): + """ + Derivative of rho. Sometimes referred to as the influence function. + + Abstract method: + + psi = rho' + """ + raise NotImplementedError + + def weights(self, z): + """ + Returns the value of psi(z) / z + + Abstract method: + + psi(z) / z + """ + raise NotImplementedError + + def psi_deriv(self, z): + """ + Derivative of psi. Used to obtain robust covariance matrix. + + See statsmodels.rlm for more information. + + Abstract method: + + psi_derive = psi' + """ + raise NotImplementedError + + def __call__(self, z): + """ + Returns the value of estimator rho applied to an input + """ + return self.rho(z) + + +class LeastSquares(RobustNorm): + """ + Least squares rho for M-estimation and its derived functions. + + See Also + -------- + statsmodels.robust.norms.RobustNorm + """ + + def rho(self, z): + """ + The least squares estimator rho function + + Parameters + ---------- + z : ndarray + 1d array + + Returns + ------- + rho : ndarray + rho(z) = (1/2.)*z**2 + """ + + return z**2 * 0.5 + + def psi(self, z): + """ + The psi function for the least squares estimator + + The analytic derivative of rho + + Parameters + ---------- + z : array_like + 1d array + + Returns + ------- + psi : ndarray + psi(z) = z + """ + + return np.asarray(z) + + def weights(self, z): + """ + The least squares estimator weighting function for the IRLS algorithm. + + The psi function scaled by the input z + + Parameters + ---------- + z : array_like + 1d array + + Returns + ------- + weights : ndarray + weights(z) = np.ones(z.shape) + """ + + z = np.asarray(z) + return np.ones(z.shape, np.float64) + + def psi_deriv(self, z): + """ + The derivative of the least squares psi function. + + Returns + ------- + psi_deriv : ndarray + ones(z.shape) + + Notes + ----- + Used to estimate the robust covariance matrix. + """ + return np.ones(z.shape, np.float64) + + +class HuberT(RobustNorm): + """ + Huber's T for M estimation. + + Parameters + ---------- + t : float, optional + The tuning constant for Huber's t function. The default value is + 1.345. + + See Also + -------- + statsmodels.robust.norms.RobustNorm + """ + + def __init__(self, t=1.345): + self.t = t + + def _subset(self, z): + """ + Huber's T is defined piecewise over the range for z + """ + z = np.asarray(z) + return np.less_equal(np.abs(z), self.t) + + def rho(self, z): + r""" + The robust criterion function for Huber's t. + + Parameters + ---------- + z : array_like + 1d array + + Returns + ------- + rho : ndarray + rho(z) = .5*z**2 for \|z\| <= t + + rho(z) = \|z\|*t - .5*t**2 for \|z\| > t + """ + z = np.asarray(z) + test = self._subset(z) + return (test * 0.5 * z**2 + + (1 - test) * (np.abs(z) * self.t - 0.5 * self.t**2)) + + def psi(self, z): + r""" + The psi function for Huber's t estimator + + The analytic derivative of rho + + Parameters + ---------- + z : array_like + 1d array + + Returns + ------- + psi : ndarray + psi(z) = z for \|z\| <= t + + psi(z) = sign(z)*t for \|z\| > t + """ + z = np.asarray(z) + test = self._subset(z) + return test * z + (1 - test) * self.t * np.sign(z) + + def weights(self, z): + r""" + Huber's t weighting function for the IRLS algorithm + + The psi function scaled by z + + Parameters + ---------- + z : array_like + 1d array + + Returns + ------- + weights : ndarray + weights(z) = 1 for \|z\| <= t + + weights(z) = t/\|z\| for \|z\| > t + """ + z_isscalar = np.isscalar(z) + z = np.atleast_1d(z) + + test = self._subset(z) + absz = np.abs(z) + absz[test] = 1.0 + v = test + (1 - test) * self.t / absz + + if z_isscalar: + v = v[0] + return v + + def psi_deriv(self, z): + """ + The derivative of Huber's t psi function + + Notes + ----- + Used to estimate the robust covariance matrix. + """ + return np.less_equal(np.abs(z), self.t).astype(float) + + +# TODO: untested, but looks right. RamsayE not available in R or SAS? +class RamsayE(RobustNorm): + """ + Ramsay's Ea for M estimation. + + Parameters + ---------- + a : float, optional + The tuning constant for Ramsay's Ea function. The default value is + 0.3. + + See Also + -------- + statsmodels.robust.norms.RobustNorm + """ + + def __init__(self, a=.3): + self.a = a + + def rho(self, z): + r""" + The robust criterion function for Ramsay's Ea. + + Parameters + ---------- + z : array_like + 1d array + + Returns + ------- + rho : ndarray + rho(z) = a**-2 * (1 - exp(-a*\|z\|)*(1 + a*\|z\|)) + """ + z = np.asarray(z) + return (1 - np.exp(-self.a * np.abs(z)) * + (1 + self.a * np.abs(z))) / self.a**2 + + def psi(self, z): + r""" + The psi function for Ramsay's Ea estimator + + The analytic derivative of rho + + Parameters + ---------- + z : array_like + 1d array + + Returns + ------- + psi : ndarray + psi(z) = z*exp(-a*\|z\|) + """ + z = np.asarray(z) + return z * np.exp(-self.a * np.abs(z)) + + def weights(self, z): + r""" + Ramsay's Ea weighting function for the IRLS algorithm + + The psi function scaled by z + + Parameters + ---------- + z : array_like + 1d array + + Returns + ------- + weights : ndarray + weights(z) = exp(-a*\|z\|) + """ + + z = np.asarray(z) + return np.exp(-self.a * np.abs(z)) + + def psi_deriv(self, z): + """ + The derivative of Ramsay's Ea psi function. + + Notes + ----- + Used to estimate the robust covariance matrix. + """ + a = self.a + x = np.exp(-a * np.abs(z)) + dx = -a * x * np.sign(z) + y = z + dy = 1 + return x * dy + y * dx + + +class AndrewWave(RobustNorm): + """ + Andrew's wave for M estimation. + + Parameters + ---------- + a : float, optional + The tuning constant for Andrew's Wave function. The default value is + 1.339. + + See Also + -------- + statsmodels.robust.norms.RobustNorm + """ + def __init__(self, a=1.339): + self.a = a + + def _subset(self, z): + """ + Andrew's wave is defined piecewise over the range of z. + """ + z = np.asarray(z) + return np.less_equal(np.abs(z), self.a * np.pi) + + def rho(self, z): + r""" + The robust criterion function for Andrew's wave. + + Parameters + ---------- + z : array_like + 1d array + + Returns + ------- + rho : ndarray + The elements of rho are defined as: + + .. math:: + + rho(z) & = a^2 *(1-cos(z/a)), |z| \leq a\pi \\ + rho(z) & = 2a, |z|>q\pi + """ + + a = self.a + z = np.asarray(z) + test = self._subset(z) + return (test * a**2 * (1 - np.cos(z / a)) + + (1 - test) * a**2 * 2) + + def psi(self, z): + r""" + The psi function for Andrew's wave + + The analytic derivative of rho + + Parameters + ---------- + z : array_like + 1d array + + Returns + ------- + psi : ndarray + psi(z) = a * sin(z/a) for \|z\| <= a*pi + + psi(z) = 0 for \|z\| > a*pi + """ + + a = self.a + z = np.asarray(z) + test = self._subset(z) + return test * a * np.sin(z / a) + + def weights(self, z): + r""" + Andrew's wave weighting function for the IRLS algorithm + + The psi function scaled by z + + Parameters + ---------- + z : array_like + 1d array + + Returns + ------- + weights : ndarray + weights(z) = sin(z/a) / (z/a) for \|z\| <= a*pi + + weights(z) = 0 for \|z\| > a*pi + """ + a = self.a + z = np.asarray(z) + test = self._subset(z) + ratio = z / a + small = np.abs(ratio) < np.finfo(np.double).eps + if np.any(small): + weights = np.ones_like(ratio) + large = ~small + ratio = ratio[large] + weights[large] = test[large] * np.sin(ratio) / ratio + else: + weights = test * np.sin(ratio) / ratio + return weights + + def psi_deriv(self, z): + """ + The derivative of Andrew's wave psi function + + Notes + ----- + Used to estimate the robust covariance matrix. + """ + + test = self._subset(z) + return test * np.cos(z / self.a) + + +# TODO: this is untested +class TrimmedMean(RobustNorm): + """ + Trimmed mean function for M-estimation. + + Parameters + ---------- + c : float, optional + The tuning constant for Ramsay's Ea function. The default value is + 2.0. + + See Also + -------- + statsmodels.robust.norms.RobustNorm + """ + + def __init__(self, c=2.): + self.c = c + + def _subset(self, z): + """ + Least trimmed mean is defined piecewise over the range of z. + """ + + z = np.asarray(z) + return np.less_equal(np.abs(z), self.c) + + def rho(self, z): + r""" + The robust criterion function for least trimmed mean. + + Parameters + ---------- + z : array_like + 1d array + + Returns + ------- + rho : ndarray + rho(z) = (1/2.)*z**2 for \|z\| <= c + + rho(z) = (1/2.)*c**2 for \|z\| > c + """ + + z = np.asarray(z) + test = self._subset(z) + return test * z**2 * 0.5 + (1 - test) * self.c**2 * 0.5 + + def psi(self, z): + r""" + The psi function for least trimmed mean + + The analytic derivative of rho + + Parameters + ---------- + z : array_like + 1d array + + Returns + ------- + psi : ndarray + psi(z) = z for \|z\| <= c + + psi(z) = 0 for \|z\| > c + """ + z = np.asarray(z) + test = self._subset(z) + return test * z + + def weights(self, z): + r""" + Least trimmed mean weighting function for the IRLS algorithm + + The psi function scaled by z + + Parameters + ---------- + z : array_like + 1d array + + Returns + ------- + weights : ndarray + weights(z) = 1 for \|z\| <= c + + weights(z) = 0 for \|z\| > c + """ + z = np.asarray(z) + test = self._subset(z) + return test + + def psi_deriv(self, z): + """ + The derivative of least trimmed mean psi function + + Notes + ----- + Used to estimate the robust covariance matrix. + """ + test = self._subset(z) + return test + + +class Hampel(RobustNorm): + """ + + Hampel function for M-estimation. + + Parameters + ---------- + a : float, optional + b : float, optional + c : float, optional + The tuning constants for Hampel's function. The default values are + a,b,c = 2, 4, 8. + + See Also + -------- + statsmodels.robust.norms.RobustNorm + """ + + def __init__(self, a=2., b=4., c=8.): + self.a = a + self.b = b + self.c = c + + def _subset(self, z): + """ + Hampel's function is defined piecewise over the range of z + """ + z = np.abs(np.asarray(z)) + t1 = np.less_equal(z, self.a) + t2 = np.less_equal(z, self.b) * np.greater(z, self.a) + t3 = np.less_equal(z, self.c) * np.greater(z, self.b) + return t1, t2, t3 + + def rho(self, z): + r""" + The robust criterion function for Hampel's estimator + + Parameters + ---------- + z : array_like + 1d array + + Returns + ------- + rho : ndarray + rho(z) = z**2 / 2 for \|z\| <= a + + rho(z) = a*\|z\| - 1/2.*a**2 for a < \|z\| <= b + + rho(z) = a*(c - \|z\|)**2 / (c - b) / 2 for b < \|z\| <= c + + rho(z) = a*(b + c - a) / 2 for \|z\| > c + """ + a, b, c = self.a, self.b, self.c + + z_isscalar = np.isscalar(z) + z = np.atleast_1d(z) + + t1, t2, t3 = self._subset(z) + t34 = ~(t1 | t2) + dt = np.promote_types(z.dtype, "float") + v = np.zeros(z.shape, dtype=dt) + z = np.abs(z) + v[t1] = z[t1]**2 * 0.5 + # v[t2] = (a * (z[t2] - a) + a**2 * 0.5) + v[t2] = (a * z[t2] - a**2 * 0.5) + v[t3] = a * (c - z[t3])**2 / (c - b) * (-0.5) + v[t34] += a * (b + c - a) * 0.5 + + if z_isscalar: + v = v[0] + + return v + + def psi(self, z): + r""" + The psi function for Hampel's estimator + + The analytic derivative of rho + + Parameters + ---------- + z : array_like + 1d array + + Returns + ------- + psi : ndarray + psi(z) = z for \|z\| <= a + + psi(z) = a*sign(z) for a < \|z\| <= b + + psi(z) = a*sign(z)*(c - \|z\|)/(c-b) for b < \|z\| <= c + + psi(z) = 0 for \|z\| > c + """ + a, b, c = self.a, self.b, self.c + + z_isscalar = np.isscalar(z) + z = np.atleast_1d(z) + + t1, t2, t3 = self._subset(z) + dt = np.promote_types(z.dtype, "float") + v = np.zeros(z.shape, dtype=dt) + s = np.sign(z) + za = np.abs(z) + + v[t1] = z[t1] + v[t2] = a * s[t2] + v[t3] = a * s[t3] * (c - za[t3]) / (c - b) + + if z_isscalar: + v = v[0] + return v + + def weights(self, z): + r""" + Hampel weighting function for the IRLS algorithm + + The psi function scaled by z + + Parameters + ---------- + z : array_like + 1d array + + Returns + ------- + weights : ndarray + weights(z) = 1 for \|z\| <= a + + weights(z) = a/\|z\| for a < \|z\| <= b + + weights(z) = a*(c - \|z\|)/(\|z\|*(c-b)) for b < \|z\| <= c + + weights(z) = 0 for \|z\| > c + """ + a, b, c = self.a, self.b, self.c + + z_isscalar = np.isscalar(z) + z = np.atleast_1d(z) + + t1, t2, t3 = self._subset(z) + + dt = np.promote_types(z.dtype, "float") + v = np.zeros(z.shape, dtype=dt) + v[t1] = 1.0 + abs_z = np.abs(z) + v[t2] = a / abs_z[t2] + abs_zt3 = abs_z[t3] + v[t3] = a * (c - abs_zt3) / (abs_zt3 * (c - b)) + + if z_isscalar: + v = v[0] + return v + + def psi_deriv(self, z): + """Derivative of psi function, second derivative of rho function. + """ + a, b, c = self.a, self.b, self.c + + z_isscalar = np.isscalar(z) + z = np.atleast_1d(z) + + t1, _, t3 = self._subset(z) + + dt = np.promote_types(z.dtype, "float") + d = np.zeros(z.shape, dtype=dt) + d[t1] = 1.0 + zt3 = z[t3] + d[t3] = -(a * np.sign(zt3) * zt3) / (np.abs(zt3) * (c - b)) + + if z_isscalar: + d = d[0] + return d + + +class TukeyBiweight(RobustNorm): + """ + + Tukey's biweight function for M-estimation. + + Parameters + ---------- + c : float, optional + The tuning constant for Tukey's Biweight. The default value is + c = 4.685. + + Notes + ----- + Tukey's biweight is sometime's called bisquare. + """ + + def __init__(self, c=4.685): + self.c = c + + def _subset(self, z): + """ + Tukey's biweight is defined piecewise over the range of z + """ + z = np.abs(np.asarray(z)) + return np.less_equal(z, self.c) + + def rho(self, z): + r""" + The robust criterion function for Tukey's biweight estimator + + Parameters + ---------- + z : array_like + 1d array + + Returns + ------- + rho : ndarray + rho(z) = -(1 - (z/c)**2)**3 * c**2/6. for \|z\| <= R + + rho(z) = 0 for \|z\| > R + """ + subset = self._subset(z) + factor = self.c**2 / 6. + return -(1 - (z / self.c)**2)**3 * subset * factor + factor + + def psi(self, z): + r""" + The psi function for Tukey's biweight estimator + + The analytic derivative of rho + + Parameters + ---------- + z : array_like + 1d array + + Returns + ------- + psi : ndarray + psi(z) = z*(1 - (z/c)**2)**2 for \|z\| <= R + + psi(z) = 0 for \|z\| > R + """ + + z = np.asarray(z) + subset = self._subset(z) + return z * (1 - (z / self.c)**2)**2 * subset + + def weights(self, z): + r""" + Tukey's biweight weighting function for the IRLS algorithm + + The psi function scaled by z + + Parameters + ---------- + z : array_like + 1d array + + Returns + ------- + weights : ndarray + psi(z) = (1 - (z/c)**2)**2 for \|z\| <= R + + psi(z) = 0 for \|z\| > R + """ + + subset = self._subset(z) + return (1 - (z / self.c)**2)**2 * subset + + def psi_deriv(self, z): + """ + The derivative of Tukey's biweight psi function + + Notes + ----- + Used to estimate the robust covariance matrix. + """ + subset = self._subset(z) + return subset * ((1 - (z/self.c)**2)**2 + - (4*z**2/self.c**2) * (1-(z/self.c)**2)) + + +class MQuantileNorm(RobustNorm): + """M-quantiles objective function based on a base norm + + This norm has the same asymmetric structure as the objective function + in QuantileRegression but replaces the L1 absolute value by a chosen + base norm. + + rho_q(u) = abs(q - I(q < 0)) * rho_base(u) + + or, equivalently, + + rho_q(u) = q * rho_base(u) if u >= 0 + rho_q(u) = (1 - q) * rho_base(u) if u < 0 + + + Parameters + ---------- + q : float + M-quantile, must be between 0 and 1 + base_norm : RobustNorm instance + basic norm that is transformed into an asymmetric M-quantile norm + + Notes + ----- + This is mainly for base norms that are not redescending, like HuberT or + LeastSquares. (See Jones for the relationship of M-quantiles to quantiles + in the case of non-redescending Norms.) + + Expectiles are M-quantiles with the LeastSquares as base norm. + + References + ---------- + + .. [*] Bianchi, Annamaria, and Nicola Salvati. 2015. “Asymptotic Properties + and Variance Estimators of the M-Quantile Regression Coefficients + Estimators.” Communications in Statistics - Theory and Methods 44 (11): + 2416–29. doi:10.1080/03610926.2013.791375. + + .. [*] Breckling, Jens, and Ray Chambers. 1988. “M-Quantiles.” + Biometrika 75 (4): 761–71. doi:10.2307/2336317. + + .. [*] Jones, M. C. 1994. “Expectiles and M-Quantiles Are Quantiles.” + Statistics & Probability Letters 20 (2): 149–53. + doi:10.1016/0167-7152(94)90031-0. + + .. [*] Newey, Whitney K., and James L. Powell. 1987. “Asymmetric Least + Squares Estimation and Testing.” Econometrica 55 (4): 819–47. + doi:10.2307/1911031. + """ + + def __init__(self, q, base_norm): + self.q = q + self.base_norm = base_norm + + def _get_q(self, z): + + nobs = len(z) + mask_neg = (z < 0) # if self.q < 0.5 else (z <= 0) # maybe symmetric + qq = np.empty(nobs) + qq[mask_neg] = 1 - self.q + qq[~mask_neg] = self.q + return qq + + def rho(self, z): + """ + The robust criterion function for MQuantileNorm. + + Parameters + ---------- + z : array_like + 1d array + + Returns + ------- + rho : ndarray + """ + qq = self._get_q(z) + return qq * self.base_norm.rho(z) + + def psi(self, z): + """ + The psi function for MQuantileNorm estimator. + + The analytic derivative of rho + + Parameters + ---------- + z : array_like + 1d array + + Returns + ------- + psi : ndarray + """ + qq = self._get_q(z) + return qq * self.base_norm.psi(z) + + def weights(self, z): + """ + MQuantileNorm weighting function for the IRLS algorithm + + The psi function scaled by z, psi(z) / z + + Parameters + ---------- + z : array_like + 1d array + + Returns + ------- + weights : ndarray + """ + qq = self._get_q(z) + return qq * self.base_norm.weights(z) + + def psi_deriv(self, z): + ''' + The derivative of MQuantileNorm function + + Parameters + ---------- + z : array_like + 1d array + + Returns + ------- + psi_deriv : ndarray + + Notes + ----- + Used to estimate the robust covariance matrix. + ''' + qq = self._get_q(z) + return qq * self.base_norm.psi_deriv(z) + + def __call__(self, z): + """ + Returns the value of estimator rho applied to an input + """ + return self.rho(z) + + +def estimate_location(a, scale, norm=None, axis=0, initial=None, + maxiter=30, tol=1.0e-06): + """ + M-estimator of location using self.norm and a current + estimator of scale. + + This iteratively finds a solution to + + norm.psi((a-mu)/scale).sum() == 0 + + Parameters + ---------- + a : ndarray + Array over which the location parameter is to be estimated + scale : ndarray + Scale parameter to be used in M-estimator + norm : RobustNorm, optional + Robust norm used in the M-estimator. The default is HuberT(). + axis : int, optional + Axis along which to estimate the location parameter. The default is 0. + initial : ndarray, optional + Initial condition for the location parameter. Default is None, which + uses the median of a. + niter : int, optional + Maximum number of iterations. The default is 30. + tol : float, optional + Toleration for convergence. The default is 1e-06. + + Returns + ------- + mu : ndarray + Estimate of location + """ + if norm is None: + norm = HuberT() + + if initial is None: + mu = np.median(a, axis) + else: + mu = initial + + for _ in range(maxiter): + W = norm.weights((a-mu)/scale) + nmu = np.sum(W*a, axis) / np.sum(W, axis) + if np.all(np.less(np.abs(mu - nmu), scale * tol)): + return nmu + else: + mu = nmu + raise ValueError("location estimator failed to converge in %d iterations" + % maxiter) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/robust/robust_linear_model.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/robust/robust_linear_model.py new file mode 100644 index 0000000000000000000000000000000000000000..cfc09b1c50ccd49158e348b7752b0d292a66c129 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/robust/robust_linear_model.py @@ -0,0 +1,569 @@ +""" +Robust linear models with support for the M-estimators listed under +:ref:`norms `. + +References +---------- +PJ Huber. 'Robust Statistics' John Wiley and Sons, Inc., New York. 1981. + +PJ Huber. 1973, 'The 1972 Wald Memorial Lectures: Robust Regression: + Asymptotics, Conjectures, and Monte Carlo.' The Annals of Statistics, + 1.5, 799-821. + +R Venables, B Ripley. 'Modern Applied Statistics in S' Springer, New York, + 2002. +""" +import numpy as np +import scipy.stats as stats + +import statsmodels.base.model as base +import statsmodels.base.wrapper as wrap +import statsmodels.regression._tools as reg_tools +import statsmodels.regression.linear_model as lm +import statsmodels.robust.norms as norms +import statsmodels.robust.scale as scale +from statsmodels.tools.decorators import cache_readonly +from statsmodels.tools.sm_exceptions import ConvergenceWarning + +__all__ = ['RLM'] + + +def _check_convergence(criterion, iteration, tol, maxiter): + cond = np.abs(criterion[iteration] - criterion[iteration - 1]) + return not (np.any(cond > tol) and iteration < maxiter) + + +class RLM(base.LikelihoodModel): + __doc__ = """ + Robust Linear Model + + Estimate a robust linear model via iteratively reweighted least squares + given a robust criterion estimator. + + {params} + M : statsmodels.robust.norms.RobustNorm, optional + The robust criterion function for downweighting outliers. + The current options are LeastSquares, HuberT, RamsayE, AndrewWave, + TrimmedMean, Hampel, and TukeyBiweight. The default is HuberT(). + See statsmodels.robust.norms for more information. + {extra_params} + + Attributes + ---------- + + df_model : float + The degrees of freedom of the model. The number of regressors p less + one for the intercept. Note that the reported model degrees + of freedom does not count the intercept as a regressor, though + the model is assumed to have an intercept. + df_resid : float + The residual degrees of freedom. The number of observations n + less the number of regressors p. Note that here p does include + the intercept as using a degree of freedom. + endog : ndarray + See above. Note that endog is a reference to the data so that if + data is already an array and it is changed, then `endog` changes + as well. + exog : ndarray + See above. Note that endog is a reference to the data so that if + data is already an array and it is changed, then `endog` changes + as well. + M : statsmodels.robust.norms.RobustNorm + See above. Robust estimator instance instantiated. + nobs : float + The number of observations n + pinv_wexog : ndarray + The pseudoinverse of the design / exogenous data array. Note that + RLM has no whiten method, so this is just the pseudo inverse of the + design. + normalized_cov_params : ndarray + The p x p normalized covariance of the design / exogenous data. + This is approximately equal to (X.T X)^(-1) + + Examples + -------- + >>> import statsmodels.api as sm + >>> data = sm.datasets.stackloss.load() + >>> data.exog = sm.add_constant(data.exog) + >>> rlm_model = sm.RLM(data.endog, data.exog, \ + M=sm.robust.norms.HuberT()) + + >>> rlm_results = rlm_model.fit() + >>> rlm_results.params + array([ 0.82938433, 0.92606597, -0.12784672, -41.02649835]) + >>> rlm_results.bse + array([ 0.11100521, 0.30293016, 0.12864961, 9.79189854]) + >>> rlm_results_HC2 = rlm_model.fit(cov="H2") + >>> rlm_results_HC2.params + array([ 0.82938433, 0.92606597, -0.12784672, -41.02649835]) + >>> rlm_results_HC2.bse + array([ 0.11945975, 0.32235497, 0.11796313, 9.08950419]) + >>> mod = sm.RLM(data.endog, data.exog, M=sm.robust.norms.Hampel()) + >>> rlm_hamp_hub = mod.fit(scale_est=sm.robust.scale.HuberScale()) + >>> rlm_hamp_hub.params + array([ 0.73175452, 1.25082038, -0.14794399, -40.27122257]) + """.format( + params=base._model_params_doc, extra_params=base._missing_param_doc + ) + + def __init__(self, endog, exog, M=None, missing='none', + **kwargs): + self._check_kwargs(kwargs) + self.M = M if M is not None else norms.HuberT() + super(base.LikelihoodModel, self).__init__(endog, exog, + missing=missing, **kwargs) + self._initialize() + # things to remove_data + self._data_attr.extend(['weights', 'pinv_wexog']) + + def _initialize(self): + """ + Initializes the model for the IRLS fit. + + Resets the history and number of iterations. + """ + self.pinv_wexog = np.linalg.pinv(self.exog) + self.normalized_cov_params = np.dot(self.pinv_wexog, + np.transpose(self.pinv_wexog)) + self.df_resid = (float(self.exog.shape[0] - + np.linalg.matrix_rank(self.exog))) + self.df_model = float(np.linalg.matrix_rank(self.exog) - 1) + self.nobs = float(self.endog.shape[0]) + + def score(self, params): + raise NotImplementedError + + def information(self, params): + raise NotImplementedError + + def predict(self, params, exog=None): + """ + Return linear predicted values from a design matrix. + + Parameters + ---------- + params : array_like + Parameters of a linear model + exog : array_like, optional. + Design / exogenous data. Model exog is used if None. + + Returns + ------- + An array of fitted values + """ + # copied from linear_model # TODO: then is it needed? + if exog is None: + exog = self.exog + return np.dot(exog, params) + + def loglike(self, params): + raise NotImplementedError + + def deviance(self, tmp_results): + """ + Returns the (unnormalized) log-likelihood from the M estimator. + """ + tmp_resid = self.endog - tmp_results.fittedvalues + return self.M(tmp_resid / tmp_results.scale).sum() + + def _update_history(self, tmp_results, history, conv): + history['params'].append(tmp_results.params) + history['scale'].append(tmp_results.scale) + if conv == 'dev': + history['deviance'].append(self.deviance(tmp_results)) + elif conv == 'sresid': + history['sresid'].append(tmp_results.resid / tmp_results.scale) + elif conv == 'weights': + history['weights'].append(tmp_results.model.weights) + return history + + def _estimate_scale(self, resid): + """ + Estimates the scale based on the option provided to the fit method. + """ + if isinstance(self.scale_est, str): + if self.scale_est.lower() == 'mad': + return scale.mad(resid, center=0) + else: + raise ValueError("Option %s for scale_est not understood" % + self.scale_est) + elif isinstance(self.scale_est, scale.HuberScale): + return self.scale_est(self.df_resid, self.nobs, resid) + else: + return scale.scale_est(self, resid) ** 2 + + def fit(self, maxiter=50, tol=1e-8, scale_est='mad', init=None, cov='H1', + update_scale=True, conv='dev', start_params=None): + """ + Fits the model using iteratively reweighted least squares. + + The IRLS routine runs until the specified objective converges to `tol` + or `maxiter` has been reached. + + Parameters + ---------- + conv : str + Indicates the convergence criteria. + Available options are "coefs" (the coefficients), "weights" (the + weights in the iteration), "sresid" (the standardized residuals), + and "dev" (the un-normalized log-likelihood for the M + estimator). The default is "dev". + cov : str, optional + 'H1', 'H2', or 'H3' + Indicates how the covariance matrix is estimated. Default is 'H1'. + See rlm.RLMResults for more information. + init : str + Specifies method for the initial estimates of the parameters. + Default is None, which means that the least squares estimate + is used. Currently it is the only available choice. + maxiter : int + The maximum number of iterations to try. Default is 50. + scale_est : str or HuberScale() + 'mad' or HuberScale() + Indicates the estimate to use for scaling the weights in the IRLS. + The default is 'mad' (median absolute deviation. Other options are + 'HuberScale' for Huber's proposal 2. Huber's proposal 2 has + optional keyword arguments d, tol, and maxiter for specifying the + tuning constant, the convergence tolerance, and the maximum number + of iterations. See statsmodels.robust.scale for more information. + tol : float + The convergence tolerance of the estimate. Default is 1e-8. + update_scale : Bool + If `update_scale` is False then the scale estimate for the + weights is held constant over the iteration. Otherwise, it + is updated for each fit in the iteration. Default is True. + start_params : array_like, optional + Initial guess of the solution of the optimizer. If not provided, + the initial parameters are computed using OLS. + + Returns + ------- + results : statsmodels.rlm.RLMresults + Results instance + """ + if cov.upper() not in ["H1", "H2", "H3"]: + raise ValueError("Covariance matrix %s not understood" % cov) + else: + self.cov = cov.upper() + conv = conv.lower() + if conv not in ["weights", "coefs", "dev", "sresid"]: + raise ValueError("Convergence argument %s not understood" % conv) + self.scale_est = scale_est + + if start_params is None: + wls_results = lm.WLS(self.endog, self.exog).fit() + else: + start_params = np.asarray(start_params, dtype=np.double).squeeze() + if (start_params.shape[0] != self.exog.shape[1] or + start_params.ndim != 1): + raise ValueError('start_params must by a 1-d array with {} ' + 'values'.format(self.exog.shape[1])) + fake_wls = reg_tools._MinimalWLS(self.endog, self.exog, + weights=np.ones_like(self.endog), + check_weights=False) + wls_results = fake_wls.results(start_params) + + if not init: + self.scale = self._estimate_scale(wls_results.resid) + + history = dict(params=[np.inf], scale=[]) + if conv == 'coefs': + criterion = history['params'] + elif conv == 'dev': + history.update(dict(deviance=[np.inf])) + criterion = history['deviance'] + elif conv == 'sresid': + history.update(dict(sresid=[np.inf])) + criterion = history['sresid'] + elif conv == 'weights': + history.update(dict(weights=[np.inf])) + criterion = history['weights'] + + # done one iteration so update + history = self._update_history(wls_results, history, conv) + iteration = 1 + converged = 0 + while not converged: + if self.scale == 0.0: + import warnings + warnings.warn('Estimated scale is 0.0 indicating that the most' + ' last iteration produced a perfect fit of the ' + 'weighted data.', ConvergenceWarning) + break + self.weights = self.M.weights(wls_results.resid / self.scale) + wls_results = reg_tools._MinimalWLS(self.endog, self.exog, + weights=self.weights, + check_weights=True).fit() + if update_scale is True: + self.scale = self._estimate_scale(wls_results.resid) + history = self._update_history(wls_results, history, conv) + iteration += 1 + converged = _check_convergence(criterion, iteration, tol, maxiter) + results = RLMResults(self, wls_results.params, + self.normalized_cov_params, self.scale) + + history['iteration'] = iteration + results.fit_history = history + results.fit_options = dict(cov=cov.upper(), scale_est=scale_est, + norm=self.M.__class__.__name__, conv=conv) + # norm is not changed in fit, no old state + + # doing the next causes exception + # self.cov = self.scale_est = None #reset for additional fits + # iteration and history could contain wrong state with repeated fit + return RLMResultsWrapper(results) + + +class RLMResults(base.LikelihoodModelResults): + """ + Class to contain RLM results + + Attributes + ---------- + + bcov_scaled : ndarray + p x p scaled covariance matrix specified in the model fit method. + The default is H1. H1 is defined as + ``k**2 * (1/df_resid*sum(M.psi(sresid)**2)*scale**2)/ + ((1/nobs*sum(M.psi_deriv(sresid)))**2) * (X.T X)^(-1)`` + + where ``k = 1 + (df_model +1)/nobs * var_psiprime/m**2`` + where ``m = mean(M.psi_deriv(sresid))`` and + ``var_psiprime = var(M.psi_deriv(sresid))`` + + H2 is defined as + ``k * (1/df_resid) * sum(M.psi(sresid)**2) *scale**2/ + ((1/nobs)*sum(M.psi_deriv(sresid)))*W_inv`` + + H3 is defined as + ``1/k * (1/df_resid * sum(M.psi(sresid)**2)*scale**2 * + (W_inv X.T X W_inv))`` + + where `k` is defined as above and + ``W_inv = (M.psi_deriv(sresid) exog.T exog)^(-1)`` + + See the technical documentation for cleaner formulae. + bcov_unscaled : ndarray + The usual p x p covariance matrix with scale set equal to 1. It + is then just equivalent to normalized_cov_params. + bse : ndarray + An array of the standard errors of the parameters. The standard + errors are taken from the robust covariance matrix specified in the + argument to fit. + chisq : ndarray + An array of the chi-squared values of the parameter estimates. + df_model + See RLM.df_model + df_resid + See RLM.df_resid + fit_history : dict + Contains information about the iterations. Its keys are `deviance`, + `params`, `iteration` and the convergence criteria specified in + `RLM.fit`, if different from `deviance` or `params`. + fit_options : dict + Contains the options given to fit. + fittedvalues : ndarray + The linear predicted values. dot(exog, params) + model : statsmodels.rlm.RLM + A reference to the model instance + nobs : float + The number of observations n + normalized_cov_params : ndarray + See RLM.normalized_cov_params + params : ndarray + The coefficients of the fitted model + pinv_wexog : ndarray + See RLM.pinv_wexog + pvalues : ndarray + The p values associated with `tvalues`. Note that `tvalues` are assumed + to be distributed standard normal rather than Student's t. + resid : ndarray + The residuals of the fitted model. endog - fittedvalues + scale : float + The type of scale is determined in the arguments to the fit method in + RLM. The reported scale is taken from the residuals of the weighted + least squares in the last IRLS iteration if update_scale is True. If + update_scale is False, then it is the scale given by the first OLS + fit before the IRLS iterations. + sresid : ndarray + The scaled residuals. + tvalues : ndarray + The "t-statistics" of params. These are defined as params/bse where + bse are taken from the robust covariance matrix specified in the + argument to fit. + weights : ndarray + The reported weights are determined by passing the scaled residuals + from the last weighted least squares fit in the IRLS algorithm. + + See Also + -------- + statsmodels.base.model.LikelihoodModelResults + """ + + def __init__(self, model, params, normalized_cov_params, scale): + super().__init__(model, params, normalized_cov_params, scale) + self.model = model + self.df_model = model.df_model + self.df_resid = model.df_resid + self.nobs = model.nobs + self._cache = {} + # for remove_data + self._data_in_cache.extend(['sresid']) + + self.cov_params_default = self.bcov_scaled + # TODO: "pvals" should come from chisq on bse? + + @cache_readonly + def fittedvalues(self): + return np.dot(self.model.exog, self.params) + + @cache_readonly + def resid(self): + return self.model.endog - self.fittedvalues # before bcov + + @cache_readonly + def sresid(self): + if self.scale == 0.0: + sresid = self.resid.copy() + sresid[:] = 0.0 + return sresid + return self.resid / self.scale + + @cache_readonly + def bcov_unscaled(self): + return self.normalized_cov_params + + @cache_readonly + def weights(self): + return self.model.weights + + @cache_readonly + def bcov_scaled(self): + model = self.model + m = np.mean(model.M.psi_deriv(self.sresid)) + var_psiprime = np.var(model.M.psi_deriv(self.sresid)) + k = 1 + (self.df_model + 1) / self.nobs * var_psiprime / m ** 2 + + if model.cov == "H1": + ss_psi = np.sum(model.M.psi(self.sresid) ** 2) + s_psi_deriv = np.sum(model.M.psi_deriv(self.sresid)) + return k ** 2 * (1 / self.df_resid * ss_psi * self.scale ** 2) /\ + ((1 / self.nobs * s_psi_deriv) ** 2) *\ + model.normalized_cov_params + else: + W = np.dot(model.M.psi_deriv(self.sresid) * model.exog.T, + model.exog) + W_inv = np.linalg.inv(W) + # [W_jk]^-1 = [SUM(psi_deriv(Sr_i)*x_ij*x_jk)]^-1 + # where Sr are the standardized residuals + if model.cov == "H2": + # These are correct, based on Huber (1973) 8.13 + return k * (1 / self.df_resid) * np.sum( + model.M.psi(self.sresid) ** 2) * self.scale ** 2 \ + / ((1 / self.nobs) * + np.sum(model.M.psi_deriv(self.sresid))) * W_inv + elif model.cov == "H3": + return k ** -1 * 1 / self.df_resid * np.sum( + model.M.psi(self.sresid) ** 2) * self.scale ** 2 \ + * np.dot( + np.dot(W_inv, np.dot(model.exog.T, model.exog)), + W_inv) + + @cache_readonly + def pvalues(self): + return stats.norm.sf(np.abs(self.tvalues)) * 2 + + @cache_readonly + def bse(self): + return np.sqrt(np.diag(self.bcov_scaled)) + + @cache_readonly + def chisq(self): + return (self.params / self.bse) ** 2 + + def summary(self, yname=None, xname=None, title=0, alpha=.05, + return_fmt='text'): + """ + This is for testing the new summary setup + """ + top_left = [('Dep. Variable:', None), + ('Model:', None), + ('Method:', ['IRLS']), + ('Norm:', [self.fit_options['norm']]), + ('Scale Est.:', [self.fit_options['scale_est']]), + ('Cov Type:', [self.fit_options['cov']]), + ('Date:', None), + ('Time:', None), + ('No. Iterations:', ["%d" % self.fit_history['iteration']]) + ] + top_right = [('No. Observations:', None), + ('Df Residuals:', None), + ('Df Model:', None) + ] + + if title is not None: + title = "Robust linear Model Regression Results" + + # boiler plate + from statsmodels.iolib.summary import Summary + smry = Summary() + smry.add_table_2cols(self, gleft=top_left, gright=top_right, + yname=yname, xname=xname, title=title) + smry.add_table_params(self, yname=yname, xname=xname, alpha=alpha, + use_t=self.use_t) + + # add warnings/notes, added to text format only + etext = [] + wstr = ("If the model instance has been used for another fit with " + "different fit parameters, then the fit options might not be " + "the correct ones anymore .") + etext.append(wstr) + + if etext: + smry.add_extra_txt(etext) + + return smry + + def summary2(self, xname=None, yname=None, title=None, alpha=.05, + float_format="%.4f"): + """Experimental summary function for regression results + + Parameters + ---------- + yname : str + Name of the dependent variable (optional) + xname : list[str], optional + Names for the exogenous variables. Default is `var_##` for ## in + the number of regressors. Must match the number of parameters + in the model + title : str, optional + Title for the top table. If not None, then this replaces the + default title + alpha : float + significance level for the confidence intervals + float_format : str + print format for floats in parameters summary + + Returns + ------- + smry : Summary instance + this holds the summary tables and text, which can be printed or + converted to various output formats. + + See Also + -------- + statsmodels.iolib.summary2.Summary : class to hold summary results + """ + from statsmodels.iolib import summary2 + smry = summary2.Summary() + smry.add_base(results=self, alpha=alpha, float_format=float_format, + xname=xname, yname=yname, title=title) + + return smry + + +class RLMResultsWrapper(lm.RegressionResultsWrapper): + pass + + +wrap.populate_wrapper(RLMResultsWrapper, RLMResults) # noqa:E305 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/robust/scale.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/robust/scale.py new file mode 100644 index 0000000000000000000000000000000000000000..1927d4db7a78d4548715d55617d1037c6f65a33d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/robust/scale.py @@ -0,0 +1,400 @@ +""" +Support and standalone functions for Robust Linear Models + +References +---------- +PJ Huber. 'Robust Statistics' John Wiley and Sons, Inc., New York, 1981. + +R Venables, B Ripley. 'Modern Applied Statistics in S' + Springer, New York, 2002. + +C Croux, PJ Rousseeuw, 'Time-efficient algorithms for two highly robust +estimators of scale' Computational statistics. Physica, Heidelberg, 1992. +""" +import numpy as np +from scipy.stats import norm as Gaussian + +from statsmodels.tools import tools +from statsmodels.tools.validation import array_like, float_like + +from . import norms +from ._qn import _qn + + +def mad(a, c=Gaussian.ppf(3 / 4.0), axis=0, center=np.median): + """ + The Median Absolute Deviation along given axis of an array + + Parameters + ---------- + a : array_like + Input array. + c : float, optional + The normalization constant. Defined as scipy.stats.norm.ppf(3/4.), + which is approximately 0.6745. + axis : int, optional + The default is 0. Can also be None. + center : callable or float + If a callable is provided, such as the default `np.median` then it + is expected to be called center(a). The axis argument will be applied + via np.apply_over_axes. Otherwise, provide a float. + + Returns + ------- + mad : float + `mad` = median(abs(`a` - center))/`c` + """ + a = array_like(a, "a", ndim=None) + c = float_like(c, "c") + if not a.size: + center_val = 0.0 + elif callable(center): + if axis is not None: + center_val = np.apply_over_axes(center, a, axis) + else: + center_val = center(a.ravel()) + else: + center_val = float_like(center, "center") + err = (np.abs(a - center_val)) / c + if not err.size: + if axis is None or err.ndim == 1: + return np.nan + else: + shape = list(err.shape) + shape.pop(axis) + return np.empty(shape) + return np.median(err, axis=axis) + + +def iqr(a, c=Gaussian.ppf(3 / 4) - Gaussian.ppf(1 / 4), axis=0): + """ + The normalized interquartile range along given axis of an array + + Parameters + ---------- + a : array_like + Input array. + c : float, optional + The normalization constant, used to get consistent estimates of the + standard deviation at the normal distribution. Defined as + scipy.stats.norm.ppf(3/4.) - scipy.stats.norm.ppf(1/4.), which is + approximately 1.349. + axis : int, optional + The default is 0. Can also be None. + + Returns + ------- + The normalized interquartile range + """ + a = array_like(a, "a", ndim=None) + c = float_like(c, "c") + + if a.ndim == 0: + raise ValueError("a should have at least one dimension") + elif a.size == 0: + return np.nan + else: + quantiles = np.quantile(a, [0.25, 0.75], axis=axis) + return np.squeeze(np.diff(quantiles, axis=0) / c) + + +def qn_scale(a, c=1 / (np.sqrt(2) * Gaussian.ppf(5 / 8)), axis=0): + """ + Computes the Qn robust estimator of scale + + The Qn scale estimator is a more efficient alternative to the MAD. + The Qn scale estimator of an array a of length n is defined as + c * {abs(a[i] - a[j]): i>> import numpy as np + >>> import statsmodels.api as sm + >>> chem_data = np.array([2.20, 2.20, 2.4, 2.4, 2.5, 2.7, 2.8, 2.9, 3.03, + ... 3.03, 3.10, 3.37, 3.4, 3.4, 3.4, 3.5, 3.6, 3.7, 3.7, 3.7, 3.7, + ... 3.77, 5.28, 28.95]) + >>> sm.robust.scale.huber(chem_data) + (array(3.2054980819923693), array(0.67365260010478967)) + """ + + def __init__(self, c=1.5, tol=1.0e-08, maxiter=30, norm=None): + self.c = c + self.maxiter = maxiter + self.tol = tol + self.norm = norm + tmp = 2 * Gaussian.cdf(c) - 1 + self.gamma = tmp + c ** 2 * (1 - tmp) - 2 * c * Gaussian.pdf(c) + + def __call__(self, a, mu=None, initscale=None, axis=0): + """ + Compute Huber's proposal 2 estimate of scale, using an optional + initial value of scale and an optional estimate of mu. If mu + is supplied, it is not reestimated. + + Parameters + ---------- + a : ndarray + 1d array + mu : float or None, optional + If the location mu is supplied then it is not reestimated. + Default is None, which means that it is estimated. + initscale : float or None, optional + A first guess on scale. If initscale is None then the standardized + median absolute deviation of a is used. + + Notes + ----- + `Huber` minimizes the function + + sum(psi((a[i]-mu)/scale)**2) + + as a function of (mu, scale), where + + psi(x) = np.clip(x, -self.c, self.c) + """ + a = np.asarray(a) + if mu is None: + n = a.shape[0] - 1 + mu = np.median(a, axis=axis) + est_mu = True + else: + n = a.shape[0] + mu = mu + est_mu = False + + if initscale is None: + scale = mad(a, axis=axis) + else: + scale = initscale + scale = tools.unsqueeze(scale, axis, a.shape) + mu = tools.unsqueeze(mu, axis, a.shape) + return self._estimate_both(a, scale, mu, axis, est_mu, n) + + def _estimate_both(self, a, scale, mu, axis, est_mu, n): + """ + Estimate scale and location simultaneously with the following + pseudo_loop: + + while not_converged: + mu, scale = estimate_location(a, scale, mu), estimate_scale(a, scale, mu) + + where estimate_location is an M-estimator and estimate_scale implements + the check used in Section 5.5 of Venables & Ripley + """ # noqa:E501 + for _ in range(self.maxiter): + # Estimate the mean along a given axis + if est_mu: + if self.norm is None: + # This is a one-step fixed-point estimator + # if self.norm == norms.HuberT + # It should be faster than using norms.HuberT + nmu = ( + np.clip( + a, mu - self.c * scale, mu + self.c * scale + ).sum(axis) + / a.shape[axis] + ) + else: + nmu = norms.estimate_location( + a, scale, self.norm, axis, mu, self.maxiter, self.tol + ) + else: + # Effectively, do nothing + nmu = mu.squeeze() + nmu = tools.unsqueeze(nmu, axis, a.shape) + + subset = np.less_equal(np.abs((a - mu) / scale), self.c) + card = subset.sum(axis) + + scale_num = np.sum(subset * (a - nmu) ** 2, axis) + scale_denom = n * self.gamma - (a.shape[axis] - card) * self.c ** 2 + nscale = np.sqrt(scale_num / scale_denom) + nscale = tools.unsqueeze(nscale, axis, a.shape) + + test1 = np.all( + np.less_equal(np.abs(scale - nscale), nscale * self.tol) + ) + test2 = np.all( + np.less_equal(np.abs(mu - nmu), nscale * self.tol) + ) + if not (test1 and test2): + mu = nmu + scale = nscale + else: + return nmu.squeeze(), nscale.squeeze() + raise ValueError( + "joint estimation of location and scale failed " + "to converge in %d iterations" % self.maxiter + ) + + +huber = Huber() + + +class HuberScale: + r""" + Huber's scaling for fitting robust linear models. + + Huber's scale is intended to be used as the scale estimate in the + IRLS algorithm and is slightly different than the `Huber` class. + + Parameters + ---------- + d : float, optional + d is the tuning constant for Huber's scale. Default is 2.5 + tol : float, optional + The convergence tolerance + maxiter : int, optiona + The maximum number of iterations. The default is 30. + + Methods + ------- + call + Return's Huber's scale computed as below + + Notes + ----- + Huber's scale is the iterative solution to + + scale_(i+1)**2 = 1/(n*h)*sum(chi(r/sigma_i)*sigma_i**2 + + where the Huber function is + + chi(x) = (x**2)/2 for \|x\| < d + chi(x) = (d**2)/2 for \|x\| >= d + + and the Huber constant h = (n-p)/n*(d**2 + (1-d**2)* + scipy.stats.norm.cdf(d) - .5 - d*sqrt(2*pi)*exp(-0.5*d**2) + """ + + def __init__(self, d=2.5, tol=1e-08, maxiter=30): + self.d = d + self.tol = tol + self.maxiter = maxiter + + def __call__(self, df_resid, nobs, resid): + h = ( + df_resid + / nobs + * ( + self.d ** 2 + + (1 - self.d ** 2) * Gaussian.cdf(self.d) + - 0.5 + - self.d / (np.sqrt(2 * np.pi)) * np.exp(-0.5 * self.d ** 2) + ) + ) + s = mad(resid) + + def subset(x): + return np.less(np.abs(resid / x), self.d) + + def chi(s): + return subset(s) * (resid / s) ** 2 / 2 + (1 - subset(s)) * ( + self.d ** 2 / 2 + ) + + scalehist = [np.inf, s] + niter = 1 + while ( + np.abs(scalehist[niter - 1] - scalehist[niter]) > self.tol + and niter < self.maxiter + ): + nscale = np.sqrt( + 1 + / (nobs * h) + * np.sum(chi(scalehist[-1])) + * scalehist[-1] ** 2 + ) + scalehist.append(nscale) + niter += 1 + # TODO: raise on convergence failure? + return scalehist[-1] + + +hubers_scale = HuberScale() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/sandbox/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/sandbox/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..91bf289559ad410ec2e15bb69ee2b0d6cbb51fea --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/sandbox/__init__.py @@ -0,0 +1,6 @@ +'''This is sandbox code + +''' +from statsmodels.tools._test_runner import PytestTester + +test = PytestTester() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/sandbox/bspline.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/sandbox/bspline.py new file mode 100644 index 0000000000000000000000000000000000000000..a48785db305e2d3b3b4fa910eaa127b88015fa48 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/sandbox/bspline.py @@ -0,0 +1,663 @@ +''' +Bspines and smoothing splines. + +General references: + + Craven, P. and Wahba, G. (1978) "Smoothing noisy data with spline functions. + Estimating the correct degree of smoothing by + the method of generalized cross-validation." + Numerische Mathematik, 31(4), 377-403. + + Hastie, Tibshirani and Friedman (2001). "The Elements of Statistical + Learning." Springer-Verlag. 536 pages. + + Hutchison, M. and Hoog, F. "Smoothing noisy data with spline functions." + Numerische Mathematik, 47(1), 99-106. +''' + +import numpy as np +import numpy.linalg as L + +from scipy.linalg import solveh_banded +from scipy.optimize import golden +from models import _hbspline #removed because this was segfaulting + +# Issue warning regarding heavy development status of this module +import warnings +_msg = """ +The bspline code is technology preview and requires significant work +on the public API and documentation. The API will likely change in the future +""" +warnings.warn(_msg, FutureWarning) + + +def _band2array(a, lower=0, symmetric=False, hermitian=False): + """ + Take an upper or lower triangular banded matrix and return a + numpy array. + + INPUTS: + a -- a matrix in upper or lower triangular banded matrix + lower -- is the matrix upper or lower triangular? + symmetric -- if True, return the original result plus its transpose + hermitian -- if True (and symmetric False), return the original + result plus its conjugate transposed + """ + + n = a.shape[1] + r = a.shape[0] + _a = 0 + + if not lower: + for j in range(r): + _b = np.diag(a[r-1-j],k=j)[j:(n+j),j:(n+j)] + _a += _b + if symmetric and j > 0: + _a += _b.T + elif hermitian and j > 0: + _a += _b.conjugate().T + else: + for j in range(r): + _b = np.diag(a[j],k=j)[0:n,0:n] + _a += _b + if symmetric and j > 0: + _a += _b.T + elif hermitian and j > 0: + _a += _b.conjugate().T + _a = _a.T + + return _a + + +def _upper2lower(ub): + """ + Convert upper triangular banded matrix to lower banded form. + + INPUTS: + ub -- an upper triangular banded matrix + + OUTPUTS: lb + lb -- a lower triangular banded matrix with same entries + as ub + """ + + lb = np.zeros(ub.shape, ub.dtype) + nrow, ncol = ub.shape + for i in range(ub.shape[0]): + lb[i,0:(ncol-i)] = ub[nrow-1-i,i:ncol] + lb[i,(ncol-i):] = ub[nrow-1-i,0:i] + return lb + +def _lower2upper(lb): + """ + Convert lower triangular banded matrix to upper banded form. + + INPUTS: + lb -- a lower triangular banded matrix + + OUTPUTS: ub + ub -- an upper triangular banded matrix with same entries + as lb + """ + + ub = np.zeros(lb.shape, lb.dtype) + nrow, ncol = lb.shape + for i in range(lb.shape[0]): + ub[nrow-1-i,i:ncol] = lb[i,0:(ncol-i)] + ub[nrow-1-i,0:i] = lb[i,(ncol-i):] + return ub + +def _triangle2unit(tb, lower=0): + """ + Take a banded triangular matrix and return its diagonal and the + unit matrix: the banded triangular matrix with 1's on the diagonal, + i.e. each row is divided by the corresponding entry on the diagonal. + + INPUTS: + tb -- a lower triangular banded matrix + lower -- if True, then tb is assumed to be lower triangular banded, + in which case return value is also lower triangular banded. + + OUTPUTS: d, b + d -- diagonal entries of tb + b -- unit matrix: if lower is False, b is upper triangular + banded and its rows of have been divided by d, + else lower is True, b is lower triangular banded + and its columns have been divieed by d. + """ + + if lower: + d = tb[0].copy() + else: + d = tb[-1].copy() + + if lower: + return d, (tb / d) + else: + lnum = _upper2lower(tb) + return d, _lower2upper(lnum / d) + + +def _trace_symbanded(a, b, lower=0): + """ + Compute the trace(ab) for two upper or banded real symmetric matrices + stored either in either upper or lower form. + + INPUTS: + a, b -- two banded real symmetric matrices (either lower or upper) + lower -- if True, a and b are assumed to be the lower half + + + OUTPUTS: trace + trace -- trace(ab) + """ + + if lower: + t = _zero_triband(a * b, lower=1) + return t[0].sum() + 2 * t[1:].sum() + else: + t = _zero_triband(a * b, lower=0) + return t[-1].sum() + 2 * t[:-1].sum() + + +def _zero_triband(a, lower=0): + """ + Explicitly zero out unused elements of a real symmetric banded matrix. + + INPUTS: + a -- a real symmetric banded matrix (either upper or lower hald) + lower -- if True, a is assumed to be the lower half + """ + + nrow, ncol = a.shape + if lower: + for i in range(nrow): + a[i, (ncol-i):] = 0. + else: + for i in range(nrow): + a[i, 0:i] = 0. + return a + + +class BSpline: + + ''' + + Bsplines of a given order and specified knots. + + Implementation is based on description in Chapter 5 of + + Hastie, Tibshirani and Friedman (2001). "The Elements of Statistical + Learning." Springer-Verlag. 536 pages. + + + INPUTS: + knots -- a sorted array of knots with knots[0] the lower boundary, + knots[1] the upper boundary and knots[1:-1] the internal + knots. + order -- order of the Bspline, default is 4 which yields cubic + splines + M -- number of additional boundary knots, if None it defaults + to order + coef -- an optional array of real-valued coefficients for the Bspline + of shape (knots.shape + 2 * (M - 1) - order,). + x -- an optional set of x values at which to evaluate the + Bspline to avoid extra evaluation in the __call__ method + + ''' + # FIXME: update parameter names, replace single character names + # FIXME: `order` should be actual spline order (implemented as order+1) + ## FIXME: update the use of spline order in extension code (evaluate is recursively called) + # FIXME: eliminate duplicate M and m attributes (m is order, M is related to tau size) + + def __init__(self, knots, order=4, M=None, coef=None, x=None): + + knots = np.squeeze(np.unique(np.asarray(knots))) + + if knots.ndim != 1: + raise ValueError('expecting 1d array for knots') + + self.m = order + if M is None: + M = self.m + self.M = M + + self.tau = np.hstack([[knots[0]]*(self.M-1), knots, [knots[-1]]*(self.M-1)]) + + self.K = knots.shape[0] - 2 + if coef is None: + self.coef = np.zeros((self.K + 2 * self.M - self.m), np.float64) + else: + self.coef = np.squeeze(coef) + if self.coef.shape != (self.K + 2 * self.M - self.m): + raise ValueError('coefficients of Bspline have incorrect shape') + if x is not None: + self.x = x + + def _setx(self, x): + self._x = x + self._basisx = self.basis(self._x) + + def _getx(self): + return self._x + + x = property(_getx, _setx) + + def __call__(self, *args): + """ + Evaluate the BSpline at a given point, yielding + a matrix B and return + + B * self.coef + + + INPUTS: + args -- optional arguments. If None, it returns self._basisx, + the BSpline evaluated at the x values passed in __init__. + Otherwise, return the BSpline evaluated at the + first argument args[0]. + + OUTPUTS: y + y -- value of Bspline at specified x values + + BUGS: + If self has no attribute x, an exception will be raised + because self has no attribute _basisx. + """ + + if not args: + b = self._basisx.T + else: + x = args[0] + b = np.asarray(self.basis(x)).T + return np.squeeze(np.dot(b, self.coef)) + + def basis_element(self, x, i, d=0): + """ + Evaluate a particular basis element of the BSpline, + or its derivative. + + INPUTS: + x -- x values at which to evaluate the basis element + i -- which element of the BSpline to return + d -- the order of derivative + + OUTPUTS: y + y -- value of d-th derivative of the i-th basis element + of the BSpline at specified x values + """ + + x = np.asarray(x, np.float64) + _shape = x.shape + if _shape == (): + x.shape = (1,) + x.shape = (np.product(_shape,axis=0),) + if i < self.tau.shape[0] - 1: + # TODO: OWNDATA flags... + v = _hbspline.evaluate(x, self.tau, self.m, d, i, i+1) + else: + return np.zeros(x.shape, np.float64) + + if (i == self.tau.shape[0] - self.m): + v = np.where(np.equal(x, self.tau[-1]), 1, v) + v.shape = _shape + return v + + def basis(self, x, d=0, lower=None, upper=None): + """ + Evaluate the basis of the BSpline or its derivative. + If lower or upper is specified, then only + the [lower:upper] elements of the basis are returned. + + INPUTS: + x -- x values at which to evaluate the basis element + i -- which element of the BSpline to return + d -- the order of derivative + lower -- optional lower limit of the set of basis + elements + upper -- optional upper limit of the set of basis + elements + + OUTPUTS: y + y -- value of d-th derivative of the basis elements + of the BSpline at specified x values + """ + x = np.asarray(x) + _shape = x.shape + if _shape == (): + x.shape = (1,) + x.shape = (np.product(_shape,axis=0),) + + if upper is None: + upper = self.tau.shape[0] - self.m + if lower is None: + lower = 0 + upper = min(upper, self.tau.shape[0] - self.m) + lower = max(0, lower) + + d = np.asarray(d) + if d.shape == (): + v = _hbspline.evaluate(x, self.tau, self.m, int(d), lower, upper) + else: + if d.shape[0] != 2: + raise ValueError("if d is not an integer, expecting a jx2 \ + array with first row indicating order \ + of derivative, second row coefficient in front.") + v = 0 + for i in range(d.shape[1]): + v += d[1,i] * _hbspline.evaluate(x, self.tau, self.m, d[0,i], lower, upper) + + v.shape = (upper-lower,) + _shape + if upper == self.tau.shape[0] - self.m: + v[-1] = np.where(np.equal(x, self.tau[-1]), 1, v[-1]) + return v + + def gram(self, d=0): + """ + Compute Gram inner product matrix, storing it in lower + triangular banded form. + + The (i,j) entry is + + G_ij = integral b_i^(d) b_j^(d) + + where b_i are the basis elements of the BSpline and (d) is the + d-th derivative. + + If d is a matrix then, it is assumed to specify a differential + operator as follows: the first row represents the order of derivative + with the second row the coefficient corresponding to that order. + + For instance: + + [[2, 3], + [3, 1]] + + represents 3 * f^(2) + 1 * f^(3). + + INPUTS: + d -- which derivative to apply to each basis element, + if d is a matrix, it is assumed to specify + a differential operator as above + + OUTPUTS: gram + gram -- the matrix of inner products of (derivatives) + of the BSpline elements + """ + + d = np.squeeze(d) + if np.asarray(d).shape == (): + self.g = _hbspline.gram(self.tau, self.m, int(d), int(d)) + else: + d = np.asarray(d) + if d.shape[0] != 2: + raise ValueError("if d is not an integer, expecting a jx2 \ + array with first row indicating order \ + of derivative, second row coefficient in front.") + if d.shape == (2,): + d.shape = (2,1) + self.g = 0 + for i in range(d.shape[1]): + for j in range(d.shape[1]): + self.g += d[1,i]* d[1,j] * _hbspline.gram(self.tau, self.m, int(d[0,i]), int(d[0,j])) + self.g = self.g.T + self.d = d + return np.nan_to_num(self.g) + +class SmoothingSpline(BSpline): + + penmax = 30. + method = "target_df" + target_df = 5 + default_pen = 1.0e-03 + optimize = True + + ''' + A smoothing spline, which can be used to smooth scatterplots, i.e. + a list of (x,y) tuples. + + See fit method for more information. + + ''' + + def fit(self, y, x=None, weights=None, pen=0.): + """ + Fit the smoothing spline to a set of (x,y) pairs. + + INPUTS: + y -- response variable + x -- if None, uses self.x + weights -- optional array of weights + pen -- constant in front of Gram matrix + + OUTPUTS: None + The smoothing spline is determined by self.coef, + subsequent calls of __call__ will be the smoothing spline. + + ALGORITHM: + Formally, this solves a minimization: + + fhat = ARGMIN_f SUM_i=1^n (y_i-f(x_i))^2 + pen * int f^(2)^2 + + int is integral. pen is lambda (from Hastie) + + See Chapter 5 of + + Hastie, Tibshirani and Friedman (2001). "The Elements of Statistical + Learning." Springer-Verlag. 536 pages. + + for more details. + + TODO: + Should add arbitrary derivative penalty instead of just + second derivative. + """ + + banded = True + + if x is None: + x = self._x + bt = self._basisx.copy() + else: + bt = self.basis(x) + + if pen == 0.: # cannot use cholesky for singular matrices + banded = False + + if x.shape != y.shape: + raise ValueError('x and y shape do not agree, by default x are \ + the Bspline\'s internal knots') + + if pen >= self.penmax: + pen = self.penmax + + + if weights is not None: + self.weights = weights + else: + self.weights = 1. + + _w = np.sqrt(self.weights) + bt *= _w + + # throw out rows with zeros (this happens at boundary points!) + + mask = np.flatnonzero(1 - np.all(np.equal(bt, 0), axis=0)) + + bt = bt[:,mask] + y = y[mask] + + self.df_total = y.shape[0] + + bty = np.squeeze(np.dot(bt, _w * y)) + self.N = y.shape[0] + + if not banded: + self.btb = np.dot(bt, bt.T) + _g = _band2array(self.g, lower=1, symmetric=True) + self.coef, _, self.rank = L.lstsq(self.btb + pen*_g, bty)[0:3] + self.rank = min(self.rank, self.btb.shape[0]) + del _g + else: + self.btb = np.zeros(self.g.shape, np.float64) + nband, nbasis = self.g.shape + for i in range(nbasis): + for k in range(min(nband, nbasis-i)): + self.btb[k,i] = (bt[i] * bt[i+k]).sum() + + bty.shape = (1,bty.shape[0]) + self.pen = pen + self.chol, self.coef = solveh_banded(self.btb + + pen*self.g, + bty, lower=1) + + self.coef = np.squeeze(self.coef) + self.resid = y * self.weights - np.dot(self.coef, bt) + self.pen = pen + + del bty + del mask + del bt + + def smooth(self, y, x=None, weights=None): + + if self.method == "target_df": + if hasattr(self, 'pen'): + self.fit(y, x=x, weights=weights, pen=self.pen) + else: + self.fit_target_df(y, x=x, weights=weights, df=self.target_df) + elif self.method == "optimize_gcv": + self.fit_optimize_gcv(y, x=x, weights=weights) + + + def gcv(self): + """ + Generalized cross-validation score of current fit. + + Craven, P. and Wahba, G. "Smoothing noisy data with spline functions. + Estimating the correct degree of smoothing by + the method of generalized cross-validation." + Numerische Mathematik, 31(4), 377-403. + """ + + norm_resid = (self.resid**2).sum() + return norm_resid / (self.df_total - self.trace()) + + def df_resid(self): + """ + Residual degrees of freedom in the fit. + + self.N - self.trace() + + where self.N is the number of observations of last fit. + """ + + return self.N - self.trace() + + def df_fit(self): + """ + How many degrees of freedom used in the fit? + + self.trace() + """ + return self.trace() + + def trace(self): + """ + Trace of the smoothing matrix S(pen) + + TODO: addin a reference to Wahba, and whoever else I used. + """ + + if self.pen > 0: + _invband = _hbspline.invband(self.chol.copy()) + tr = _trace_symbanded(_invband, self.btb, lower=1) + return tr + else: + return self.rank + + def fit_target_df(self, y, x=None, df=None, weights=None, tol=1.0e-03, + apen=0, bpen=1.0e-03): + """ + Fit smoothing spline with approximately df degrees of freedom + used in the fit, i.e. so that self.trace() is approximately df. + + Uses binary search strategy. + + In general, df must be greater than the dimension of the null space + of the Gram inner product. For cubic smoothing splines, this means + that df > 2. + + INPUTS: + y -- response variable + x -- if None, uses self.x + df -- target degrees of freedom + weights -- optional array of weights + tol -- (relative) tolerance for convergence + apen -- lower bound of penalty for binary search + bpen -- upper bound of penalty for binary search + + OUTPUTS: None + The smoothing spline is determined by self.coef, + subsequent calls of __call__ will be the smoothing spline. + """ + + df = df or self.target_df + + olddf = y.shape[0] - self.m + + if hasattr(self, "pen"): + self.fit(y, x=x, weights=weights, pen=self.pen) + curdf = self.trace() + if np.fabs(curdf - df) / df < tol: + return + if curdf > df: + apen, bpen = self.pen, 2 * self.pen + else: + apen, bpen = 0., self.pen + + while True: + + curpen = 0.5 * (apen + bpen) + self.fit(y, x=x, weights=weights, pen=curpen) + curdf = self.trace() + if curdf > df: + apen, bpen = curpen, 2 * curpen + else: + apen, bpen = apen, curpen + if apen >= self.penmax: + raise ValueError("penalty too large, try setting penmax \ + higher or decreasing df") + if np.fabs(curdf - df) / df < tol: + break + + def fit_optimize_gcv(self, y, x=None, weights=None, tol=1.0e-03, + brack=(-100,20)): + """ + Fit smoothing spline trying to optimize GCV. + + Try to find a bracketing interval for scipy.optimize.golden + based on bracket. + + It is probably best to use target_df instead, as it is + sometimes difficult to find a bracketing interval. + + INPUTS: + y -- response variable + x -- if None, uses self.x + df -- target degrees of freedom + weights -- optional array of weights + tol -- (relative) tolerance for convergence + brack -- an initial guess at the bracketing interval + + OUTPUTS: None + The smoothing spline is determined by self.coef, + subsequent calls of __call__ will be the smoothing spline. + """ + + def _gcv(pen, y, x): + self.fit(y, x=x, pen=np.exp(pen)) + a = self.gcv() + return a + + a = golden(_gcv, args=(y,x), brack=brack, tol=tol) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/sandbox/descstats.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/sandbox/descstats.py new file mode 100644 index 0000000000000000000000000000000000000000..8c7de1f4cc8812afaff7f10523e72ce639a922fd --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/sandbox/descstats.py @@ -0,0 +1,183 @@ +''' +Glue for returning descriptive statistics. +''' +import os + +import numpy as np +from scipy import stats + +from statsmodels.stats.descriptivestats import sign_test + +############################################# +# +#============================================ +# Univariate Descriptive Statistics +#============================================ +# + +def descstats(data, cols=None, axis=0): + ''' + Prints descriptive statistics for one or multiple variables. + + Parameters + ---------- + data: numpy array + `x` is the data + + v: list, optional + A list of the column number of variables. + Default is all columns. + + axis: 1 or 0 + axis order of data. Default is 0 for column-ordered data. + + Examples + -------- + >>> descstats(data.exog,v=['x_1','x_2','x_3']) + ''' + + x = np.array(data) # or rather, the data we're interested in + if cols is None: + x = x[:, None] + if cols is None and x.ndim == 1: + x = x[:,None] + + if x.shape[1] == 1: + desc = ''' + --------------------------------------------- + Univariate Descriptive Statistics + --------------------------------------------- + + Var. Name %(name)12s + ---------- + Obs. %(nobs)22i Range %(range)22s + Sum of Wts. %(sum)22s Coeff. of Variation %(coeffvar)22.4g + Mode %(mode)22.4g Skewness %(skewness)22.4g + Repeats %(nmode)22i Kurtosis %(kurtosis)22.4g + Mean %(mean)22.4g Uncorrected SS %(uss)22.4g + Median %(median)22.4g Corrected SS %(ss)22.4g + Variance %(variance)22.4g Sum Observations %(sobs)22.4g + Std. Dev. %(stddev)22.4g + ''' % {'name': cols, 'sum': 'N/A', 'nobs': len(x), 'mode': \ + stats.mode(x)[0][0], 'nmode': stats.mode(x)[1][0], \ + 'mean': x.mean(), 'median': np.median(x), 'range': \ + '('+str(x.min())+', '+str(x.max())+')', 'variance': \ + x.var(), 'stddev': x.std(), 'coeffvar': \ + stats.variation(x), 'skewness': stats.skew(x), \ + 'kurtosis': stats.kurtosis(x), 'uss': np.sum(x**2, axis=0),\ + 'ss': np.sum((x-x.mean())**2, axis=0), 'sobs': np.sum(x)} + + desc+= ''' + + Percentiles + ------------- + 1 %% %12.4g + 5 %% %12.4g + 10 %% %12.4g + 25 %% %12.4g + + 50 %% %12.4g + + 75 %% %12.4g + 90 %% %12.4g + 95 %% %12.4g + 99 %% %12.4g + ''' % tuple([stats.scoreatpercentile(x,per) for per in (1,5,10,25, + 50,75,90,95,99)]) + t,p_t=stats.ttest_1samp(x,0) + M,p_M=sign_test(x) + S,p_S=stats.wilcoxon(np.squeeze(x)) + + desc+= ''' + + Tests of Location (H0: Mu0=0) + ----------------------------- + Test Statistic Two-tailed probability + -----------------+----------------------------------------- + Student's t | t {:7.5f} Pr > |t| <{:.4f} + Sign | M {:8.2f} Pr >= |M| <{:.4f} + Signed Rank | S {:8.2f} Pr >= |S| <{:.4f} + + '''.format(t,p_t,M,p_M,S,p_S) +# Should this be part of a 'descstats' +# in any event these should be split up, so that they can be called +# individually and only returned together if someone calls summary +# or something of the sort + + elif x.shape[1] > 1: + desc =''' + Var. Name | Obs. Mean Std. Dev. Range + ------------+--------------------------------------------------------'''+\ + os.linesep + + for var in range(x.shape[1]): + xv = x[:, var] + kwargs = { + 'name': var, + 'obs': len(xv), + 'mean': xv.mean(), + 'stddev': xv.std(), + 'range': '('+str(xv.min())+', '+str(xv.max())+')'+os.linesep + } + desc += ("%(name)15s %(obs)9i %(mean)12.4g %(stddev)12.4g " + "%(range)20s" % kwargs) + else: + raise ValueError("data not understood") + + return desc + +#if __name__=='__main__': +# test descstats +# import os +# loc='http://eagle1.american.edu/~js2796a/data/handguns_data.csv' +# relpath=(load_dataset(loc)) +# dta=np.recfromcsv(relpath) +# descstats(dta,['stpop']) +# raw_input('Hit enter for multivariate test') +# descstats(dta,['stpop','avginc','vio']) + +# with plain arrays +# import string2dummy as s2d +# dts=s2d.string2dummy(dta) +# ndts=np.vstack(dts[col] for col in dts.dtype.names) +# observations in columns and data in rows +# is easier for the call to stats + +# what to make of +# ndts=np.column_stack(dts[col] for col in dts.dtype.names) +# ntda=ntds.swapaxis(1,0) +# ntda is ntds returns false? + +# or now we just have detailed information about the different strings +# would this approach ever be inappropriate for a string typed variable +# other than dates? +# descstats(ndts, [1]) +# raw_input("Enter to try second part") +# descstats(ndts, [1,20,3]) + +if __name__ == '__main__': + import statsmodels.api as sm + data = sm.datasets.longley.load() + data.exog = sm.add_constant(data.exog, prepend=False) + sum1 = descstats(data.exog) + sum1a = descstats(data.exog[:,:1]) + +# loc='http://eagle1.american.edu/~js2796a/data/handguns_data.csv' +# dta=np.recfromcsv(loc) +# summary2 = descstats(dta,['stpop']) +# summary3 = descstats(dta,['stpop','avginc','vio']) +#TODO: needs a by argument +# summary4 = descstats(dta) this fails +# this is a bug +# p = dta[['stpop']] +# p.view(dtype = np.float, type = np.ndarray) +# this works +# p.view(dtype = np.int, type = np.ndarray) + +### This is *really* slow ### + if os.path.isfile('./Econ724_PS_I_Data.csv'): + data2 = np.recfromcsv('./Econ724_PS_I_Data.csv') + sum2 = descstats(data2.ahe) + sum3 = descstats(np.column_stack((data2.ahe,data2.yrseduc))) + sum4 = descstats(np.column_stack([data2[_] for \ + _ in data2.dtype.names])) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/sandbox/gam.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/sandbox/gam.py new file mode 100644 index 0000000000000000000000000000000000000000..d51281226c24e04579bf6ef603ac2a3cd5fa20b5 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/sandbox/gam.py @@ -0,0 +1,433 @@ +""" +Generalized additive models + + + +Requirements for smoothers +-------------------------- + +smooth(y, weights=xxx) : ? no return ? alias for fit +predict(x=None) : smoothed values, fittedvalues or for new exog +df_fit() : degress of freedom of fit ? + + +Notes +----- +- using PolySmoother works for AdditiveModel, and GAM with Poisson and Binomial +- testfailure with Gamma, no other families tested +- there is still an indeterminacy in the split up of the constant across + components (smoothers) and alpha, sum, i.e. constant, looks good. + - role of offset, that I have not tried to figure out yet + +Refactoring +----------- +currently result is attached to model instead of other way around +split up Result in class for AdditiveModel and for GAM, +subclass GLMResults, needs verification that result statistics are appropriate +how much inheritance, double inheritance? +renamings and cleanup +interface to other smoothers, scipy splines + +basic unittests as support for refactoring exist, but we should have a test +case for gamma and the others. Advantage of PolySmoother is that we can +benchmark against the parametric GLM results. + +""" + +# JP: +# changes: use PolySmoother instead of crashing bspline +# TODO: check/catalogue required interface of a smoother +# TODO: replace default smoother by corresponding function to initialize +# other smoothers +# TODO: fix iteration, do not define class with iterator methods, use looping; +# add maximum iteration and other optional stop criteria +# fixed some of the dimension problems in PolySmoother, +# now graph for example looks good +# NOTE: example script is now in examples folder +#update: I did some of the above, see module docstring + +import numpy as np + +from statsmodels.genmod import families +from statsmodels.sandbox.nonparametric.smoothers import PolySmoother +from statsmodels.genmod.generalized_linear_model import GLM +from statsmodels.tools.sm_exceptions import IterationLimitWarning, iteration_limit_doc + +import warnings + +DEBUG = False + +def default_smoother(x, s_arg=None): + ''' + + ''' +# _x = x.copy() +# _x.sort() + _x = np.sort(x) + n = x.shape[0] + # taken form smooth.spline in R + + #if n < 50: + if n < 500: + nknots = n + else: + a1 = np.log(50) / np.log(2) + a2 = np.log(100) / np.log(2) + a3 = np.log(140) / np.log(2) + a4 = np.log(200) / np.log(2) + if n < 200: + nknots = 2**(a1 + (a2 - a1) * (n - 50)/150.) + elif n < 800: + nknots = 2**(a2 + (a3 - a2) * (n - 200)/600.) + elif n < 3200: + nknots = 2**(a3 + (a4 - a3) * (n - 800)/2400.) + else: + nknots = 200 + (n - 3200.)**0.2 + knots = _x[np.linspace(0, n-1, nknots).astype(np.int32)] + + #s = SmoothingSpline(knots, x=x.copy()) + #when I set order=2, I get nans in the GAM prediction + if s_arg is None: + order = 3 #what about knots? need smoother *args or **kwds + else: + order = s_arg + s = PolySmoother(order, x=x.copy()) #TODO: change order, why copy? +# s.gram(d=2) +# s.target_df = 5 + return s + +class Offset: + + def __init__(self, fn, offset): + self.fn = fn + self.offset = offset + + def __call__(self, *args, **kw): + return self.fn(*args, **kw) + self.offset + +class Results: + + def __init__(self, Y, alpha, exog, smoothers, family, offset): + self.nobs, self.k_vars = exog.shape #assumes exog is 2d + #weird: If I put the previous line after the definition of self.mu, + # then the attributed do not get added + self.Y = Y + self.alpha = alpha + self.smoothers = smoothers + self.offset = offset + self.family = family + self.exog = exog + self.offset = offset + self.mu = self.linkinversepredict(exog) #TODO: remove __call__ + + + + def __call__(self, exog): + '''expected value ? check new GLM, same as mu for given exog + maybe remove this + ''' + return self.linkinversepredict(exog) + + def linkinversepredict(self, exog): #TODO what's the name in GLM + '''expected value ? check new GLM, same as mu for given exog + ''' + return self.family.link.inverse(self.predict(exog)) + + def predict(self, exog): + '''predict response, sum of smoothed components + TODO: What's this in the case of GLM, corresponds to X*beta ? + ''' + #note: sum is here over axis=0, + #TODO: transpose in smoothed and sum over axis=1 + + #BUG: there is some inconsistent orientation somewhere + #temporary hack, will not work for 1d + #print dir(self) + #print 'self.nobs, self.k_vars', self.nobs, self.k_vars + exog_smoothed = self.smoothed(exog) + #print 'exog_smoothed.shape', exog_smoothed.shape + if exog_smoothed.shape[0] == self.k_vars: + import warnings + warnings.warn("old orientation, colvars, will go away", + FutureWarning) + return np.sum(self.smoothed(exog), axis=0) + self.alpha + if exog_smoothed.shape[1] == self.k_vars: + return np.sum(exog_smoothed, axis=1) + self.alpha + else: + raise ValueError('shape mismatch in predict') + + def smoothed(self, exog): + '''get smoothed prediction for each component + + ''' + #bug: with exog in predict I get a shape error + #print 'smoothed', exog.shape, self.smoothers[0].predict(exog).shape + #there was a mistake exog did not have column index i + return np.array([self.smoothers[i].predict(exog[:,i]) + self.offset[i] + #should not be a mistake because exog[:,i] is attached to smoother, but + #it is for different exog + #return np.array([self.smoothers[i].predict() + self.offset[i] + for i in range(exog.shape[1])]).T + + def smoothed_demeaned(self, exog): + components = self.smoothed(exog) + means = components.mean(0) + constant = means.sum() + self.alpha + components_demeaned = components - means + return components_demeaned, constant + +class AdditiveModel: + '''additive model with non-parametric, smoothed components + + Parameters + ---------- + exog : ndarray + smoothers : None or list of smoother instances + smoother instances not yet checked + weights : None or ndarray + family : None or family instance + I think only used because of shared results with GAM and subclassing. + If None, then Gaussian is used. + ''' + + def __init__(self, exog, smoothers=None, weights=None, family=None): + self.exog = exog + if weights is not None: + self.weights = weights + else: + self.weights = np.ones(self.exog.shape[0]) + + self.smoothers = smoothers or [default_smoother(exog[:,i]) for i in range(exog.shape[1])] + + #TODO: why do we set here df, refactoring temporary? + for i in range(exog.shape[1]): + self.smoothers[i].df = 10 + + if family is None: + self.family = families.Gaussian() + else: + self.family = family + #self.family = families.Gaussian() + + def _iter__(self): + '''initialize iteration ?, should be removed + + ''' + self.iter = 0 + self.dev = np.inf + return self + + def next(self): + '''internal calculation for one fit iteration + + BUG: I think this does not improve, what is supposed to improve + offset does not seem to be used, neither an old alpha + The smoothers keep coef/params from previous iteration + ''' + _results = self.results + Y = self.results.Y + mu = _results.predict(self.exog) + #TODO offset is never used ? + offset = np.zeros(self.exog.shape[1], np.float64) + alpha = (Y * self.weights).sum() / self.weights.sum() + for i in range(self.exog.shape[1]): + tmp = self.smoothers[i].predict() + #TODO: check what smooth needs to do + #smooth (alias for fit, fit given x to new y and attach + #print 'next shape', (Y - alpha - mu + tmp).shape + bad = np.isnan(Y - alpha - mu + tmp).any() + if bad: #temporary assert while debugging + print(Y, alpha, mu, tmp) + raise ValueError("nan encountered") + #self.smoothers[i].smooth(Y - alpha - mu + tmp, + self.smoothers[i].smooth(Y - mu + tmp, + weights=self.weights) + tmp2 = self.smoothers[i].predict() #fittedvalues of previous smooth/fit + self.results.offset[i] = -(tmp2*self.weights).sum() / self.weights.sum() + #self.offset used in smoothed + if DEBUG: + print(self.smoothers[i].params) + mu += tmp2 - tmp + #change setting offset here: tests still pass, offset equal to constant + #in component ??? what's the effect of offset + offset = self.results.offset + #print self.iter + #self.iter += 1 #missing incrementing of iter counter NOT + return Results(Y, alpha, self.exog, self.smoothers, self.family, offset) + + def cont(self): + '''condition to continue iteration loop + + Parameters + ---------- + tol + + Returns + ------- + cont : bool + If true, then iteration should be continued. + + ''' + self.iter += 1 #moved here to always count, not necessary + if DEBUG: + print(self.iter, self.results.Y.shape) + print(self.results.predict(self.exog).shape, self.weights.shape) + curdev = (((self.results.Y - self.results.predict(self.exog))**2) * self.weights).sum() + + if self.iter > self.maxiter: #kill it, no max iterationoption + return False + if np.fabs((self.dev - curdev) / curdev) < self.rtol: + self.dev = curdev + return False + + #self.iter += 1 + self.dev = curdev + return True + + def df_resid(self): + '''degrees of freedom of residuals, ddof is sum of all smoothers df + ''' + return self.results.Y.shape[0] - np.array([self.smoothers[i].df_fit() for i in range(self.exog.shape[1])]).sum() + + def estimate_scale(self): + '''estimate standard deviation of residuals + ''' + #TODO: remove use of self.results.__call__ + return ((self.results.Y - self.results(self.exog))**2).sum() / self.df_resid() + + def fit(self, Y, rtol=1.0e-06, maxiter=30): + '''fit the model to a given endogenous variable Y + + This needs to change for consistency with statsmodels + + ''' + self.rtol = rtol + self.maxiter = maxiter + #iter(self) # what does this do? anything? + self._iter__() + mu = 0 + alpha = (Y * self.weights).sum() / self.weights.sum() + + offset = np.zeros(self.exog.shape[1], np.float64) + + for i in range(self.exog.shape[1]): + self.smoothers[i].smooth(Y - alpha - mu, + weights=self.weights) + tmp = self.smoothers[i].predict() + offset[i] = (tmp * self.weights).sum() / self.weights.sum() + tmp -= tmp.sum() + mu += tmp + + self.results = Results(Y, alpha, self.exog, self.smoothers, self.family, offset) + + while self.cont(): + self.results = self.next() + + if self.iter >= self.maxiter: + warnings.warn(iteration_limit_doc, IterationLimitWarning) + + return self.results + +class Model(GLM, AdditiveModel): +#class Model(AdditiveModel): + #TODO: what does GLM do? Is it actually used ? + #only used in __init__, dropping it does not change results + #but where gets family attached now? - weird, it's Gaussian in this case now + #also where is the link defined? + #AdditiveModel overwrites family and sets it to Gaussian - corrected + + #I think both GLM and AdditiveModel subclassing is only used in __init__ + + #niter = 2 + +# def __init__(self, exog, smoothers=None, family=family.Gaussian()): +# GLM.__init__(self, exog, family=family) +# AdditiveModel.__init__(self, exog, smoothers=smoothers) +# self.family = family + def __init__(self, endog, exog, smoothers=None, family=families.Gaussian()): + #self.family = family + #TODO: inconsistent super __init__ + AdditiveModel.__init__(self, exog, smoothers=smoothers, family=family) + GLM.__init__(self, endog, exog, family=family) + assert self.family is family #make sure we got the right family + + def next(self): + _results = self.results + Y = _results.Y + if np.isnan(self.weights).all(): + print("nanweights1") + + _results.mu = self.family.link.inverse(_results.predict(self.exog)) + #eta = _results.predict(self.exog) + #_results.mu = self.family.fitted(eta) + weights = self.family.weights(_results.mu) + if np.isnan(weights).all(): + self.weights = weights + print("nanweights2") + self.weights = weights + if DEBUG: + print('deriv isnan', np.isnan(self.family.link.deriv(_results.mu)).any()) + + #Z = _results.predict(self.exog) + \ + Z = _results.predict(self.exog) + \ + self.family.link.deriv(_results.mu) * (Y - _results.mu) #- _results.alpha #?added alpha + + m = AdditiveModel(self.exog, smoothers=self.smoothers, + weights=self.weights, family=self.family) + + #TODO: I do not know what the next two lines do, Z, Y ? which is endog? + #Y is original endog, Z is endog for the next step in the iterative solver + + _results = m.fit(Z) + self.history.append([Z, _results.predict(self.exog)]) + _results.Y = Y + _results.mu = self.family.link.inverse(_results.predict(self.exog)) + self.iter += 1 + self.results = _results + + return _results + + def estimate_scale(self, Y=None): + """ + Return Pearson\'s X^2 estimate of scale. + """ + + if Y is None: + Y = self.Y + resid = Y - self.results.mu + return (np.power(resid, 2) / self.family.variance(self.results.mu)).sum() \ + / self.df_resid #TODO check this + #/ AdditiveModel.df_resid(self) #what is the class doing here? + + + def fit(self, Y, rtol=1.0e-06, maxiter=30): + + self.rtol = rtol + self.maxiter = maxiter + + self.Y = np.asarray(Y, np.float64) + + self.history = [] + + #iter(self) + self._iter__() + + #TODO code duplication with next? + alpha = self.Y.mean() + mu0 = self.family.starting_mu(Y) + #Z = self.family.link(alpha) + self.family.link.deriv(alpha) * (Y - alpha) + Z = self.family.link(alpha) + self.family.link.deriv(alpha) * (Y - mu0) + m = AdditiveModel(self.exog, smoothers=self.smoothers, family=self.family) + self.results = m.fit(Z) + self.results.mu = self.family.link.inverse(self.results.predict(self.exog)) + self.results.Y = Y + + while self.cont(): + self.results = self.next() + self.scale = self.results.scale = self.estimate_scale() + + if self.iter >= self.maxiter: + import warnings + warnings.warn(iteration_limit_doc, IterationLimitWarning) + + return self.results diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/sandbox/infotheo.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/sandbox/infotheo.py new file mode 100644 index 0000000000000000000000000000000000000000..ec1c84aa1f4fbd9b777c5be798f7aa390c832376 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/sandbox/infotheo.py @@ -0,0 +1,520 @@ +""" +Information Theoretic and Entropy Measures + +References +---------- +Golan, As. 2008. "Information and Entropy Econometrics -- A Review and + Synthesis." Foundations And Trends in Econometrics 2(1-2), 1-145. + +Golan, A., Judge, G., and Miller, D. 1996. Maximum Entropy Econometrics. + Wiley & Sons, Chichester. +""" +#For MillerMadow correction +#Miller, G. 1955. Note on the bias of information estimates. Info. Theory +# Psychol. Prob. Methods II-B:95-100. + +#For ChaoShen method +#Chao, A., and T.-J. Shen. 2003. Nonparametric estimation of Shannon's index of diversity when +#there are unseen species in sample. Environ. Ecol. Stat. 10:429-443. +#Good, I. J. 1953. The population frequencies of species and the estimation of population parameters. +#Biometrika 40:237-264. +#Horvitz, D.G., and D. J. Thompson. 1952. A generalization of sampling without replacement from a finute universe. J. Am. Stat. Assoc. 47:663-685. + +#For NSB method +#Nemenman, I., F. Shafee, and W. Bialek. 2002. Entropy and inference, revisited. In: Dietterich, T., +#S. Becker, Z. Gharamani, eds. Advances in Neural Information Processing Systems 14: 471-478. +#Cambridge (Massachusetts): MIT Press. + +#For shrinkage method +#Dougherty, J., Kohavi, R., and Sahami, M. (1995). Supervised and unsupervised discretization of +#continuous features. In International Conference on Machine Learning. +#Yang, Y. and Webb, G. I. (2003). Discretization for naive-bayes learning: managing discretization +#bias and variance. Technical Report 2003/131 School of Computer Science and Software Engineer- +#ing, Monash University. + +from statsmodels.compat.python import lzip, lmap +from scipy import stats +import numpy as np +from matplotlib import pyplot as plt +from scipy.special import logsumexp as sp_logsumexp + +#TODO: change these to use maxentutils so that over/underflow is handled +#with the logsumexp. + + +def logsumexp(a, axis=None): + """ + Compute the log of the sum of exponentials log(e^{a_1}+...e^{a_n}) of a + + Avoids numerical overflow. + + Parameters + ---------- + a : array_like + The vector to exponentiate and sum + axis : int, optional + The axis along which to apply the operation. Defaults is None. + + Returns + ------- + sum(log(exp(a))) + + Notes + ----- + This function was taken from the mailing list + http://mail.scipy.org/pipermail/scipy-user/2009-October/022931.html + + This should be superceded by the ufunc when it is finished. + """ + if axis is None: + # Use the scipy.maxentropy version. + return sp_logsumexp(a) + a = np.asarray(a) + shp = list(a.shape) + shp[axis] = 1 + a_max = a.max(axis=axis) + s = np.log(np.exp(a - a_max.reshape(shp)).sum(axis=axis)) + lse = a_max + s + return lse + + +def _isproperdist(X): + """ + Checks to see if `X` is a proper probability distribution + """ + X = np.asarray(X) + if not np.allclose(np.sum(X), 1) or not np.all(X>=0) or not np.all(X<=1): + return False + else: + return True + +def discretize(X, method="ef", nbins=None): + """ + Discretize `X` + + Parameters + ---------- + bins : int, optional + Number of bins. Default is floor(sqrt(N)) + method : str + "ef" is equal-frequency binning + "ew" is equal-width binning + + Examples + -------- + """ + nobs = len(X) + if nbins is None: + nbins = np.floor(np.sqrt(nobs)) + if method == "ef": + discrete = np.ceil(nbins * stats.rankdata(X)/nobs) + if method == "ew": + width = np.max(X) - np.min(X) + width = np.floor(width/nbins) + svec, ivec = stats.fastsort(X) + discrete = np.zeros(nobs) + binnum = 1 + base = svec[0] + discrete[ivec[0]] = binnum + for i in range(1,nobs): + if svec[i] < base + width: + discrete[ivec[i]] = binnum + else: + base = svec[i] + binnum += 1 + discrete[ivec[i]] = binnum + return discrete +#TODO: looks okay but needs more robust tests for corner cases + + + +def logbasechange(a,b): + """ + There is a one-to-one transformation of the entropy value from + a log base b to a log base a : + + H_{b}(X)=log_{b}(a)[H_{a}(X)] + + Returns + ------- + log_{b}(a) + """ + return np.log(b)/np.log(a) + +def natstobits(X): + """ + Converts from nats to bits + """ + return logbasechange(np.e, 2) * X + +def bitstonats(X): + """ + Converts from bits to nats + """ + return logbasechange(2, np.e) * X + +#TODO: make this entropy, and then have different measures as +#a method +def shannonentropy(px, logbase=2): + """ + This is Shannon's entropy + + Parameters + ---------- + logbase, int or np.e + The base of the log + px : 1d or 2d array_like + Can be a discrete probability distribution, a 2d joint distribution, + or a sequence of probabilities. + + Returns + ----- + For log base 2 (bits) given a discrete distribution + H(p) = sum(px * log2(1/px) = -sum(pk*log2(px)) = E[log2(1/p(X))] + + For log base 2 (bits) given a joint distribution + H(px,py) = -sum_{k,j}*w_{kj}log2(w_{kj}) + + Notes + ----- + shannonentropy(0) is defined as 0 + """ +#TODO: have not defined the px,py case? + px = np.asarray(px) + if not np.all(px <= 1) or not np.all(px >= 0): + raise ValueError("px does not define proper distribution") + entropy = -np.sum(np.nan_to_num(px*np.log2(px))) + if logbase != 2: + return logbasechange(2,logbase) * entropy + else: + return entropy + +# Shannon's information content +def shannoninfo(px, logbase=2): + """ + Shannon's information + + Parameters + ---------- + px : float or array_like + `px` is a discrete probability distribution + + Returns + ------- + For logbase = 2 + np.log2(px) + """ + px = np.asarray(px) + if not np.all(px <= 1) or not np.all(px >= 0): + raise ValueError("px does not define proper distribution") + if logbase != 2: + return - logbasechange(2,logbase) * np.log2(px) + else: + return - np.log2(px) + +def condentropy(px, py, pxpy=None, logbase=2): + """ + Return the conditional entropy of X given Y. + + Parameters + ---------- + px : array_like + py : array_like + pxpy : array_like, optional + If pxpy is None, the distributions are assumed to be independent + and conendtropy(px,py) = shannonentropy(px) + logbase : int or np.e + + Returns + ------- + sum_{kj}log(q_{j}/w_{kj} + + where q_{j} = Y[j] + and w_kj = X[k,j] + """ + if not _isproperdist(px) or not _isproperdist(py): + raise ValueError("px or py is not a proper probability distribution") + if pxpy is not None and not _isproperdist(pxpy): + raise ValueError("pxpy is not a proper joint distribtion") + if pxpy is None: + pxpy = np.outer(py,px) + condent = np.sum(pxpy * np.nan_to_num(np.log2(py/pxpy))) + if logbase == 2: + return condent + else: + return logbasechange(2, logbase) * condent + +def mutualinfo(px,py,pxpy, logbase=2): + """ + Returns the mutual information between X and Y. + + Parameters + ---------- + px : array_like + Discrete probability distribution of random variable X + py : array_like + Discrete probability distribution of random variable Y + pxpy : 2d array_like + The joint probability distribution of random variables X and Y. + Note that if X and Y are independent then the mutual information + is zero. + logbase : int or np.e, optional + Default is 2 (bits) + + Returns + ------- + shannonentropy(px) - condentropy(px,py,pxpy) + """ + if not _isproperdist(px) or not _isproperdist(py): + raise ValueError("px or py is not a proper probability distribution") + if pxpy is not None and not _isproperdist(pxpy): + raise ValueError("pxpy is not a proper joint distribtion") + if pxpy is None: + pxpy = np.outer(py,px) + return shannonentropy(px, logbase=logbase) - condentropy(px,py,pxpy, + logbase=logbase) + +def corrent(px,py,pxpy,logbase=2): + """ + An information theoretic correlation measure. + + Reflects linear and nonlinear correlation between two random variables + X and Y, characterized by the discrete probability distributions px and py + respectively. + + Parameters + ---------- + px : array_like + Discrete probability distribution of random variable X + py : array_like + Discrete probability distribution of random variable Y + pxpy : 2d array_like, optional + Joint probability distribution of X and Y. If pxpy is None, X and Y + are assumed to be independent. + logbase : int or np.e, optional + Default is 2 (bits) + + Returns + ------- + mutualinfo(px,py,pxpy,logbase=logbase)/shannonentropy(py,logbase=logbase) + + Notes + ----- + This is also equivalent to + + corrent(px,py,pxpy) = 1 - condent(px,py,pxpy)/shannonentropy(py) + """ + if not _isproperdist(px) or not _isproperdist(py): + raise ValueError("px or py is not a proper probability distribution") + if pxpy is not None and not _isproperdist(pxpy): + raise ValueError("pxpy is not a proper joint distribtion") + if pxpy is None: + pxpy = np.outer(py,px) + + return mutualinfo(px,py,pxpy,logbase=logbase)/shannonentropy(py, + logbase=logbase) + +def covent(px,py,pxpy,logbase=2): + """ + An information theoretic covariance measure. + + Reflects linear and nonlinear correlation between two random variables + X and Y, characterized by the discrete probability distributions px and py + respectively. + + Parameters + ---------- + px : array_like + Discrete probability distribution of random variable X + py : array_like + Discrete probability distribution of random variable Y + pxpy : 2d array_like, optional + Joint probability distribution of X and Y. If pxpy is None, X and Y + are assumed to be independent. + logbase : int or np.e, optional + Default is 2 (bits) + + Returns + ------- + condent(px,py,pxpy,logbase=logbase) + condent(py,px,pxpy, + logbase=logbase) + + Notes + ----- + This is also equivalent to + + covent(px,py,pxpy) = condent(px,py,pxpy) + condent(py,px,pxpy) + """ + if not _isproperdist(px) or not _isproperdist(py): + raise ValueError("px or py is not a proper probability distribution") + if pxpy is not None and not _isproperdist(pxpy): + raise ValueError("pxpy is not a proper joint distribtion") + if pxpy is None: + pxpy = np.outer(py,px) + + # FIXME: these should be `condentropy`, not `condent` + return (condent(px, py, pxpy, logbase=logbase) # noqa:F821 See GH#5756 + + condent(py, px, pxpy, logbase=logbase)) # noqa:F821 See GH#5756 + + + +#### Generalized Entropies #### + +def renyientropy(px,alpha=1,logbase=2,measure='R'): + """ + Renyi's generalized entropy + + Parameters + ---------- + px : array_like + Discrete probability distribution of random variable X. Note that + px is assumed to be a proper probability distribution. + logbase : int or np.e, optional + Default is 2 (bits) + alpha : float or inf + The order of the entropy. The default is 1, which in the limit + is just Shannon's entropy. 2 is Renyi (Collision) entropy. If + the string "inf" or numpy.inf is specified the min-entropy is returned. + measure : str, optional + The type of entropy measure desired. 'R' returns Renyi entropy + measure. 'T' returns the Tsallis entropy measure. + + Returns + ------- + 1/(1-alpha)*log(sum(px**alpha)) + + In the limit as alpha -> 1, Shannon's entropy is returned. + + In the limit as alpha -> inf, min-entropy is returned. + """ +#TODO:finish returns +#TODO:add checks for measure + if not _isproperdist(px): + raise ValueError("px is not a proper probability distribution") + alpha = float(alpha) + if alpha == 1: + genent = shannonentropy(px) + if logbase != 2: + return logbasechange(2, logbase) * genent + return genent + elif 'inf' in str(alpha).lower() or alpha == np.inf: + return -np.log(np.max(px)) + + # gets here if alpha != (1 or inf) + px = px**alpha + genent = np.log(px.sum()) + if logbase == 2: + return 1/(1-alpha) * genent + else: + return 1/(1-alpha) * logbasechange(2, logbase) * genent + +#TODO: before completing this, need to rethink the organization of +# (relative) entropy measures, ie., all put into one function +# and have kwdargs, etc.? +def gencrossentropy(px,py,pxpy,alpha=1,logbase=2, measure='T'): + """ + Generalized cross-entropy measures. + + Parameters + ---------- + px : array_like + Discrete probability distribution of random variable X + py : array_like + Discrete probability distribution of random variable Y + pxpy : 2d array_like, optional + Joint probability distribution of X and Y. If pxpy is None, X and Y + are assumed to be independent. + logbase : int or np.e, optional + Default is 2 (bits) + measure : str, optional + The measure is the type of generalized cross-entropy desired. 'T' is + the cross-entropy version of the Tsallis measure. 'CR' is Cressie-Read + measure. + """ + + +if __name__ == "__main__": + print("From Golan (2008) \"Information and Entropy Econometrics -- A Review \ +and Synthesis") + print("Table 3.1") + # Examples from Golan (2008) + + X = [.2,.2,.2,.2,.2] + Y = [.322,.072,.511,.091,.004] + + for i in X: + print(shannoninfo(i)) + for i in Y: + print(shannoninfo(i)) + print(shannonentropy(X)) + print(shannonentropy(Y)) + + p = [1e-5,1e-4,.001,.01,.1,.15,.2,.25,.3,.35,.4,.45,.5] + + plt.subplot(111) + plt.ylabel("Information") + plt.xlabel("Probability") + x = np.linspace(0,1,100001) + plt.plot(x, shannoninfo(x)) +# plt.show() + + plt.subplot(111) + plt.ylabel("Entropy") + plt.xlabel("Probability") + x = np.linspace(0,1,101) + plt.plot(x, lmap(shannonentropy, lzip(x,1-x))) +# plt.show() + + # define a joint probability distribution + # from Golan (2008) table 3.3 + w = np.array([[0,0,1./3],[1/9.,1/9.,1/9.],[1/18.,1/9.,1/6.]]) + # table 3.4 + px = w.sum(0) + py = w.sum(1) + H_X = shannonentropy(px) + H_Y = shannonentropy(py) + H_XY = shannonentropy(w) + H_XgivenY = condentropy(px,py,w) + H_YgivenX = condentropy(py,px,w) +# note that cross-entropy is not a distance measure as the following shows + D_YX = logbasechange(2,np.e)*stats.entropy(px, py) + D_XY = logbasechange(2,np.e)*stats.entropy(py, px) + I_XY = mutualinfo(px,py,w) + print("Table 3.3") + print(H_X,H_Y, H_XY, H_XgivenY, H_YgivenX, D_YX, D_XY, I_XY) + + print("discretize functions") + X=np.array([21.2,44.5,31.0,19.5,40.6,38.7,11.1,15.8,31.9,25.8,20.2,14.2, + 24.0,21.0,11.3,18.0,16.3,22.2,7.8,27.8,16.3,35.1,14.9,17.1,28.2,16.4, + 16.5,46.0,9.5,18.8,32.1,26.1,16.1,7.3,21.4,20.0,29.3,14.9,8.3,22.5, + 12.8,26.9,25.5,22.9,11.2,20.7,26.2,9.3,10.8,15.6]) + discX = discretize(X) + #CF: R's infotheo +#TODO: compare to pyentropy quantize? + print + print("Example in section 3.6 of Golan, using table 3.3") + print("Bounding errors using Fano's inequality") + print("H(P_{e}) + P_{e}log(K-1) >= H(X|Y)") + print("or, a weaker inequality") + print("P_{e} >= [H(X|Y) - 1]/log(K)") + print("P(x) = %s" % px) + print("X = 3 has the highest probability, so this is the estimate Xhat") + pe = 1 - px[2] + print("The probability of error Pe is 1 - p(X=3) = %0.4g" % pe) + H_pe = shannonentropy([pe,1-pe]) + print("H(Pe) = %0.4g and K=3" % H_pe) + print("H(Pe) + Pe*log(K-1) = %0.4g >= H(X|Y) = %0.4g" % \ + (H_pe+pe*np.log2(2), H_XgivenY)) + print("or using the weaker inequality") + print(f"Pe = {pe:0.4g} >= [H(X) - 1]/log(K) = {(H_X - 1)/np.log2(3):0.4g}") + print("Consider now, table 3.5, where there is additional information") + print("The conditional probabilities of P(X|Y=y) are ") + w2 = np.array([[0.,0.,1.],[1/3.,1/3.,1/3.],[1/6.,1/3.,1/2.]]) + print(w2) +# not a proper distribution? + print("The probability of error given this information is") + print("Pe = [H(X|Y) -1]/log(K) = %0.4g" % ((np.mean([0,shannonentropy(w2[1]),shannonentropy(w2[2])])-1)/np.log2(3))) + print("such that more information lowers the error") + +### Stochastic processes + markovchain = np.array([[.553,.284,.163],[.465,.312,.223],[.420,.322,.258]]) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/sandbox/mle.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/sandbox/mle.py new file mode 100644 index 0000000000000000000000000000000000000000..1c599b1299e5c520e1550f4299942f6cafe77c55 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/sandbox/mle.py @@ -0,0 +1,63 @@ +'''What's the origin of this file? It is not ours. +Does not run because of missing mtx files, now included + +changes: JP corrections to imports so it runs, comment out print +''' +import numpy as np +from numpy import dot, outer, random +from scipy import io, linalg, optimize +from scipy.sparse import eye as speye +import matplotlib.pyplot as plt + +def R(v): + rq = dot(v.T,A*v)/dot(v.T,B*v) + res = (A*v-rq*B*v)/linalg.norm(B*v) + data.append(linalg.norm(res)) + return rq + +def Rp(v): + """ Gradient """ + result = 2*(A*v-R(v)*B*v)/dot(v.T,B*v) + #print "Rp: ", result + return result + +def Rpp(v): + """ Hessian """ + result = 2*(A-R(v)*B-outer(B*v,Rp(v))-outer(Rp(v),B*v))/dot(v.T,B*v) + #print "Rpp: ", result + return result + + +A = io.mmread('nos4.mtx') # clustered eigenvalues +#B = io.mmread('bcsstm02.mtx.gz') +#A = io.mmread('bcsstk06.mtx.gz') # clustered eigenvalues +#B = io.mmread('bcsstm06.mtx.gz') +n = A.shape[0] +B = speye(n,n) +random.seed(1) +v_0=random.rand(n) + +print("try fmin_bfgs") +full_output = 1 +data=[] +v,fopt, gopt, Hopt, func_calls, grad_calls, warnflag, allvecs = \ + optimize.fmin_bfgs(R,v_0,fprime=Rp,full_output=full_output,retall=1) +if warnflag == 0: + plt.semilogy(np.arange(0,len(data)),data) + print('Rayleigh quotient BFGS',R(v)) + + +print("fmin_bfgs OK") + +print("try fmin_ncg") + +# +# WARNING: the program may hangs if fmin_ncg is used +# +data=[] +v,fopt, fcalls, gcalls, hcalls, warnflag, allvecs = \ + optimize.fmin_ncg(R,v_0,fprime=Rp,fhess=Rpp,full_output=full_output,retall=1) +if warnflag==0: + plt.figure() + plt.semilogy(np.arange(0,len(data)),data) + print('Rayleigh quotient NCG',R(v)) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/sandbox/multilinear.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/sandbox/multilinear.py new file mode 100644 index 0000000000000000000000000000000000000000..736066fabaf2b682cff496d12ba34878580f4e58 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/sandbox/multilinear.py @@ -0,0 +1,323 @@ +"""Analyze a set of multiple variables with a linear models + +multiOLS: + take a model and test it on a series of variables defined over a + pandas dataset, returning a summary for each variable + +multigroup: + take a boolean vector and the definition of several groups of variables + and test if the group has a fraction of true values higher than the + rest. It allows to test if the variables in the group are significantly + more significant than outside the group. +""" +from patsy import dmatrix +import pandas as pd +from statsmodels.api import OLS +from statsmodels.api import stats +import numpy as np +import logging + +def _model2dataframe(model_endog, model_exog, model_type=OLS, **kwargs): + """return a series containing the summary of a linear model + + All the exceding parameters will be redirected to the linear model + """ + # create the linear model and perform the fit + model_result = model_type(model_endog, model_exog, **kwargs).fit() + # keeps track of some global statistics + statistics = pd.Series({'r2': model_result.rsquared, + 'adj_r2': model_result.rsquared_adj}) + # put them togher with the result for each term + result_df = pd.DataFrame({'params': model_result.params, + 'pvals': model_result.pvalues, + 'std': model_result.bse, + 'statistics': statistics}) + # add the complexive results for f-value and the total p-value + fisher_df = pd.DataFrame({'params': {'_f_test': model_result.fvalue}, + 'pvals': {'_f_test': model_result.f_pvalue}}) + # merge them and unstack to obtain a hierarchically indexed series + res_series = pd.concat([result_df, fisher_df]).unstack() + return res_series.dropna() + + +def multiOLS(model, dataframe, column_list=None, method='fdr_bh', + alpha=0.05, subset=None, model_type=OLS, **kwargs): + """apply a linear model to several endogenous variables on a dataframe + + Take a linear model definition via formula and a dataframe that will be + the environment of the model, and apply the linear model to a subset + (or all) of the columns of the dataframe. It will return a dataframe + with part of the information from the linear model summary. + + Parameters + ---------- + model : str + formula description of the model + dataframe : pandas.dataframe + dataframe where the model will be evaluated + column_list : list[str], optional + Names of the columns to analyze with the model. + If None (Default) it will perform the function on all the + eligible columns (numerical type and not in the model definition) + model_type : model class, optional + The type of model to be used. The default is the linear model. + Can be any linear model (OLS, WLS, GLS, etc..) + method : str, optional + the method used to perform the pvalue correction for multiple testing. + default is the Benjamini/Hochberg, other available methods are: + + `bonferroni` : one-step correction + `sidak` : on-step correction + `holm-sidak` : + `holm` : + `simes-hochberg` : + `hommel` : + `fdr_bh` : Benjamini/Hochberg + `fdr_by` : Benjamini/Yekutieli + + alpha : float, optional + the significance level used for the pvalue correction (default 0.05) + subset : bool array + the selected rows to be used in the regression + + all the other parameters will be directed to the model creation. + + Returns + ------- + summary : pandas.DataFrame + a dataframe containing an extract from the summary of the model + obtained for each columns. It will give the model complexive f test + result and p-value, and the regression value and standard deviarion + for each of the regressors. The DataFrame has a hierachical column + structure, divided as: + + - params: contains the parameters resulting from the models. Has + an additional column named _f_test containing the result of the + F test. + - pval: the pvalue results of the models. Has the _f_test column + for the significativity of the whole test. + - adj_pval: the corrected pvalues via the multitest function. + - std: uncertainties of the model parameters + - statistics: contains the r squared statistics and the adjusted + r squared. + + Notes + ----- + The main application of this function is on system biology to perform + a linear model testing of a lot of different parameters, like the + different genetic expression of several genes. + + See Also + -------- + statsmodels.stats.multitest + contains several functions to perform the multiple p-value correction + + Examples + -------- + Using the longley data as dataframe example + + >>> import statsmodels.api as sm + >>> data = sm.datasets.longley.load_pandas() + >>> df = data.exog + >>> df['TOTEMP'] = data.endog + + This will perform the specified linear model on all the + other columns of the dataframe + >>> multiOLS('GNP + 1', df) + + This select only a certain subset of the columns + >>> multiOLS('GNP + 0', df, ['GNPDEFL', 'TOTEMP', 'POP']) + + It is possible to specify a trasformation also on the target column, + conforming to the patsy formula specification + >>> multiOLS('GNP + 0', df, ['I(GNPDEFL**2)', 'center(TOTEMP)']) + + It is possible to specify the subset of the dataframe + on which perform the analysis + >> multiOLS('GNP + 1', df, subset=df.GNPDEFL > 90) + + Even a single column name can be given without enclosing it in a list + >>> multiOLS('GNP + 0', df, 'GNPDEFL') + """ + # data normalization + # if None take all the numerical columns that are not present in the model + # it's not waterproof but is a good enough criterion for everyday use + if column_list is None: + column_list = [name for name in dataframe.columns + if dataframe[name].dtype != object and name not in model] + # if it's a single string transform it in a single element list + if isinstance(column_list, str): + column_list = [column_list] + if subset is not None: + dataframe = dataframe.loc[subset] + # perform each model and retrieve the statistics + col_results = {} + # as the model will use always the same endogenous variables + # we can create them once and reuse + model_exog = dmatrix(model, data=dataframe, return_type="dataframe") + for col_name in column_list: + # it will try to interpret the column name as a valid dataframe + # index as it can be several times faster. If it fails it + # interpret it as a patsy formula (for example for centering) + try: + model_endog = dataframe[col_name] + except KeyError: + model_endog = dmatrix(col_name + ' + 0', data=dataframe) + # retrieve the result and store them + res = _model2dataframe(model_endog, model_exog, model_type, **kwargs) + col_results[col_name] = res + # mangle them togheter and sort by complexive p-value + summary = pd.DataFrame(col_results) + # order by the p-value: the most useful model first! + summary = summary.T.sort_values([('pvals', '_f_test')]) + summary.index.name = 'endogenous vars' + # implementing the pvalue correction method + smt = stats.multipletests + for (key1, key2) in summary: + if key1 != 'pvals': + continue + p_values = summary[key1, key2] + corrected = smt(p_values, method=method, alpha=alpha)[1] + # extend the dataframe of results with the column + # of the corrected p_values + summary['adj_' + key1, key2] = corrected + return summary + + +def _test_group(pvalues, group_name, group, exact=True): + """test if the objects in the group are different from the general set. + + The test is performed on the pvalues set (ad a pandas series) over + the group specified via a fisher exact test. + """ + from scipy.stats import fisher_exact, chi2_contingency + + totals = 1.0 * len(pvalues) + total_significant = 1.0 * np.sum(pvalues) + cross_index = [c for c in group if c in pvalues.index] + missing = [c for c in group if c not in pvalues.index] + if missing: + s = ('the test is not well defined if the group ' + 'has elements not presents in the significativity ' + 'array. group name: {}, missing elements: {}') + logging.warning(s.format(group_name, missing)) + # how many are significant and not in the group + group_total = 1.0 * len(cross_index) + group_sign = 1.0 * len([c for c in cross_index if pvalues[c]]) + group_nonsign = 1.0 * (group_total - group_sign) + # how many are significant and not outside the group + extern_sign = 1.0 * (total_significant - group_sign) + extern_nonsign = 1.0 * (totals - total_significant - group_nonsign) + # make the fisher test or the chi squared + test = fisher_exact if exact else chi2_contingency + table = [[extern_nonsign, extern_sign], [group_nonsign, group_sign]] + pvalue = test(np.array(table))[1] + # is the group more represented or less? + part = group_sign, group_nonsign, extern_sign, extern_nonsign + #increase = (group_sign / group_total) > (total_significant / totals) + increase = np.log((totals * group_sign) + / (total_significant * group_total)) + return pvalue, increase, part + + +def multigroup(pvals, groups, exact=True, keep_all=True, alpha=0.05): + """Test if the given groups are different from the total partition. + + Given a boolean array test if each group has a proportion of positives + different than the complexive proportion. + The test can be done as an exact Fisher test or approximated as a + Chi squared test for more speed. + + Parameters + ---------- + pvals : pandas series of boolean + the significativity of the variables under analysis + groups : dict of list + the name of each category of variables under exam. + each one is a list of the variables included + exact : bool, optional + If True (default) use the fisher exact test, otherwise + use the chi squared test for contingencies tables. + For high number of elements in the array the fisher test can + be significantly slower than the chi squared. + keep_all : bool, optional + if False it will drop those groups where the fraction + of positive is below the expected result. If True (default) + it will keep all the significant results. + alpha : float, optional + the significativity level for the pvalue correction + on the whole set of groups (not inside the groups themselves). + + Returns + ------- + result_df: pandas dataframe + for each group returns: + + pvals - the fisher p value of the test + adj_pvals - the adjusted pvals + increase - the log of the odd ratio between the + internal significant ratio versus the external one + _in_sign - significative elements inside the group + _in_non - non significative elements inside the group + _out_sign - significative elements outside the group + _out_non - non significative elements outside the group + + Notes + ----- + This test allow to see if a category of variables is generally better + suited to be described for the model. For example to see if a predictor + gives more information on demographic or economical parameters, + by creating two groups containing the endogenous variables of each + category. + + This function is conceived for medical dataset with a lot of variables + that can be easily grouped into functional groups. This is because + The significativity of a group require a rather large number of + composing elements. + + Examples + -------- + A toy example on a real dataset, the Guerry dataset from R + >>> url = "https://raw.githubusercontent.com/vincentarelbundock/" + >>> url = url + "Rdatasets/csv/HistData/Guerry.csv" + >>> df = pd.read_csv(url, index_col='dept') + + evaluate the relationship between the various paramenters whith the Wealth + >>> pvals = multiOLS('Wealth', df)['adj_pvals', '_f_test'] + + define the groups + >>> groups = {} + >>> groups['crime'] = ['Crime_prop', 'Infanticide', + ... 'Crime_parents', 'Desertion', 'Crime_pers'] + >>> groups['religion'] = ['Donation_clergy', 'Clergy', 'Donations'] + >>> groups['wealth'] = ['Commerce', 'Lottery', 'Instruction', 'Literacy'] + + do the analysis of the significativity + >>> multigroup(pvals < 0.05, groups) + """ + pvals = pd.Series(pvals) + if not (set(pvals.unique()) <= {False, True}): + raise ValueError("the series should be binary") + if hasattr(pvals.index, 'is_unique') and not pvals.index.is_unique: + raise ValueError("series with duplicated index is not accepted") + results = {'pvals': {}, + 'increase': {}, + '_in_sign': {}, + '_in_non': {}, + '_out_sign': {}, + '_out_non': {}} + for group_name, group_list in groups.items(): + res = _test_group(pvals, group_name, group_list, exact) + results['pvals'][group_name] = res[0] + results['increase'][group_name] = res[1] + results['_in_sign'][group_name] = res[2][0] + results['_in_non'][group_name] = res[2][1] + results['_out_sign'][group_name] = res[2][2] + results['_out_non'][group_name] = res[2][3] + result_df = pd.DataFrame(results).sort_values('pvals') + if not keep_all: + result_df = result_df[result_df.increase] + smt = stats.multipletests + corrected = smt(result_df['pvals'], method='fdr_bh', alpha=alpha)[1] + result_df['adj_pvals'] = corrected + return result_df diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/sandbox/pca.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/sandbox/pca.py new file mode 100644 index 0000000000000000000000000000000000000000..bab8fff0bc818b591076464b268bb9271d648217 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/sandbox/pca.py @@ -0,0 +1,224 @@ +#Copyright (c) 2008 Erik Tollerud (etolleru@uci.edu) +import numpy as np + + +class Pca: + """ + A basic class for Principal Component Analysis (PCA). + + p is the number of dimensions, while N is the number of data points + """ + _colors=('r','g','b','c','y','m','k') #defaults + + def __calc(self): + A = self.A + M=A-np.mean(A,axis=0) + N=M/np.std(M,axis=0) + + self.M = M + self.N = N + self._eig = None + + def __init__(self,data,names=None): + """ + p X N matrix input + """ + A = np.array(data).T + n,p = A.shape + self.n,self.p = n,p + if p > n: + from warnings import warn + warn('p > n - intentional?', RuntimeWarning) + self.A = A + self._origA=A.copy() + + self.__calc() + + self._colors= np.tile(self._colors,int((p-1)/len(self._colors))+1)[:p] + if names is not None and len(names) != p: + raise ValueError('names must match data dimension') + self.names = None if names is None else tuple([str(x) for x in names]) + + + def getCovarianceMatrix(self): + """ + returns the covariance matrix for the dataset + """ + return np.cov(self.N.T) + + def getEigensystem(self): + """ + returns a tuple of (eigenvalues,eigenvectors) for the data set. + """ + if self._eig is None: + res = np.linalg.eig(self.getCovarianceMatrix()) + sorti=np.argsort(res[0])[::-1] + res=(res[0][sorti],res[1][:,sorti]) + self._eig=res + return self._eig + + def getEigenvalues(self): + return self.getEigensystem()[0] + + def getEigenvectors(self): + return self.getEigensystem()[1] + + def getEnergies(self): + """ + "energies" are just normalized eigenvectors + """ + v=self.getEigenvalues() + return v/np.sum(v) + + def plot2d(self,ix=0,iy=1,clf=True): + """ + Generates a 2-dimensional plot of the data set and principle components + using matplotlib. + + ix specifies which p-dimension to put on the x-axis of the plot + and iy specifies which to put on the y-axis (0-indexed) + """ + import matplotlib.pyplot as plt + x,y=self.N[:,ix],self.N[:,iy] + if clf: + plt.clf() + plt.scatter(x,y) + vals,evs=self.getEigensystem() + #evx,evy=evs[:,ix],evs[:,iy] + xl,xu=plt.xlim() + yl,yu=plt.ylim() + dx,dy=(xu-xl),(yu-yl) + for val,vec,c in zip(vals,evs.T,self._colors): + plt.arrow(0,0,val*vec[ix],val*vec[iy],head_width=0.05*(dx*dy/4)**0.5,fc=c,ec=c) + #plt.arrow(0,0,vals[ix]*evs[ix,ix],vals[ix]*evs[iy,ix],head_width=0.05*(dx*dy/4)**0.5,fc='g',ec='g') + #plt.arrow(0,0,vals[iy]*evs[ix,iy],vals[iy]*evs[iy,iy],head_width=0.05*(dx*dy/4)**0.5,fc='r',ec='r') + if self.names is not None: + plt.xlabel('$'+self.names[ix]+'/\\sigma$') + plt.ylabel('$'+self.names[iy]+'/\\sigma$') + + def plot3d(self,ix=0,iy=1,iz=2,clf=True): + """ + Generates a 3-dimensional plot of the data set and principle components + using mayavi. + + ix, iy, and iz specify which of the input p-dimensions to place on each of + the x,y,z axes, respectively (0-indexed). + """ + import enthought.mayavi.mlab as M + if clf: + M.clf() + z3=np.zeros(3) + v=(self.getEigenvectors()*self.getEigenvalues()) + M.quiver3d(z3,z3,z3,v[ix],v[iy],v[iz],scale_factor=5) + M.points3d(self.N[:,ix],self.N[:,iy],self.N[:,iz],scale_factor=0.3) + if self.names: + M.axes(xlabel=self.names[ix]+'/sigma',ylabel=self.names[iy]+'/sigma',zlabel=self.names[iz]+'/sigma') + else: + M.axes() + + def sigclip(self,sigs): + """ + clips out all data points that are more than a certain number + of standard deviations from the mean. + + sigs can be either a single value or a length-p sequence that + specifies the number of standard deviations along each of the + p dimensions. + """ + if np.isscalar(sigs): + sigs=sigs*np.ones(self.N.shape[1]) + sigs = sigs*np.std(self.N,axis=1) + n = self.N.shape[0] + m = np.all(np.abs(self.N) < sigs,axis=1) + self.A=self.A[m] + self.__calc() + return n-sum(m) + + def reset(self): + self.A = self._origA.copy() + self.__calc() + + + def project(self,vals=None,enthresh=None,nPCs=None,cumen=None): + """ + projects the normalized values onto the components + + enthresh, nPCs, and cumen determine how many PCs to use + + if vals is None, the normalized data vectors are the values to project. + Otherwise, it should be convertable to a p x N array + + returns n,p(>threshold) dimension array + """ + nonnones = sum([e is not None for e in (enthresh, nPCs, cumen)]) + if nonnones == 0: + m = slice(None) + elif nonnones > 1: + raise ValueError("cannot specify more than one threshold") + else: + if enthresh is not None: + m = self.energies() > enthresh + elif nPCs is not None: + m = slice(None,nPCs) + elif cumen is not None: + m = np.cumsum(self.energies()) < cumen + else: + raise RuntimeError('Should be unreachable') + + if vals is None: + vals = self.N.T + else: + vals = np.array(vals,copy=False) + if self.N.T.shape[0] != vals.shape[0]: + raise ValueError("shape for vals does not match") + proj = np.matrix(self.getEigenvectors()).T*vals + return proj[m].T + + def deproject(self,A,normed=True): + """ + input is an n X q array, where q <= p + + output is p X n + """ + A=np.atleast_2d(A) + n,q = A.shape + p = self.A.shape[1] + if q > p : + raise ValueError("q > p") + + evinv=np.linalg.inv(np.matrix(self.getEigenvectors()).T) + + zs = np.zeros((n,p)) + zs[:,:q]=A + + proj = evinv*zs.T + + if normed: + return np.array(proj.T).T + else: + mns=np.mean(self.A,axis=0) + sds=np.std(self.M,axis=0) + return (np.array(proj.T)*sds+mns).T + + def subtractPC(self,pc,vals=None): + """ + pc can be a scalar or any sequence of pc indecies + + if vals is None, the source data is self.A, else whatever is in vals + (which must be p x m) + """ + if vals is None: + vals = self.A + else: + vals = vals.T + if vals.shape[1]!= self.A.shape[1]: + raise ValueError("vals do not have the correct number of components") + + pcs=self.project() + zpcs=np.zeros_like(pcs) + zpcs[:,pc]=pcs[:,pc] + upc=self.deproject(zpcs,False) + + A = vals.T-upc + B = A.T*np.std(self.M,axis=0) + return B+np.mean(self.A,axis=0) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/sandbox/predict_functional.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/sandbox/predict_functional.py new file mode 100644 index 0000000000000000000000000000000000000000..9570bf0a01fa5f23276b7285c4366dc17c4da9ce --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/sandbox/predict_functional.py @@ -0,0 +1,447 @@ +""" +A predict-like function that constructs means and pointwise or +simultaneous confidence bands for the function f(x) = E[Y | X*=x, +X1=x1, ...], where X* is the focus variable and X1, X2, ... are +non-focus variables. This is especially useful when conducting a +functional regression in which the role of x is modeled with b-splines +or other basis functions. +""" +import pandas as pd +import patsy +import numpy as np +import warnings + +from statsmodels.tools.sm_exceptions import ValueWarning +from statsmodels.compat.pandas import Appender + +_predict_functional_doc =\ + """ + Predictions and contrasts of a fitted model as a function of a given covariate. + + The value of the focus variable varies along a sequence of its + quantiles, calculated from the data used to fit the model. The + other variables are held constant either at given values, or at + values obtained by applying given summary functions to the data + used to fit the model. Optionally, a second specification of the + non-focus variables is provided and the contrast between the two + specifications is returned. + + Parameters + ---------- + result : statsmodels result object + A results object for the fitted model. + focus_var : str + The name of the 'focus variable'. + summaries : dict-like + A map from names of non-focus variables to summary functions. + Each summary function is applied to the data used to fit the + model, to obtain a value at which the variable is held fixed. + values : dict-like + Values at which a given non-focus variable is held fixed. + summaries2 : dict-like + A second set of summary functions used to define a contrast. + values2 : dict-like + A second set of fixed values used to define a contrast. + alpha : float + `1 - alpha` is the coverage probability. + ci_method : str + The method for constructing the confidence band, one of + 'pointwise', 'scheffe', and 'simultaneous'. + num_points : int + The number of equally-spaced quantile points where the + prediction is made. + exog : array_like + Explicitly provide points to cover with the confidence band. + exog2 : array_like + Explicitly provide points to contrast to `exog` in a functional + confidence band. + kwargs : + Arguments passed to the `predict` method. + + Returns + ------- + pred : array_like + The predicted mean values. + cb : array_like + An array with two columns, containing respectively the lower + and upper limits of a confidence band. + fvals : array_like + The values of the focus variable at which the prediction is + made. + + Notes + ----- + All variables in the model except for the focus variable should be + included as a key in either `summaries` or `values` (unless `exog` + is provided). + + If `summaries2` and `values2` are not provided, the returned value + contains predicted conditional means for the outcome as the focus + variable varies, with the other variables fixed as specified. + + If `summaries2` and/or `values2` is provided, two sets of + predicted conditional means are calculated, and the returned value + is the contrast between them. + + If `exog` is provided, then the rows should contain a sequence of + values approximating a continuous path through the domain of the + covariates. For example, if Z(s) is the covariate expressed as a + function of s, then the rows of exog may approximate Z(g(s)) for + some continuous function g. If `exog` is provided then neither of + the summaries or values arguments should be provided. If `exog2` + is also provided, then the returned value is a contrast between + the functionas defined by `exog` and `exog2`. + + Examples + -------- + Fit a model using a formula in which the predictors are age + (modeled with splines), ethnicity (which is categorical), gender, + and income. Then we obtain the fitted mean values as a function + of age for females with mean income and the most common + ethnicity. + + >>> model = sm.OLS.from_formula('y ~ bs(age, df=4) + C(ethnicity) + gender + income', data) + >>> result = model.fit() + >>> mode = lambda x : x.value_counts().argmax() + >>> summaries = {'income': np.mean, ethnicity=mode} + >>> values = {'gender': 'female'} + >>> pr, cb, x = predict_functional(result, 'age', summaries, values) + + Fit a model using arrays. Plot the means as a function of x3, + holding x1 fixed at its mean value in the data used to fit the + model, and holding x2 fixed at 1. + + >>> model = sm.OLS(y ,x) + >>> result = model.fit() + >>> summaries = {'x1': np.mean} + >>> values = {'x2': 1} + >>> pr, cb, x = predict_functional(result, 'x3', summaries, values) + + Fit a model usng a formula and construct a contrast comparing the + female and male predicted mean functions. + + >>> model = sm.OLS.from_formula('y ~ bs(age, df=4) + gender', data) + >>> result = model.fit() + >>> values = {'gender': 'female'} + >>> values2 = {'gender': 'male'} + >>> pr, cb, x = predict_functional(result, 'age', values=values, values2=values2) + """ + + +def _make_exog_from_formula(result, focus_var, summaries, values, num_points): + """ + Create dataframes for exploring a fitted model as a function of one variable. + + This works for models fit with a formula. + + Returns + ------- + dexog : data frame + A data frame in which the focus variable varies and the other variables + are fixed at specified or computed values. + fexog : data frame + The data frame `dexog` processed through the model formula. + """ + + model = result.model + exog = model.data.frame + + if summaries is None: + summaries = {} + if values is None: + values = {} + + if exog[focus_var].dtype is np.dtype('O'): + raise ValueError('focus variable may not have object type') + + colnames = list(summaries.keys()) + list(values.keys()) + [focus_var] + dtypes = [exog[x].dtype for x in colnames] + + # Check for variables whose values are not set either through + # `values` or `summaries`. Since the model data frame can contain + # extra variables not referenced in the formula RHS, this may not + # be a problem, so just warn. There is no obvious way to extract + # from a formula all the variable names that it references. + varl = set(exog.columns.tolist()) - {model.endog_names} + unmatched = varl - set(colnames) + unmatched = list(unmatched) + if len(unmatched) > 0: + warnings.warn("%s in data frame but not in summaries or values." + % ", ".join(["'%s'" % x for x in unmatched]), + ValueWarning) + + # Initialize at zero so each column can be converted to any dtype. + ix = range(num_points) + fexog = pd.DataFrame(index=ix, columns=colnames) + for d, x in zip(dtypes, colnames): + fexog[x] = pd.Series(index=ix, dtype=d) + + # The values of the 'focus variable' are a sequence of percentiles + pctls = np.linspace(0, 100, num_points).tolist() + fvals = np.percentile(exog[focus_var], pctls) + fvals = np.asarray(fvals) + fexog.loc[:, focus_var] = fvals + + # The values of the other variables may be given by summary functions... + for ky in summaries.keys(): + fexog.loc[:, ky] = summaries[ky](exog.loc[:, ky]) + + # or they may be provided as given values. + for ky in values.keys(): + fexog[ky] = values[ky] + + dexog = patsy.dmatrix(model.data.design_info, fexog, + return_type='dataframe') + return dexog, fexog, fvals + + +def _make_exog_from_arrays(result, focus_var, summaries, values, num_points): + """ + Create dataframes for exploring a fitted model as a function of one variable. + + This works for models fit without a formula. + + Returns + ------- + exog : data frame + A data frame in which the focus variable varies and the other variables + are fixed at specified or computed values. + """ + + model = result.model + model_exog = model.exog + exog_names = model.exog_names + + if summaries is None: + summaries = {} + if values is None: + values = {} + + exog = np.zeros((num_points, model_exog.shape[1])) + + # Check for variables whose values are not set either through + # `values` or `summaries`. + colnames = list(values.keys()) + list(summaries.keys()) + [focus_var] + unmatched = set(exog_names) - set(colnames) + unmatched = list(unmatched) + if len(unmatched) > 0: + warnings.warn("%s in model but not in `summaries` or `values`." + % ", ".join(["'%s'" % x for x in unmatched]), + ValueWarning) + + # The values of the 'focus variable' are a sequence of percentiles + pctls = np.linspace(0, 100, num_points).tolist() + ix = exog_names.index(focus_var) + fvals = np.percentile(model_exog[:, ix], pctls) + exog[:, ix] = fvals + + # The values of the other variables may be given by summary functions... + for ky in summaries.keys(): + ix = exog_names.index(ky) + exog[:, ix] = summaries[ky](model_exog[:, ix]) + + # or they may be provided as given values. + for ky in values.keys(): + ix = exog_names.index(ky) + exog[:, ix] = values[ky] + + return exog, fvals + + +def _make_exog(result, focus_var, summaries, values, num_points): + + # Branch depending on whether the model was fit with a formula. + if hasattr(result.model.data, "frame"): + dexog, fexog, fvals = _make_exog_from_formula(result, focus_var, + summaries, values, num_points) + else: + exog, fvals = _make_exog_from_arrays(result, focus_var, summaries, + values, num_points) + dexog, fexog = exog, exog + + return dexog, fexog, fvals + + +def _check_args(values, summaries, values2, summaries2): + + if values is None: + values = {} + if values2 is None: + values2 = {} + if summaries is None: + summaries = {} + if summaries2 is None: + summaries2 = {} + + for (s,v) in (summaries, values), (summaries2, values2): + ky = set(v.keys()) & set(s.keys()) + ky = list(ky) + if len(ky) > 0: + raise ValueError("One or more variable names are contained in both `summaries` and `values`:" + + ", ".join(ky)) + + return values, summaries, values2, summaries2 + + +@Appender(_predict_functional_doc) +def predict_functional(result, focus_var, summaries=None, values=None, + summaries2=None, values2=None, alpha=0.05, + ci_method="pointwise", linear=True, num_points=10, + exog=None, exog2=None, **kwargs): + + if ci_method not in ("pointwise", "scheffe", "simultaneous"): + raise ValueError('confidence band method must be one of ' + '`pointwise`, `scheffe`, and `simultaneous`.') + + contrast = (values2 is not None) or (summaries2 is not None) + + if contrast and not linear: + raise ValueError("`linear` must be True for computing contrasts") + + model = result.model + if exog is not None: + + if any(x is not None for x in [summaries, summaries2, values, values2]): + raise ValueError("if `exog` is provided then do not " + "provide `summaries` or `values`") + + fexog = exog + dexog = patsy.dmatrix(model.data.design_info, + fexog, return_type='dataframe') + fvals = exog[focus_var] + + if exog2 is not None: + fexog2 = exog + dexog2 = patsy.dmatrix(model.data.design_info, + fexog2, return_type='dataframe') + fvals2 = fvals + + else: + + values, summaries, values2, summaries2 = _check_args(values, + summaries, + values2, + summaries2) + + dexog, fexog, fvals = _make_exog(result, focus_var, summaries, + values, num_points) + + if len(summaries2) + len(values2) > 0: + dexog2, fexog2, fvals2 = _make_exog(result, focus_var, summaries2, + values2, num_points) + + from statsmodels.genmod.generalized_linear_model import GLM + from statsmodels.genmod.generalized_estimating_equations import GEE + if isinstance(result.model, (GLM, GEE)): + kwargs_pred = kwargs.copy() + kwargs_pred.update({"which": "linear"}) + else: + kwargs_pred = kwargs + + pred = result.predict(exog=fexog, **kwargs_pred) + if contrast: + pred2 = result.predict(exog=fexog2, **kwargs_pred) + pred = pred - pred2 + dexog = dexog - dexog2 + + if ci_method == 'pointwise': + + t_test = result.t_test(dexog) + cb = t_test.conf_int(alpha=alpha) + + elif ci_method == 'scheffe': + + t_test = result.t_test(dexog) + sd = t_test.sd + cb = np.zeros((num_points, 2)) + + # Scheffe's method + from scipy.stats.distributions import f as fdist + df1 = result.model.exog.shape[1] + df2 = result.model.exog.shape[0] - df1 + qf = fdist.cdf(1 - alpha, df1, df2) + fx = sd * np.sqrt(df1 * qf) + cb[:, 0] = pred - fx + cb[:, 1] = pred + fx + + elif ci_method == 'simultaneous': + + sigma, c = _glm_basic_scr(result, dexog, alpha) + cb = np.zeros((dexog.shape[0], 2)) + cb[:, 0] = pred - c*sigma + cb[:, 1] = pred + c*sigma + + if not linear: + # May need to support other models with link-like functions. + link = result.family.link + pred = link.inverse(pred) + cb = link.inverse(cb) + + return pred, cb, fvals + + +def _glm_basic_scr(result, exog, alpha): + """ + The basic SCR from (Sun et al. Annals of Statistics 2000). + + Computes simultaneous confidence regions (SCR). + + Parameters + ---------- + result : results instance + The fitted GLM results instance + exog : array_like + The exog values spanning the interval + alpha : float + `1 - alpha` is the coverage probability. + + Returns + ------- + An array with two columns, containing the lower and upper + confidence bounds, respectively. + + Notes + ----- + The rows of `exog` should be a sequence of covariate values + obtained by taking one 'free variable' x and varying it over an + interval. The matrix `exog` is thus the basis functions and any + other covariates evaluated as x varies. + """ + + model = result.model + n = model.exog.shape[0] + + # Get the Hessian without recomputing. + cov = result.cov_params() + hess = np.linalg.inv(cov) + + # Proposition 3.1 of Sun et al. + A = hess / n + B = np.linalg.cholesky(A).T # Upper Cholesky triangle + + # The variance and SD of the linear predictor at each row of exog. + sigma2 = (np.dot(exog, cov) * exog).sum(axis=1) + sigma = np.asarray(np.sqrt(sigma2)) + + # Calculate kappa_0 (formula 42 from Sun et al) + bz = np.linalg.solve(B.T, exog.T).T + bz /= np.sqrt(n) + bz /= sigma[:, None] + bzd = np.diff(bz, 1, axis=0) + bzdn = (bzd**2).sum(1) + kappa_0 = np.sqrt(bzdn).sum() + + from scipy.stats.distributions import norm + + # The root of this function is the multiplier for the confidence + # band, see Sun et al. equation 35. + def func(c): + return kappa_0 * np.exp(-c**2/2) / np.pi + 2*(1 - norm.cdf(c)) - alpha + + from scipy.optimize import brentq + + c, rslt = brentq(func, 1, 10, full_output=True) + if not rslt.converged: + raise ValueError("Root finding error in basic SCR") + + return sigma, c diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/sandbox/rls.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/sandbox/rls.py new file mode 100644 index 0000000000000000000000000000000000000000..9daa663cca6aac92015b911047e41e9457472ac7 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/sandbox/rls.py @@ -0,0 +1,151 @@ +"""Restricted least squares + +from pandas +License: Simplified BSD +""" +import numpy as np +from statsmodels.regression.linear_model import GLS, RegressionResults + + +class RLS(GLS): + """ + Restricted general least squares model that handles linear constraints + + Parameters + ---------- + endog : array_like + n length array containing the dependent variable + exog : array_like + n-by-p array of independent variables + constr : array_like + k-by-p array of linear constraints + param : array_like or scalar + p-by-1 array (or scalar) of constraint parameters + sigma (None): scalar or array_like + The weighting matrix of the covariance. No scaling by default (OLS). + If sigma is a scalar, then it is converted into an n-by-n diagonal + matrix with sigma as each diagonal element. + If sigma is an n-length array, then it is assumed to be a diagonal + matrix with the given sigma on the diagonal (WLS). + + Notes + ----- + endog = exog * beta + epsilon + weights' * constr * beta = param + + See Greene and Seaks, "The Restricted Least Squares Estimator: + A Pedagogical Note", The Review of Economics and Statistics, 1991. + """ + + def __init__(self, endog, exog, constr, param=0., sigma=None): + N, Q = exog.shape + constr = np.asarray(constr) + if constr.ndim == 1: + K, P = 1, constr.shape[0] + else: + K, P = constr.shape + if Q != P: + raise Exception('Constraints and design do not align') + self.ncoeffs = Q + self.nconstraint = K + self.constraint = constr + if np.isscalar(param) and K > 1: + param = np.ones((K,)) * param + self.param = param + if sigma is None: + sigma = 1. + if np.isscalar(sigma): + sigma = np.ones(N) * sigma + sigma = np.squeeze(sigma) + if sigma.ndim == 1: + self.sigma = np.diag(sigma) + self.cholsigmainv = np.diag(np.sqrt(sigma)) + else: + self.sigma = sigma + self.cholsigmainv = np.linalg.cholesky(np.linalg.pinv(self.sigma)).T + super(GLS, self).__init__(endog, exog) + + _rwexog = None + @property + def rwexog(self): + """Whitened exogenous variables augmented with restrictions""" + if self._rwexog is None: + P = self.ncoeffs + K = self.nconstraint + design = np.zeros((P + K, P + K)) + design[:P, :P] = np.dot(self.wexog.T, self.wexog) #top left + constr = np.reshape(self.constraint, (K, P)) + design[:P, P:] = constr.T #top right partition + design[P:, :P] = constr #bottom left partition + design[P:, P:] = np.zeros((K, K)) #bottom right partition + self._rwexog = design + return self._rwexog + + _inv_rwexog = None + @property + def inv_rwexog(self): + """Inverse of self.rwexog""" + if self._inv_rwexog is None: + self._inv_rwexog = np.linalg.inv(self.rwexog) + return self._inv_rwexog + + _rwendog = None + @property + def rwendog(self): + """Whitened endogenous variable augmented with restriction parameters""" + if self._rwendog is None: + P = self.ncoeffs + K = self.nconstraint + response = np.zeros((P + K,)) + response[:P] = np.dot(self.wexog.T, self.wendog) + response[P:] = self.param + self._rwendog = response + return self._rwendog + + _ncp = None + @property + def rnorm_cov_params(self): + """Parameter covariance under restrictions""" + if self._ncp is None: + P = self.ncoeffs + self._ncp = self.inv_rwexog[:P, :P] + return self._ncp + + _wncp = None + @property + def wrnorm_cov_params(self): + """ + Heteroskedasticity-consistent parameter covariance + Used to calculate White standard errors. + """ + if self._wncp is None: + df = self.df_resid + pred = np.dot(self.wexog, self.coeffs) + eps = np.diag((self.wendog - pred) ** 2) + sigmaSq = np.sum(eps) + pinvX = np.dot(self.rnorm_cov_params, self.wexog.T) + self._wncp = np.dot(np.dot(pinvX, eps), pinvX.T) * df / sigmaSq + return self._wncp + + _coeffs = None + @property + def coeffs(self): + """Estimated parameters""" + if self._coeffs is None: + betaLambda = np.dot(self.inv_rwexog, self.rwendog) + self._coeffs = betaLambda[:self.ncoeffs] + return self._coeffs + + def fit(self): + rncp = self.wrnorm_cov_params + lfit = RegressionResults(self, self.coeffs, normalized_cov_params=rncp) + return lfit + +if __name__=="__main__": + import statsmodels.api as sm + dta = np.genfromtxt('./rlsdata.txt', names=True) + design = np.column_stack((dta['Y'],dta['Y']**2,dta[['NE','NC','W','S']].view(float).reshape(dta.shape[0],-1))) + design = sm.add_constant(design, prepend=True) + rls_mod = RLS(dta['G'],design, constr=[0,0,0,1,1,1,1]) + rls_fit = rls_mod.fit() + print(rls_fit.params) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/sandbox/sysreg.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/sandbox/sysreg.py new file mode 100644 index 0000000000000000000000000000000000000000..980bca8590156d3b6dc510ff4f4dfeb29cc3ff4a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/sandbox/sysreg.py @@ -0,0 +1,376 @@ +from statsmodels.regression.linear_model import GLS +import numpy as np +from statsmodels.base.model import LikelihoodModelResults +from scipy import sparse + +# http://www.irisa.fr/aladin/wg-statlin/WORKSHOPS/RENNES02/SLIDES/Foschi.pdf + +__all__ = ['SUR', 'Sem2SLS'] + + +#probably should have a SystemModel superclass +# TODO: does it make sense of SUR equations to have +# independent endogenous regressors? If so, then +# change docs to LHS = RHS +#TODO: make a dictionary that holds equation specific information +#rather than these cryptic lists? Slower to get a dict value? +#TODO: refine sigma definition +class SUR: + """ + Seemingly Unrelated Regression + + Parameters + ---------- + sys : list + [endog1, exog1, endog2, exog2,...] It will be of length 2 x M, + where M is the number of equations endog = exog. + sigma : array_like + M x M array where sigma[i,j] is the covariance between equation i and j + dfk : None, 'dfk1', or 'dfk2' + Default is None. Correction for the degrees of freedom + should be specified for small samples. See the notes for more + information. + + Attributes + ---------- + cholsigmainv : ndarray + The transpose of the Cholesky decomposition of `pinv_wexog` + df_model : ndarray + Model degrees of freedom of each equation. p_{m} - 1 where p is + the number of regressors for each equation m and one is subtracted + for the constant. + df_resid : ndarray + Residual degrees of freedom of each equation. Number of observations + less the number of parameters. + endog : ndarray + The LHS variables for each equation in the system. + It is a M x nobs array where M is the number of equations. + exog : ndarray + The RHS variable for each equation in the system. + It is a nobs x sum(p_{m}) array. Which is just each + RHS array stacked next to each other in columns. + history : dict + Contains the history of fitting the model. Probably not of interest + if the model is fit with `igls` = False. + iterations : int + The number of iterations until convergence if the model is fit + iteratively. + nobs : float + The number of observations of the equations. + normalized_cov_params : ndarray + sum(p_{m}) x sum(p_{m}) array + :math:`\\left[X^{T}\\left(\\Sigma^{-1}\\otimes\\boldsymbol{I}\\right)X\\right]^{-1}` + pinv_wexog : ndarray + The pseudo-inverse of the `wexog` + sigma : ndarray + M x M covariance matrix of the cross-equation disturbances. See notes. + sp_exog : CSR sparse matrix + Contains a block diagonal sparse matrix of the design so that + exog1 ... exogM are on the diagonal. + wendog : ndarray + M * nobs x 1 array of the endogenous variables whitened by + `cholsigmainv` and stacked into a single column. + wexog : ndarray + M*nobs x sum(p_{m}) array of the whitened exogenous variables. + + Notes + ----- + All individual equations are assumed to be well-behaved, homoskedastic + iid errors. This is basically an extension of GLS, using sparse matrices. + + .. math:: \\Sigma=\\left[\\begin{array}{cccc} + \\sigma_{11} & \\sigma_{12} & \\cdots & \\sigma_{1M}\\\\ + \\sigma_{21} & \\sigma_{22} & \\cdots & \\sigma_{2M}\\\\ + \\vdots & \\vdots & \\ddots & \\vdots\\\\ + \\sigma_{M1} & \\sigma_{M2} & \\cdots & \\sigma_{MM}\\end{array}\\right] + + References + ---------- + Zellner (1962), Greene (2003) + """ +#TODO: Does each equation need nobs to be the same? + def __init__(self, sys, sigma=None, dfk=None): + if len(sys) % 2 != 0: + raise ValueError("sys must be a list of pairs of endogenous and \ +exogenous variables. Got length %s" % len(sys)) + if dfk: + if not dfk.lower() in ['dfk1','dfk2']: + raise ValueError("dfk option %s not understood" % (dfk)) + self._dfk = dfk + M = len(sys[1::2]) + self._M = M +# exog = np.zeros((M,M), dtype=object) +# for i,eq in enumerate(sys[1::2]): +# exog[i,i] = np.asarray(eq) # not sure this exog is needed + # used to compute resids for now + exog = np.column_stack(np.asarray(sys[1::2][i]) for i in range(M)) +# exog = np.vstack(np.asarray(sys[1::2][i]) for i in range(M)) + self.exog = exog # 2d ndarray exog is better +# Endog, might just go ahead and reshape this? + endog = np.asarray(sys[::2]) + self.endog = endog + self.nobs = float(self.endog[0].shape[0]) # assumes all the same length + + # Degrees of Freedom + df_resid = [] + df_model = [] + [df_resid.append(self.nobs - np.linalg.matrix_rank(_)) for _ in sys[1::2]] + [df_model.append(np.linalg.matrix_rank(_) - 1) for _ in sys[1::2]] + self.df_resid = np.asarray(df_resid) + self.df_model = np.asarray(df_model) + +# "Block-diagonal" sparse matrix of exog + sp_exog = sparse.lil_matrix((int(self.nobs*M), + int(np.sum(self.df_model+1)))) # linked lists to build + self._cols = np.cumsum(np.hstack((0, self.df_model+1))) + for i in range(M): + sp_exog[i*self.nobs:(i+1)*self.nobs, + self._cols[i]:self._cols[i+1]] = sys[1::2][i] + self.sp_exog = sp_exog.tocsr() # cast to compressed for efficiency +# Deal with sigma, check shape earlier if given + if np.any(sigma): + sigma = np.asarray(sigma) # check shape + elif sigma is None: + resids = [] + for i in range(M): + resids.append(GLS(endog[i],exog[:, + self._cols[i]:self._cols[i+1]]).fit().resid) + resids = np.asarray(resids).reshape(M,-1) + sigma = self._compute_sigma(resids) + self.sigma = sigma + self.cholsigmainv = np.linalg.cholesky(np.linalg.pinv(\ + self.sigma)).T + self.initialize() + + def initialize(self): + self.wendog = self.whiten(self.endog) + self.wexog = self.whiten(self.sp_exog) + self.pinv_wexog = np.linalg.pinv(self.wexog) + self.normalized_cov_params = np.dot(self.pinv_wexog, + np.transpose(self.pinv_wexog)) + self.history = {'params' : [np.inf]} + self.iterations = 0 + + def _update_history(self, params): + self.history['params'].append(params) + + def _compute_sigma(self, resids): + """ + Computes the sigma matrix and update the cholesky decomposition. + """ + M = self._M + nobs = self.nobs + sig = np.dot(resids, resids.T) # faster way to do this? + if not self._dfk: + div = nobs + elif self._dfk.lower() == 'dfk1': + div = np.zeros(M**2) + for i in range(M): + for j in range(M): + div[i+j] = ((self.df_model[i]+1) *\ + (self.df_model[j]+1))**(1/2) + div.reshape(M,M) + else: # 'dfk2' error checking is done earlier + div = np.zeros(M**2) + for i in range(M): + for j in range(M): + div[i+j] = nobs - np.max(self.df_model[i]+1, + self.df_model[j]+1) + div.reshape(M,M) +# does not handle (#,) + self.cholsigmainv = np.linalg.cholesky(np.linalg.pinv(sig/div)).T + return sig/div + + def whiten(self, X): + """ + SUR whiten method. + + Parameters + ---------- + X : list of arrays + Data to be whitened. + + Returns + ------- + If X is the exogenous RHS of the system. + ``np.dot(np.kron(cholsigmainv,np.eye(M)),np.diag(X))`` + + If X is the endogenous LHS of the system. + """ + nobs = self.nobs + if X is self.endog: # definitely not a robust check + return np.dot(np.kron(self.cholsigmainv,np.eye(nobs)), + X.reshape(-1,1)) + elif X is self.sp_exog: + return (sparse.kron(self.cholsigmainv, + sparse.eye(nobs,nobs))*X).toarray()#*=dot until cast to array + + def fit(self, igls=False, tol=1e-5, maxiter=100): + """ + igls : bool + Iterate until estimates converge if sigma is None instead of + two-step GLS, which is the default is sigma is None. + + tol : float + + maxiter : int + + Notes + ----- + This ia naive implementation that does not exploit the block + diagonal structure. It should work for ill-conditioned `sigma` + but this is untested. + """ + + if not np.any(self.sigma): + self.sigma = self._compute_sigma(self.endog, self.exog) + M = self._M + beta = np.dot(self.pinv_wexog, self.wendog) + self._update_history(beta) + self.iterations += 1 + if not igls: + sur_fit = SysResults(self, beta, self.normalized_cov_params) + return sur_fit + + conv = self.history['params'] + while igls and (np.any(np.abs(conv[-2] - conv[-1]) > tol)) and \ + (self.iterations < maxiter): + fittedvalues = (self.sp_exog*beta).reshape(M,-1) + resids = self.endog - fittedvalues # do not attach results yet + self.sigma = self._compute_sigma(resids) # need to attach for compute? + self.wendog = self.whiten(self.endog) + self.wexog = self.whiten(self.sp_exog) + self.pinv_wexog = np.linalg.pinv(self.wexog) + self.normalized_cov_params = np.dot(self.pinv_wexog, + np.transpose(self.pinv_wexog)) + beta = np.dot(self.pinv_wexog, self.wendog) + self._update_history(beta) + self.iterations += 1 + sur_fit = SysResults(self, beta, self.normalized_cov_params) + return sur_fit + + def predict(self, design): + pass + +#TODO: Should just have a general 2SLS estimator to subclass +# for IV, FGLS, etc. +# Also should probably have SEM class and estimators as subclasses +class Sem2SLS: + """ + Two-Stage Least Squares for Simultaneous equations + + Parameters + ---------- + sys : list + [endog1, exog1, endog2, exog2,...] It will be of length 2 x M, + where M is the number of equations endog = exog. + indep_endog : dict + A dictionary mapping the equation to the column numbers of the + the independent endogenous regressors in each equation. + It is assumed that the system is entered as broken up into + LHS and RHS. For now, the values of the dict have to be sequences. + Note that the keys for the equations should be zero-indexed. + instruments : ndarray + Array of the exogenous independent variables. + + Notes + ----- + This is unfinished, and the design should be refactored. + Estimation is done by brute force and there is no exploitation of + the structure of the system. + """ + def __init__(self, sys, indep_endog=None, instruments=None): + if len(sys) % 2 != 0: + raise ValueError("sys must be a list of pairs of endogenous and \ +exogenous variables. Got length %s" % len(sys)) + M = len(sys[1::2]) + self._M = M +# The lists are probably a bad idea + self.endog = sys[::2] # these are just list containers + self.exog = sys[1::2] + self._K = [np.linalg.matrix_rank(_) for _ in sys[1::2]] +# fullexog = np.column_stack((_ for _ in self.exog)) + + self.instruments = instruments + + # Keep the Y_j's in a container to get IVs + instr_endog = {} + [instr_endog.setdefault(_,[]) for _ in indep_endog.keys()] + + for eq_key in indep_endog: + for varcol in indep_endog[eq_key]: + instr_endog[eq_key].append(self.exog[eq_key][:,varcol]) + # ^ copy needed? +# self._instr_endog = instr_endog + + self._indep_endog = indep_endog + _col_map = np.cumsum(np.hstack((0,self._K))) # starting col no.s +# move this check to whiten since we're not going to build a full exog? + for eq_key in indep_endog: + try: + iter(indep_endog[eq_key]) + except: +# eq_key = [eq_key] + raise TypeError("The values of the indep_exog dict must be " + "iterable. Got type %s for converter %s" + % (type(indep_endog[eq_key]), eq_key)) +# for del_col in indep_endog[eq_key]: +# fullexog = np.delete(fullexog, _col_map[eq_key]+del_col, 1) +# _col_map[eq_key+1:] -= 1 + +# Josef's example for deleting reoccuring "rows" +# fullexog = np.unique(fullexog.T.view([('',fullexog.dtype)]*\ +# fullexog.shape[0])).view(fullexog.dtype).reshape(\ +# fullexog.shape[0],-1) +# From http://article.gmane.org/gmane.comp.python.numeric.general/32276/ +# Or Jouni' suggetsion of taking a hash: +# http://www.mail-archive.com/numpy-discussion@scipy.org/msg04209.html +# not clear to me how this would work though, only if they are the *same* +# elements? +# self.fullexog = fullexog + self.wexog = self.whiten(instr_endog) + + + def whiten(self, Y): + """ + Runs the first stage of the 2SLS. + + Returns the RHS variables that include the instruments. + """ + wexog = [] + indep_endog = self._indep_endog # this has the col mapping +# fullexog = self.fullexog + instruments = self.instruments + for eq in range(self._M): # need to go through all equations regardless + instr_eq = Y.get(eq, None) # Y has the eq to ind endog array map + newRHS = self.exog[eq].copy() + if instr_eq: + for i,LHS in enumerate(instr_eq): + yhat = GLS(LHS, self.instruments).fit().fittedvalues + newRHS[:,indep_endog[eq][i]] = yhat + # this might fail if there is a one variable column (nobs,) + # in exog + wexog.append(newRHS) + return wexog + + def fit(self): + """ + """ + delta = [] + wexog = self.wexog + endog = self.endog + for j in range(self._M): + delta.append(GLS(endog[j], wexog[j]).fit().params) + return delta + +class SysResults(LikelihoodModelResults): + """ + Not implemented yet. + """ + def __init__(self, model, params, normalized_cov_params=None, scale=1.): + super().__init__(model, params, + normalized_cov_params, scale) + self._get_results() + + def _get_results(self): + pass diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tests/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..72cbcf98bf0cfe0d0298739a39fbc9e65442a360 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tests/__init__.py @@ -0,0 +1 @@ +# Tests for the package behavior of statsmodels diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tests/test_package.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tests/test_package.py new file mode 100644 index 0000000000000000000000000000000000000000..4397fa6d3ab57862ef3612ba72d853bafbb21416 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tests/test_package.py @@ -0,0 +1,37 @@ +import subprocess +import sys + +from statsmodels.compat.python import PYTHON_IMPL_WASM + +import pytest + + +@pytest.mark.skipif( + PYTHON_IMPL_WASM, + reason="Can't start subprocess in WASM/Pyodide" +) +def test_lazy_imports(): + # Check that when statsmodels.api is imported, matplotlib is _not_ imported + cmd = ("import statsmodels.api as sm; " + "import sys; " + "mods = [x for x in sys.modules if 'matplotlib.pyplot' in x]; " + "assert not mods, mods") + cmd = sys.executable + ' -c "' + cmd + '"' + p = subprocess.Popen(cmd, shell=True, close_fds=True) + p.wait() + rc = p.returncode + assert rc == 0 + + +@pytest.mark.skipif( + PYTHON_IMPL_WASM, + reason="Can't start subprocess in WASM/Pyodide" +) +def test_docstring_optimization_compat(): + # GH#5235 check that importing with stripped docstrings does not raise + cmd = sys.executable + ' -OO -c "import statsmodels.api as sm"' + p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + out = p.communicate() + rc = p.returncode + assert rc == 0, out diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tests/test_x13.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tests/test_x13.py new file mode 100644 index 0000000000000000000000000000000000000000..8bf8ba308e03c191525a36ff86d62ea59adea57d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tests/test_x13.py @@ -0,0 +1,10 @@ +import pandas as pd + +from statsmodels.tsa.x13 import _make_var_names + + +def test_make_var_names(): + # Check that _make_var_names return the current name when exog is + # a pandas Series + exog = pd.Series([1, 2, 3], name="abc") + assert _make_var_names(exog) == exog.name diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tools/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d6c589b7655d6c960aaa0fdf4e5085ec3f163f5c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tools/__init__.py @@ -0,0 +1,6 @@ +from .tools import add_constant, categorical +from statsmodels.tools._test_runner import PytestTester + +__all__ = ['test', 'add_constant', 'categorical'] + +test = PytestTester() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tools/docstring.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tools/docstring.py new file mode 100644 index 0000000000000000000000000000000000000000..272aaa4c9637d459b32207e68d931788f68380a2 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tools/docstring.py @@ -0,0 +1,723 @@ +""" +Substantially copied from NumpyDoc 1.0pre. +""" +from collections import namedtuple +from collections.abc import Mapping +import copy +import inspect +import re +import textwrap + +from statsmodels.tools.sm_exceptions import ParseError + + +def dedent_lines(lines): + """Deindent a list of lines maximally""" + return textwrap.dedent("\n".join(lines)).split("\n") + + +def strip_blank_lines(line): + """Remove leading and trailing blank lines from a list of lines""" + while line and not line[0].strip(): + del line[0] + while line and not line[-1].strip(): + del line[-1] + return line + + +class Reader: + """ + A line-based string reader. + """ + + def __init__(self, data): + """ + Parameters + ---------- + data : str + String with lines separated by '\n'. + """ + if isinstance(data, list): + self._str = data + else: + self._str = data.split("\n") # store string as list of lines + + self.reset() + + def __getitem__(self, n): + return self._str[n] + + def reset(self): + self._line_num = 0 # current line nr + + def read(self): + if not self.eof(): + out = self[self._line_num] + self._line_num += 1 + return out + else: + return "" + + def seek_next_non_empty_line(self): + for line in self[self._line_num :]: + if line.strip(): + break + else: + self._line_num += 1 + + def eof(self): + return self._line_num >= len(self._str) + + def read_to_condition(self, condition_func): + start = self._line_num + for line in self[start:]: + if condition_func(line): + return self[start : self._line_num] + self._line_num += 1 + if self.eof(): + return self[start : self._line_num + 1] + return [] + + def read_to_next_empty_line(self): + self.seek_next_non_empty_line() + + def is_empty(line): + return not line.strip() + + return self.read_to_condition(is_empty) + + def read_to_next_unindented_line(self): + def is_unindented(line): + return line.strip() and (len(line.lstrip()) == len(line)) + + return self.read_to_condition(is_unindented) + + def peek(self, n=0): + if self._line_num + n < len(self._str): + return self[self._line_num + n] + else: + return "" + + def is_empty(self): + return not "".join(self._str).strip() + + +Parameter = namedtuple("Parameter", ["name", "type", "desc"]) + + +class NumpyDocString(Mapping): + """Parses a numpydoc string to an abstract representation + + Instances define a mapping from section title to structured data. + """ + + sections = { + "Signature": "", + "Summary": [""], + "Extended Summary": [], + "Parameters": [], + "Returns": [], + "Yields": [], + "Receives": [], + "Raises": [], + "Warns": [], + "Other Parameters": [], + "Attributes": [], + "Methods": [], + "See Also": [], + "Notes": [], + "Warnings": [], + "References": "", + "Examples": "", + "index": {}, + } + + def __init__(self, docstring): + orig_docstring = docstring + docstring = textwrap.dedent(docstring).split("\n") + + self._doc = Reader(docstring) + self._parsed_data = copy.deepcopy(self.sections) + + try: + self._parse() + except ParseError as e: + e.docstring = orig_docstring + raise + + def __getitem__(self, key): + return self._parsed_data[key] + + def __setitem__(self, key, val): + if key not in self._parsed_data: + self._error_location("Unknown section %s" % key) + else: + self._parsed_data[key] = val + + def __iter__(self): + return iter(self._parsed_data) + + def __len__(self): + return len(self._parsed_data) + + def _is_at_section(self): + self._doc.seek_next_non_empty_line() + + if self._doc.eof(): + return False + + l1 = self._doc.peek().strip() # e.g. Parameters + + if l1.startswith(".. index::"): + return True + + l2 = self._doc.peek(1).strip() # ---------- or ========== + return l2.startswith("-" * len(l1)) or l2.startswith("=" * len(l1)) + + def _strip(self, doc): + i = 0 + j = 0 + for i, line in enumerate(doc): + if line.strip(): + break + + for j, line in enumerate(doc[::-1]): + if line.strip(): + break + + return doc[i : len(doc) - j] + + def _read_to_next_section(self): + section = self._doc.read_to_next_empty_line() + + while not self._is_at_section() and not self._doc.eof(): + if not self._doc.peek(-1).strip(): # previous line was empty + section += [""] + + section += self._doc.read_to_next_empty_line() + + return section + + def _read_sections(self): + while not self._doc.eof(): + data = self._read_to_next_section() + name = data[0].strip() + + if name.startswith(".."): # index section + yield name, data[1:] + elif len(data) < 2: + yield StopIteration + else: + yield name, self._strip(data[2:]) + + def _parse_param_list(self, content, single_element_is_type=False): + r = Reader(content) + params = [] + while not r.eof(): + header = r.read().strip() + if " : " in header: + arg_name, arg_type = header.split(" : ")[:2] + else: + if single_element_is_type: + arg_name, arg_type = "", header + else: + arg_name, arg_type = header, "" + + desc = r.read_to_next_unindented_line() + desc = dedent_lines(desc) + desc = strip_blank_lines(desc) + + params.append(Parameter(arg_name, arg_type, desc)) + + return params + + # See also supports the following formats. + # + # + # SPACE* COLON SPACE+ SPACE* + # ( COMMA SPACE+ )+ (COMMA | PERIOD)? SPACE* + # ( COMMA SPACE+ )* SPACE* COLON SPACE+ SPACE* + + # is one of + # + # COLON COLON BACKTICK BACKTICK + # where + # is a legal function name, and + # is any nonempty sequence of word characters. + # Examples: func_f1 :meth:`func_h1` :obj:`~baz.obj_r` :class:`class_j` + # is a string describing the function. + + _role = r":(?P\w+):" + _funcbacktick = r"`(?P(?:~\w+\.)?[a-zA-Z0-9_\.-]+)`" + _funcplain = r"(?P[a-zA-Z0-9_\.-]+)" + _funcname = r"(" + _role + _funcbacktick + r"|" + _funcplain + r")" + _funcnamenext = _funcname.replace("role", "rolenext") + _funcnamenext = _funcnamenext.replace("name", "namenext") + _description = r"(?P\s*:(\s+(?P\S+.*))?)?\s*$" + _func_rgx = re.compile(r"^\s*" + _funcname + r"\s*") + _line_rgx = re.compile( + r"^\s*" + + r"(?P" + + _funcname # group for all function names + + r"(?P([,]\s+" + + _funcnamenext + + r")*)" + + r")" + + # end of "allfuncs" + # Some function lists have a trailing comma (or period) + r"(?P[,\.])?" + + _description + ) + + # Empty elements are replaced with '..' + empty_description = ".." + + def _parse_see_also(self, content): + """ + func_name : Descriptive text + continued text + another_func_name : Descriptive text + func_name1, func_name2, :meth:`func_name`, func_name3 + """ + + items = [] + + def parse_item_name(text): + """Match ':role:`name`' or 'name'.""" + m = self._func_rgx.match(text) + if not m: + raise ParseError(f"{text} is not a item name") + role = m.group("role") + name = m.group("name") if role else m.group("name2") + return name, role, m.end() + + rest = [] + for line in content: + if not line.strip(): + continue + + line_match = self._line_rgx.match(line) + description = None + if line_match: + description = line_match.group("desc") + if line_match.group("trailing") and description: + self._error_location( + "Unexpected comma or period after function list at " + "index %d of line " + '"%s"' % (line_match.end("trailing"), line) + ) + if not description and line.startswith(" "): + rest.append(line.strip()) + elif line_match: + funcs = [] + text = line_match.group("allfuncs") + while True: + if not text.strip(): + break + name, role, match_end = parse_item_name(text) + funcs.append((name, role)) + text = text[match_end:].strip() + if text and text[0] == ",": + text = text[1:].strip() + rest = list(filter(None, [description])) + items.append((funcs, rest)) + else: + raise ParseError(f"{line} is not a item name") + return items + + def _parse_index(self, section, content): + """ + .. index: default + :refguide: something, else, and more + """ + + def strip_each_in(lst): + return [s.strip() for s in lst] + + out = {} + section = section.split("::") + if len(section) > 1: + out["default"] = strip_each_in(section[1].split(","))[0] + for line in content: + line = line.split(":") + if len(line) > 2: + out[line[1]] = strip_each_in(line[2].split(",")) + return out + + def _parse_summary(self): + """Grab signature (if given) and summary""" + if self._is_at_section(): + return + + # If several signatures present, take the last one + while True: + summary = self._doc.read_to_next_empty_line() + summary_str = " ".join([s.strip() for s in summary]).strip() + compiled = re.compile(r"^([\w., ]+=)?\s*[\w\.]+\(.*\)$") + if compiled.match(summary_str): + self["Signature"] = summary_str + if not self._is_at_section(): + continue + break + + if summary is not None: + self["Summary"] = summary + + if not self._is_at_section(): + self["Extended Summary"] = self._read_to_next_section() + + def _parse(self): + self._doc.reset() + self._parse_summary() + + sections = list(self._read_sections()) + section_names = {section for section, content in sections} + + has_returns = "Returns" in section_names + has_yields = "Yields" in section_names + # We could do more tests, but we are not. Arbitrarily. + if has_returns and has_yields: + msg = "Docstring contains both a Returns and Yields section." + raise ValueError(msg) + if not has_yields and "Receives" in section_names: + msg = "Docstring contains a Receives section but not Yields." + raise ValueError(msg) + + for (section, content) in sections: + if not section.startswith(".."): + section = (s.capitalize() for s in section.split(" ")) + section = " ".join(section) + if self.get(section): + self._error_location( + "The section %s appears twice" % section + ) + + if section in ( + "Parameters", + "Other Parameters", + "Attributes", + "Methods", + ): + self[section] = self._parse_param_list(content) + elif section in ( + "Returns", + "Yields", + "Raises", + "Warns", + "Receives", + ): + self[section] = self._parse_param_list( + content, single_element_is_type=True + ) + elif section.startswith(".. index::"): + self["index"] = self._parse_index(section, content) + elif section == "See Also": + self["See Also"] = self._parse_see_also(content) + else: + self[section] = content + + def _error_location(self, msg): + if hasattr(self, "_obj"): + # we know where the docs came from: + try: + filename = inspect.getsourcefile(self._obj) + except TypeError: + filename = None + msg = msg + ( + f" in the docstring of {self._obj} in {filename}." + ) + + raise ValueError(msg) + + # string conversion routines + + def _str_header(self, name, symbol="-"): + return [name, len(name) * symbol] + + def _str_indent(self, doc, indent=4): + out = [] + for line in doc: + out += [" " * indent + line] + return out + + def _str_signature(self): + if self["Signature"]: + return [self["Signature"].replace("*", r"\*")] + [""] + else: + return [""] + + def _str_summary(self): + if self["Summary"]: + return self["Summary"] + [""] + else: + return [] + + def _str_extended_summary(self): + if self["Extended Summary"]: + return self["Extended Summary"] + [""] + else: + return [] + + def _str_param_list(self, name): + out = [] + if self[name]: + out += self._str_header(name) + for param in self[name]: + parts = [] + if param.name: + parts.append(param.name) + if param.type: + parts.append(param.type) + out += [" : ".join(parts)] + if param.desc and "".join(param.desc).strip(): + out += self._str_indent(param.desc) + out += [""] + return out + + def _str_section(self, name): + out = [] + if self[name]: + out += self._str_header(name) + out += self[name] + out += [""] + return out + + def _str_see_also(self, func_role): + if not self["See Also"]: + return [] + out = [] + out += self._str_header("See Also") + last_had_desc = True + for funcs, desc in self["See Also"]: + assert isinstance(funcs, list) + links = [] + for func, role in funcs: + if role: + link = f":{role}:`{func}`" + elif func_role: + link = f":{func_role}:`{func}`" + else: + link = "%s" % func + links.append(link) + link = ", ".join(links) + out += [link] + if desc: + out += self._str_indent([" ".join(desc)]) + last_had_desc = True + else: + last_had_desc = False + out += self._str_indent([self.empty_description]) + + if last_had_desc: + out += [""] + return out + + def _str_index(self): + idx = self["index"] + out = [] + output_index = False + default_index = idx.get("default", "") + if default_index: + output_index = True + out += [".. index:: %s" % default_index] + for section, references in idx.items(): + if section == "default": + continue + output_index = True + out += [" :{}: {}".format(section, ", ".join(references))] + if output_index: + return out + else: + return "" + + def __str__(self, func_role=""): + out = [] + out += self._str_signature() + out += self._str_summary() + out += self._str_extended_summary() + for param_list in ( + "Parameters", + "Returns", + "Yields", + "Receives", + "Other Parameters", + "Raises", + "Warns", + ): + out += self._str_param_list(param_list) + out += self._str_section("Warnings") + out += self._str_see_also(func_role) + for s in ("Notes", "References", "Examples"): + out += self._str_section(s) + for param_list in ("Attributes", "Methods"): + out += self._str_param_list(param_list) + out += self._str_index() + return "\n".join(out) + + +class Docstring: + """ + Docstring modification. + + Parameters + ---------- + docstring : str + The docstring to modify. + """ + + def __init__(self, docstring): + self._ds = None + self._docstring = docstring + if docstring is None: + return + self._ds = NumpyDocString(docstring) + + def remove_parameters(self, parameters): + """ + Parameters + ---------- + parameters : str, list[str] + The names of the parameters to remove. + """ + if self._docstring is None: + # Protection against -oo execution + return + if isinstance(parameters, str): + parameters = [parameters] + repl = [ + param + for param in self._ds["Parameters"] + if param.name not in parameters + ] + if len(repl) + len(parameters) != len(self._ds["Parameters"]): + raise ValueError("One or more parameters were not found.") + self._ds["Parameters"] = repl + + def insert_parameters(self, after, parameters): + """ + Parameters + ---------- + after : {None, str} + If None, inset the parameters before the first parameter in the + docstring. + parameters : Parameter, list[Parameter] + A Parameter of a list of Parameters. + """ + if self._docstring is None: + # Protection against -oo execution + return + if isinstance(parameters, Parameter): + parameters = [parameters] + if after is None: + self._ds["Parameters"] = parameters + self._ds["Parameters"] + else: + loc = -1 + for i, param in enumerate(self._ds["Parameters"]): + if param.name == after: + loc = i + 1 + break + if loc < 0: + raise ValueError() + params = self._ds["Parameters"][:loc] + parameters + params += self._ds["Parameters"][loc:] + self._ds["Parameters"] = params + + def replace_block(self, block_name, block): + """ + Parameters + ---------- + block_name : str + Name of the block to replace, e.g., 'Summary'. + block : object + The replacement block. The structure of the replacement block must + match how the block is stored by NumpyDocString. + """ + if self._docstring is None: + # Protection against -oo execution + return + block_name = " ".join(map(str.capitalize, block_name.split(" "))) + if block_name not in self._ds: + raise ValueError( + "{} is not a block in the " "docstring".format(block_name) + ) + if not isinstance(block, list) and isinstance( + self._ds[block_name], list + ): + block = [block] + self._ds[block_name] = block + + def extract_parameters(self, parameters, indent=0): + if self._docstring is None: + # Protection against -oo execution + return + if isinstance(parameters, str): + parameters = [parameters] + ds_params = {param.name: param for param in self._ds["Parameters"]} + missing = set(parameters).difference(ds_params.keys()) + if missing: + raise ValueError( + "{} were not found in the " + "docstring".format(",".join(missing)) + ) + final = [ds_params[param] for param in parameters] + ds = copy.deepcopy(self._ds) + for key in ds: + if key != "Parameters": + ds[key] = [] if key != "index" else {} + else: + ds[key] = final + out = str(ds).strip() + if indent: + out = textwrap.indent(out, " " * indent) + + out = "\n".join(out.split("\n")[2:]) + return out + + def __str__(self): + return str(self._ds) + + +def remove_parameters(docstring, parameters): + """ + Parameters + ---------- + docstring : str + The docstring to modify. + parameters : str, list[str] + The names of the parameters to remove. + + Returns + ------- + str + The modified docstring. + """ + if docstring is None: + return + ds = Docstring(docstring) + ds.remove_parameters(parameters) + return str(ds) + + +def indent(text, prefix, predicate=None): + """ + Non-protected indent + + Parameters + ---------- + text : {None, str} + If None, function always returns "" + prefix : str + Prefix to add to the start of each line + predicate : callable, optional + If provided, 'prefix' will only be added to the lines + where 'predicate(line)' is True. If 'predicate' is not provided, + it will default to adding 'prefix' to all non-empty lines that do not + consist solely of whitespace characters. + + Returns + ------- + + """ + if text is None: + return "" + return textwrap.indent(text, prefix, predicate=predicate) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tools/grouputils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tools/grouputils.py new file mode 100644 index 0000000000000000000000000000000000000000..cb0260d8c9482c3c3c23593aa9222f54eb57427d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tools/grouputils.py @@ -0,0 +1,553 @@ +"""Tools for working with groups + +This provides several functions to work with groups and a Group class that +keeps track of the different representations and has methods to work more +easily with groups. + + +Author: Josef Perktold, +Author: Nathaniel Smith, recipe for sparse_dummies on scipy user mailing list + +Created on Tue Nov 29 15:44:53 2011 : sparse_dummies +Created on Wed Nov 30 14:28:24 2011 : combine_indices +changes: add Group class + +Notes +~~~~~ + +This reverses the class I used before, where the class was for the data and +the group was auxiliary. Here, it is only the group, no data is kept. + +sparse_dummies needs checking for corner cases, e.g. +what if a category level has zero elements? This can happen with subset + selection even if the original groups where defined as arange. + +Not all methods and options have been tried out yet after refactoring + +need more efficient loop if groups are sorted -> see GroupSorted.group_iter +""" +from statsmodels.compat.python import lrange, lzip +import numpy as np +import pandas as pd + +import statsmodels.tools.data as data_util +from pandas import Index, MultiIndex + + +def combine_indices(groups, prefix='', sep='.', return_labels=False): + """use np.unique to get integer group indices for product, intersection + """ + if isinstance(groups, tuple): + groups = np.column_stack(groups) + else: + groups = np.asarray(groups) + + dt = groups.dtype + + is2d = (groups.ndim == 2) # need to store + + if is2d: + ncols = groups.shape[1] + if not groups.flags.c_contiguous: + groups = np.array(groups, order='C') + + groups_ = groups.view([('', groups.dtype)] * groups.shape[1]) + else: + groups_ = groups + + uni, uni_idx, uni_inv = np.unique(groups_, return_index=True, + return_inverse=True) + + if is2d: + uni = uni.view(dt).reshape(-1, ncols) + + # avoiding a view would be + # for t in uni.dtype.fields.values(): + # assert (t[0] == dt) + # + # uni.dtype = dt + # uni.shape = (uni.size//ncols, ncols) + + if return_labels: + label = [(prefix+sep.join(['%s']*len(uni[0]))) % tuple(ii) + for ii in uni] + return uni_inv, uni_idx, uni, label + else: + return uni_inv, uni_idx, uni + + +# written for and used in try_covariance_grouploop.py +def group_sums(x, group, use_bincount=True): + """simple bincount version, again + + group : ndarray, integer + assumed to be consecutive integers + + no dtype checking because I want to raise in that case + + uses loop over columns of x + + for comparison, simple python loop + """ + x = np.asarray(x) + group = np.asarray(group).squeeze() + if x.ndim == 1: + x = x[:, None] + elif x.ndim > 2 and use_bincount: + raise ValueError('not implemented yet') + + if use_bincount: + + # re-label groups or bincount takes too much memory + if np.max(group) > 2 * x.shape[0]: + group = pd.factorize(group)[0] + + return np.array( + [ + np.bincount(group, weights=x[:, col]) + for col in range(x.shape[1]) + ] + ) + else: + uniques = np.unique(group) + result = np.zeros([len(uniques)] + list(x.shape[1:])) + for ii, cat in enumerate(uniques): + result[ii] = x[group == cat].sum(0) + return result + + +def group_sums_dummy(x, group_dummy): + """sum by groups given group dummy variable + + group_dummy can be either ndarray or sparse matrix + """ + if data_util._is_using_ndarray_type(group_dummy, None): + return np.dot(x.T, group_dummy) + else: # check for sparse + return x.T * group_dummy + + +# TODO: See if this can be entirely replaced by Grouping.dummy_sparse; +# see GH#5687 +def dummy_sparse(groups): + """create a sparse indicator from a group array with integer labels + + Parameters + ---------- + groups : ndarray, int, 1d (nobs,) + an array of group indicators for each observation. Group levels are + assumed to be defined as consecutive integers, i.e. range(n_groups) + where n_groups is the number of group levels. A group level with no + observations for it will still produce a column of zeros. + + Returns + ------- + indi : ndarray, int8, 2d (nobs, n_groups) + an indicator array with one row per observation, that has 1 in the + column of the group level for that observation + + Examples + -------- + + >>> g = np.array([0, 0, 2, 1, 1, 2, 0]) + >>> indi = dummy_sparse(g) + >>> indi + <7x3 sparse matrix of type '' + with 7 stored elements in Compressed Sparse Row format> + >>> indi.todense() + matrix([[1, 0, 0], + [1, 0, 0], + [0, 0, 1], + [0, 1, 0], + [0, 1, 0], + [0, 0, 1], + [1, 0, 0]], dtype=int8) + + + current behavior with missing groups + >>> g = np.array([0, 0, 2, 0, 2, 0]) + >>> indi = dummy_sparse(g) + >>> indi.todense() + matrix([[1, 0, 0], + [1, 0, 0], + [0, 0, 1], + [1, 0, 0], + [0, 0, 1], + [1, 0, 0]], dtype=int8) + """ + from scipy import sparse + + indptr = np.arange(len(groups)+1) + data = np.ones(len(groups), dtype=np.int8) + indi = sparse.csr_matrix((data, groups, indptr)) + + return indi + + +class Group: + + def __init__(self, group, name=''): + + # self.group = np.asarray(group) # TODO: use checks in combine_indices + self.name = name + uni, uni_idx, uni_inv = combine_indices(group) + + # TODO: rename these to something easier to remember + self.group_int, self.uni_idx, self.uni = uni, uni_idx, uni_inv + + self.n_groups = len(self.uni) + + # put this here so they can be overwritten before calling labels + self.separator = '.' + self.prefix = self.name + if self.prefix: + self.prefix = self.prefix + '=' + + # cache decorator + def counts(self): + return np.bincount(self.group_int) + + # cache_decorator + def labels(self): + # is this only needed for product of groups (intersection)? + prefix = self.prefix + uni = self.uni + sep = self.separator + + if uni.ndim > 1: + label = [(prefix+sep.join(['%s']*len(uni[0]))) % tuple(ii) + for ii in uni] + else: + label = [prefix + '%s' % ii for ii in uni] + return label + + def dummy(self, drop_idx=None, sparse=False, dtype=int): + """ + drop_idx is only available if sparse=False + + drop_idx is supposed to index into uni + """ + uni = self.uni + if drop_idx is not None: + idx = lrange(len(uni)) + del idx[drop_idx] + uni = uni[idx] + + group = self.group + + if not sparse: + return (group[:, None] == uni[None, :]).astype(dtype) + else: + return dummy_sparse(self.group_int) + + def interaction(self, other): + if isinstance(other, self.__class__): + other = other.group + return self.__class__((self, other)) + + def group_sums(self, x, use_bincount=True): + return group_sums(x, self.group_int, use_bincount=use_bincount) + + def group_demean(self, x, use_bincount=True): + nobs = float(len(x)) + means_g = group_sums(x / nobs, self.group_int, + use_bincount=use_bincount) + x_demeaned = x - means_g[self.group_int] # check reverse_index? + return x_demeaned, means_g + + +class GroupSorted(Group): + def __init__(self, group, name=''): + super(self.__class__, self).__init__(group, name=name) + + idx = (np.nonzero(np.diff(group))[0]+1).tolist() + self.groupidx = lzip([0] + idx, idx + [len(group)]) + + def group_iter(self): + for low, upp in self.groupidx: + yield slice(low, upp) + + def lag_indices(self, lag): + """return the index array for lagged values + + Warning: if k is larger then the number of observations for an + individual, then no values for that individual are returned. + + TODO: for the unbalanced case, I should get the same truncation for + the array with lag=0. From the return of lag_idx we would not know + which individual is missing. + + TODO: do I want the full equivalent of lagmat in tsa? + maxlag or lag or lags. + + not tested yet + """ + lag_idx = np.asarray(self.groupidx)[:, 1] - lag # asarray or already? + mask_ok = (lag <= lag_idx) + # still an observation that belongs to the same individual + + return lag_idx[mask_ok] + + +def _is_hierarchical(x): + """ + Checks if the first item of an array-like object is also array-like + If so, we have a MultiIndex and returns True. Else returns False. + """ + item = x[0] + # is there a better way to do this? + if isinstance(item, (list, tuple, np.ndarray, pd.Series, pd.DataFrame)): + return True + else: + return False + + +def _make_hierarchical_index(index, names): + return MultiIndex.from_tuples(*[index], names=names) + + +def _make_generic_names(index): + n_names = len(index.names) + pad = str(len(str(n_names))) # number of digits + return [("group{0:0"+pad+"}").format(i) for i in range(n_names)] + + +class Grouping: + def __init__(self, index, names=None): + """ + index : index-like + Can be pandas MultiIndex or Index or array-like. If array-like + and is a MultipleIndex (more than one grouping variable), + groups are expected to be in each row. E.g., [('red', 1), + ('red', 2), ('green', 1), ('green', 2)] + names : list or str, optional + The names to use for the groups. Should be a str if only + one grouping variable is used. + + Notes + ----- + If index is already a pandas Index then there is no copy. + """ + if isinstance(index, (Index, MultiIndex)): + if names is not None: + if hasattr(index, 'set_names'): # newer pandas + index.set_names(names, inplace=True) + else: + index.names = names + self.index = index + else: # array_like + if _is_hierarchical(index): + self.index = _make_hierarchical_index(index, names) + else: + self.index = Index(index, name=names) + if names is None: + names = _make_generic_names(self.index) + if hasattr(self.index, 'set_names'): + self.index.set_names(names, inplace=True) + else: + self.index.names = names + + self.nobs = len(self.index) + self.nlevels = len(self.index.names) + self.slices = None + + @property + def index_shape(self): + if hasattr(self.index, 'levshape'): + return self.index.levshape + else: + return self.index.shape + + @property + def levels(self): + if hasattr(self.index, 'levels'): + return self.index.levels + else: + return pd.Categorical(self.index).levels + + @property + def labels(self): + # this was index_int, but that's not a very good name... + codes = getattr(self.index, 'codes', None) + if codes is None: + if hasattr(self.index, 'labels'): + codes = self.index.labels + else: + codes = pd.Categorical(self.index).codes[None] + return codes + + @property + def group_names(self): + return self.index.names + + def reindex(self, index=None, names=None): + """ + Resets the index in-place. + """ + # NOTE: this is not of much use if the rest of the data does not change + # This needs to reset cache + if names is None: + names = self.group_names + self = Grouping(index, names) + + def get_slices(self, level=0): + """ + Sets the slices attribute to be a list of indices of the sorted + groups for the first index level. I.e., self.slices[0] is the + index where each observation is in the first (sorted) group. + """ + # TODO: refactor this + groups = self.index.get_level_values(level).unique() + groups = np.array(groups) + groups.sort() + if isinstance(self.index, MultiIndex): + self.slices = [self.index.get_loc_level(x, level=level)[0] + for x in groups] + else: + self.slices = [self.index.get_loc(x) for x in groups] + + def count_categories(self, level=0): + """ + Sets the attribute counts to equal the bincount of the (integer-valued) + labels. + """ + # TODO: refactor this not to set an attribute. Why would we do this? + self.counts = np.bincount(self.labels[level]) + + def check_index(self, is_sorted=True, unique=True, index=None): + """Sanity checks""" + if not index: + index = self.index + if is_sorted: + test = pd.DataFrame(lrange(len(index)), index=index) + test_sorted = test.sort() + if not test.index.equals(test_sorted.index): + raise Exception('Data is not be sorted') + if unique: + if len(index) != len(index.unique()): + raise Exception('Duplicate index entries') + + def sort(self, data, index=None): + """Applies a (potentially hierarchical) sort operation on a numpy array + or pandas series/dataframe based on the grouping index or a + user-supplied index. Returns an object of the same type as the + original data as well as the matching (sorted) Pandas index. + """ + + if index is None: + index = self.index + if data_util._is_using_ndarray_type(data, None): + if data.ndim == 1: + out = pd.Series(data, index=index, copy=True) + out = out.sort_index() + else: + out = pd.DataFrame(data, index=index) + out = out.sort_index(inplace=False) # copies + return np.array(out), out.index + elif data_util._is_using_pandas(data, None): + out = data + out = out.reindex(index) # copies? + out = out.sort_index() + return out, out.index + else: + msg = 'data must be a Numpy array or a Pandas Series/DataFrame' + raise ValueError(msg) + + def transform_dataframe(self, dataframe, function, level=0, **kwargs): + """Apply function to each column, by group + Assumes that the dataframe already has a proper index""" + if dataframe.shape[0] != self.nobs: + raise Exception('dataframe does not have the same shape as index') + out = dataframe.groupby(level=level).apply(function, **kwargs) + if 1 in out.shape: + return np.ravel(out) + else: + return np.array(out) + + def transform_array(self, array, function, level=0, **kwargs): + """Apply function to each column, by group + """ + if array.shape[0] != self.nobs: + raise Exception('array does not have the same shape as index') + dataframe = pd.DataFrame(array, index=self.index) + return self.transform_dataframe(dataframe, function, level=level, + **kwargs) + + def transform_slices(self, array, function, level=0, **kwargs): + """Apply function to each group. Similar to transform_array but does + not coerce array to a DataFrame and back and only works on a 1D or 2D + numpy array. function is called function(group, group_idx, **kwargs). + """ + array = np.asarray(array) + if array.shape[0] != self.nobs: + raise Exception('array does not have the same shape as index') + # always reset because level is given. need to refactor this. + self.get_slices(level=level) + processed = [] + for s in self.slices: + if array.ndim == 2: + subset = array[s, :] + elif array.ndim == 1: + subset = array[s] + processed.append(function(subset, s, **kwargs)) + processed = np.array(processed) + return processed.reshape(-1, processed.shape[-1]) + + # TODO: this is not general needs to be a PanelGrouping object + def dummies_time(self): + self.dummy_sparse(level=1) + return self._dummies + + def dummies_groups(self, level=0): + self.dummy_sparse(level=level) + return self._dummies + + def dummy_sparse(self, level=0): + """create a sparse indicator from a group array with integer labels + + Parameters + ---------- + groups : ndarray, int, 1d (nobs,) + An array of group indicators for each observation. Group levels + are assumed to be defined as consecutive integers, i.e. + range(n_groups) where n_groups is the number of group levels. + A group level with no observations for it will still produce a + column of zeros. + + Returns + ------- + indi : ndarray, int8, 2d (nobs, n_groups) + an indicator array with one row per observation, that has 1 in the + column of the group level for that observation + + Examples + -------- + + >>> g = np.array([0, 0, 2, 1, 1, 2, 0]) + >>> indi = dummy_sparse(g) + >>> indi + <7x3 sparse matrix of type '' + with 7 stored elements in Compressed Sparse Row format> + >>> indi.todense() + matrix([[1, 0, 0], + [1, 0, 0], + [0, 0, 1], + [0, 1, 0], + [0, 1, 0], + [0, 0, 1], + [1, 0, 0]], dtype=int8) + + + current behavior with missing groups + >>> g = np.array([0, 0, 2, 0, 2, 0]) + >>> indi = dummy_sparse(g) + >>> indi.todense() + matrix([[1, 0, 0], + [1, 0, 0], + [0, 0, 1], + [1, 0, 0], + [0, 0, 1], + [1, 0, 0]], dtype=int8) + """ + indi = dummy_sparse(self.labels[level]) + self._dummies = indi diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tools/print_version.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tools/print_version.py new file mode 100644 index 0000000000000000000000000000000000000000..bd2d4224d398b427d381ac36518b594aabbbe080 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tools/print_version.py @@ -0,0 +1,290 @@ +#!/usr/bin/env python +from functools import reduce +import sys +from os.path import dirname + + +def safe_version(module, attr='__version__', *others): + if not isinstance(attr, list): + attr = [attr] + try: + return reduce(getattr, [module] + attr) + except AttributeError: + if others: + return safe_version(module, others[0], *others[1:]) + return "Cannot detect version" + + +def _show_versions_only(): + print("\nINSTALLED VERSIONS") + print("------------------") + print("Python: %d.%d.%d.%s.%s" % sys.version_info[:]) + try: + import os + (sysname, nodename, release, version, machine) = os.uname() + print(f"OS: {sysname} {release} {version} {machine}") + print("byteorder: %s" % sys.byteorder) + print("LC_ALL: %s" % os.environ.get('LC_ALL', "None")) + print("LANG: %s" % os.environ.get('LANG', "None")) + except: + pass + try: + import statsmodels + has_sm = True + except ImportError: + has_sm = False + + print('\nstatsmodels\n===========\n') + if has_sm: + print('Installed: %s' % safe_version(statsmodels)) + else: + print('Not installed') + + print("\nRequired Dependencies\n=====================\n") + try: + import Cython + print("cython: %s" % safe_version(Cython)) + except ImportError: + print("cython: Not installed") + + try: + import numpy + print("numpy: %s" % safe_version(numpy, ['version', 'version'])) + except ImportError: + print("numpy: Not installed") + + try: + import scipy + print("scipy: %s" % safe_version(scipy, ['version', 'version'])) + except ImportError: + print("scipy: Not installed") + + try: + import pandas + print("pandas: %s" % safe_version(pandas)) + except ImportError: + print("pandas: Not installed") + + try: + import dateutil + print(" dateutil: %s" % safe_version(dateutil)) + except ImportError: + print(" dateutil: not installed") + + try: + import patsy + print("patsy: %s" % safe_version(patsy)) + except ImportError: + print("patsy: Not installed") + + print("\nOptional Dependencies\n=====================\n") + + try: + import matplotlib as mpl + print("matplotlib: %s" % safe_version(mpl)) + except ImportError: + print("matplotlib: Not installed") + + try: + from cvxopt import info + print("cvxopt: %s" % safe_version(info, 'version')) + except ImportError: + print("cvxopt: Not installed") + + try: + import joblib + print("joblib: %s " % (safe_version(joblib))) + except ImportError: + print("joblib: Not installed") + + print("\nDeveloper Tools\n================\n") + + try: + import IPython + print("IPython: %s" % safe_version(IPython)) + except ImportError: + print("IPython: Not installed") + try: + import jinja2 + print(" jinja2: %s" % safe_version(jinja2)) + except ImportError: + print(" jinja2: Not installed") + + try: + import sphinx + print("sphinx: %s" % safe_version(sphinx)) + except ImportError: + print("sphinx: Not installed") + + try: + import pygments + print(" pygments: %s" % safe_version(pygments)) + except ImportError: + print(" pygments: Not installed") + + try: + import pytest + print(f"pytest: {safe_version(pytest)} ({dirname(pytest.__file__)})") + except ImportError: + print("pytest: Not installed") + + try: + import virtualenv + print("virtualenv: %s" % safe_version(virtualenv)) + except ImportError: + print("virtualenv: Not installed") + + print("\n") + + +def show_versions(show_dirs=True): + """ + List the versions of statsmodels and any installed dependencies + + Parameters + ---------- + show_dirs : bool + Flag indicating to show module locations + """ + if not show_dirs: + _show_versions_only() + print("\nINSTALLED VERSIONS") + print("------------------") + print("Python: %d.%d.%d.%s.%s" % sys.version_info[:]) + try: + import os + (sysname, nodename, release, version, machine) = os.uname() + print(f"OS: {sysname} {release} {version} {machine}") + print("byteorder: %s" % sys.byteorder) + print("LC_ALL: %s" % os.environ.get('LC_ALL', "None")) + print("LANG: %s" % os.environ.get('LANG', "None")) + except: + pass + + try: + import statsmodels + has_sm = True + except ImportError: + has_sm = False + + print('\nstatsmodels\n===========\n') + if has_sm: + print('Installed: {} ({})'.format(safe_version(statsmodels), + dirname(statsmodels.__file__))) + else: + print('Not installed') + + print("\nRequired Dependencies\n=====================\n") + try: + import Cython + print("cython: {} ({})".format(safe_version(Cython), + dirname(Cython.__file__))) + except ImportError: + print("cython: Not installed") + + try: + import numpy + print("numpy: {} ({})".format(safe_version(numpy, ['version', 'version']), + dirname(numpy.__file__))) + except ImportError: + print("numpy: Not installed") + + try: + import scipy + print("scipy: {} ({})".format(safe_version(scipy, ['version', 'version']), + dirname(scipy.__file__))) + except ImportError: + print("scipy: Not installed") + + try: + import pandas + print("pandas: {} ({})".format(safe_version(pandas, ['version', 'version'], + '__version__'), + dirname(pandas.__file__))) + except ImportError: + print("pandas: Not installed") + + try: + import dateutil + print(" dateutil: {} ({})".format(safe_version(dateutil), + dirname(dateutil.__file__))) + except ImportError: + print(" dateutil: not installed") + + try: + import patsy + print("patsy: {} ({})".format(safe_version(patsy), + dirname(patsy.__file__))) + except ImportError: + print("patsy: Not installed") + + print("\nOptional Dependencies\n=====================\n") + + try: + import matplotlib as mpl + print("matplotlib: {} ({})".format(safe_version(mpl), + dirname(mpl.__file__))) + print(" backend: %s " % mpl.rcParams['backend']) + except ImportError: + print("matplotlib: Not installed") + + try: + from cvxopt import info + print("cvxopt: {} ({})".format(safe_version(info, 'version'), + dirname(info.__file__))) + except ImportError: + print("cvxopt: Not installed") + + try: + import joblib + print("joblib: {} ({})".format(safe_version(joblib), + dirname(joblib.__file__))) + except ImportError: + print("joblib: Not installed") + + print("\nDeveloper Tools\n================\n") + + try: + import IPython + print("IPython: {} ({})".format(safe_version(IPython), + dirname(IPython.__file__))) + except ImportError: + print("IPython: Not installed") + try: + import jinja2 + print(" jinja2: {} ({})".format(safe_version(jinja2), + dirname(jinja2.__file__))) + except ImportError: + print(" jinja2: Not installed") + + try: + import sphinx + print("sphinx: {} ({})".format(safe_version(sphinx), + dirname(sphinx.__file__))) + except ImportError: + print("sphinx: Not installed") + + try: + import pygments + print(" pygments: {} ({})".format(safe_version(pygments), + dirname(pygments.__file__))) + except ImportError: + print(" pygments: Not installed") + + try: + import pytest + print(f"pytest: {safe_version(pytest)} ({dirname(pytest.__file__)})") + except ImportError: + print("pytest: Not installed") + + try: + import virtualenv + print("virtualenv: {} ({})".format(safe_version(virtualenv), + dirname(virtualenv.__file__))) + except ImportError: + print("virtualenv: Not installed") + + print("\n") + +if __name__ == "__main__": + show_versions() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tools/rng_qrng.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tools/rng_qrng.py new file mode 100644 index 0000000000000000000000000000000000000000..e36ee44bbd612471ec613a27e8144d6338d75704 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tools/rng_qrng.py @@ -0,0 +1,55 @@ +import numpy as np +import scipy.stats as stats + +_future_warn = """\ +Passing `None` as the seed currently return the NumPy singleton RandomState +(np.random.mtrand._rand). After release 0.13 this will change to using the +default generator provided by NumPy (np.random.default_rng()). If you need +reproducible draws, you should pass a seeded np.random.Generator, e.g., + +import numpy as np +seed = 32839283923801 +rng = np.random.default_rng(seed)" +""" + + +def check_random_state(seed=None): + """ + Turn `seed` into a random number generator. + + Parameters + ---------- + seed : {None, int, array_like[ints], `numpy.random.Generator`, + `numpy.random.RandomState`, `scipy.stats.qmc.QMCEngine`}, optional + + If `seed` is None fresh, unpredictable entropy will be pulled + from the OS and `numpy.random.Generator` is used. + If `seed` is an int or ``array_like[ints]``, a new ``Generator`` + instance is used, seeded with `seed`. + If `seed` is already a ``Generator``, ``RandomState`` or + `scipy.stats.qmc.QMCEngine` instance then + that instance is used. + + `scipy.stats.qmc.QMCEngine` requires SciPy >=1.7. It also means + that the generator only have the method ``random``. + + Returns + ------- + seed : {`numpy.random.Generator`, `numpy.random.RandomState`, + `scipy.stats.qmc.QMCEngine`} + + Random number generator. + """ + if hasattr(stats, "qmc") and \ + isinstance(seed, stats.qmc.QMCEngine): + return seed + elif isinstance(seed, np.random.RandomState): + return seed + elif isinstance(seed, np.random.Generator): + return seed + elif seed is not None: + return np.random.default_rng(seed) + else: + import warnings + warnings.warn(_future_warn, FutureWarning) + return np.random.mtrand._rand diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tools/rootfinding.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tools/rootfinding.py new file mode 100644 index 0000000000000000000000000000000000000000..cb403165385b78dd0db8d7947e9cba7e654c1611 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tools/rootfinding.py @@ -0,0 +1,221 @@ +""" + +Created on Mon Mar 18 15:48:23 2013 +Author: Josef Perktold + +TODO: + - test behavior if nans or infs are encountered during the evaluation. + now partially robust to nans, if increasing can be determined or is given. + - rewrite core loop to use for...except instead of while. + +""" +import numpy as np +from scipy import optimize + +from statsmodels.tools.testing import Holder + +DEBUG = False + + +# based on scipy.stats.distributions._ppf_single_call +def brentq_expanding(func, low=None, upp=None, args=(), xtol=1e-5, + start_low=None, start_upp=None, increasing=None, + max_it=100, maxiter_bq=100, factor=10, + full_output=False): + '''find the root of a function in one variable by expanding and brentq + + Assumes function ``func`` is monotonic. + + Parameters + ---------- + func : callable + function for which we find the root ``x`` such that ``func(x) = 0`` + low : float or None + lower bound for brentq + upp : float or None + upper bound for brentq + args : tuple + optional additional arguments for ``func`` + xtol : float + parameter x tolerance given to brentq + start_low : float (positive) or None + starting bound for expansion with increasing ``x``. It needs to be + positive. If None, then it is set to 1. + start_upp : float (negative) or None + starting bound for expansion with decreasing ``x``. It needs to be + negative. If None, then it is set to -1. + increasing : bool or None + If None, then the function is evaluated at the initial bounds to + determine wether the function is increasing or not. If increasing is + True (False), then it is assumed that the function is monotonically + increasing (decreasing). + max_it : int + maximum number of expansion steps. + maxiter_bq : int + maximum number of iterations of brentq. + factor : float + expansion factor for step of shifting the bounds interval, default is + 10. + full_output : bool, optional + If full_output is False, the root is returned. If full_output is True, + the return value is (x, r), where x is the root, and r is a + RootResults object. + + + Returns + ------- + x : float + root of the function, value at which ``func(x) = 0``. + info : RootResult (optional) + returned if ``full_output`` is True. + attributes: + + - start_bounds : starting bounds for expansion stage + - brentq_bounds : bounds used with ``brentq`` + - iterations_expand : number of iterations in expansion stage + - converged : True if brentq converged. + - flag : return status, 'converged' if brentq converged + - function_calls : number of function calls by ``brentq`` + - iterations : number of iterations in ``brentq`` + + + Notes + ----- + If increasing is None, then whether the function is monotonically + increasing or decreasing is inferred from evaluating the function at the + initial bounds. This can fail if there is numerically no variation in the + data in this range. In this case, using different starting bounds or + directly specifying ``increasing`` can make it possible to move the + expansion in the right direction. + + If + + ''' + # TODO: rtol is missing, what does it do? + left, right = low, upp # alias + + # start_upp first because of possible sl = -1 > upp + if upp is not None: + su = upp + elif start_upp is not None: + if start_upp < 0: + raise ValueError('start_upp needs to be positive') + su = start_upp + else: + su = 1. + + if low is not None: + sl = low + elif start_low is not None: + if start_low > 0: + raise ValueError('start_low needs to be negative') + sl = start_low + else: + sl = min(-1., su - 1.) + + # need sl < su + if upp is None: + su = max(su, sl + 1.) + + # increasing or not ? + if ((low is None) or (upp is None)) and increasing is None: + assert sl < su # check during development + f_low = func(sl, *args) + f_upp = func(su, *args) + + # special case for F-distribution (symmetric around zero for effect + # size) + # chisquare also takes an indefinite time (did not wait see if it + # returns) + if np.max(np.abs(f_upp - f_low)) < 1e-15 and sl == -1 and su == 1: + sl = 1e-8 + f_low = func(sl, *args) + increasing = (f_low < f_upp) + + # possibly func returns nan + delta = su - sl + if np.isnan(f_low): + # try just 3 points to find ``increasing`` + # do not change sl because brentq can handle one nan bound + for fraction in [0.25, 0.5, 0.75]: + sl_ = sl + fraction * delta + f_low = func(sl_, *args) + if not np.isnan(f_low): + break + else: + raise ValueError('could not determine whether function is ' + + 'increasing based on starting interval.' + + '\nspecify increasing or change starting ' + + 'bounds') + if np.isnan(f_upp): + for fraction in [0.25, 0.5, 0.75]: + su_ = su + fraction * delta + f_upp = func(su_, *args) + if not np.isnan(f_upp): + break + else: + raise ValueError('could not determine whether function is' + + 'increasing based on starting interval.' + + '\nspecify increasing or change starting ' + + 'bounds') + + increasing = (f_low < f_upp) + + if not increasing: + sl, su = su, sl + left, right = right, left + + n_it = 0 + if left is None and sl != 0: + left = sl + while func(left, *args) > 0: + # condition is also false if func returns nan + right = left + left *= factor + if n_it >= max_it: + break + n_it += 1 + # left is now such that func(left) < q + if right is None and su != 0: + right = su + while func(right, *args) < 0: + left = right + right *= factor + if n_it >= max_it: + break + n_it += 1 + # right is now such that func(right) > q + + if n_it >= max_it: + # print('Warning: max_it reached') + # TODO: use Warnings, Note: brentq might still work even with max_it + f_low = func(sl, *args) + f_upp = func(su, *args) + if np.isnan(f_low) and np.isnan(f_upp): + # can we still get here? + raise ValueError('max_it reached' + + '\nthe function values at boths bounds are NaN' + + '\nchange the starting bounds, set bounds' + + 'or increase max_it') + + res = optimize.brentq(func, left, right, args=args, + xtol=xtol, maxiter=maxiter_bq, + full_output=full_output) + if full_output: + val = res[0] + info = Holder( + # from brentq + root=res[1].root, + iterations=res[1].iterations, + function_calls=res[1].function_calls, + converged=res[1].converged, + flag=res[1].flag, + # ours: + iterations_expand=n_it, + start_bounds=(sl, su), + brentq_bounds=(left, right), + increasing=increasing, + ) + return val, info + else: + return res diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tools/sequences.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tools/sequences.py new file mode 100644 index 0000000000000000000000000000000000000000..de409ee27ea4081936f345d9665d5d20f923002a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tools/sequences.py @@ -0,0 +1,212 @@ +"""Low discrepancy sequence tools.""" +import numpy as np + + +def discrepancy(sample, bounds=None): + """Discrepancy. + + Compute the centered discrepancy on a given sample. + It is a measure of the uniformity of the points in the parameter space. + The lower the value is, the better the coverage of the parameter space is. + + Parameters + ---------- + sample : array_like (n_samples, k_vars) + The sample to compute the discrepancy from. + bounds : tuple or array_like ([min, k_vars], [max, k_vars]) + Desired range of transformed data. The transformation apply the bounds + on the sample and not the theoretical space, unit cube. Thus min and + max values of the sample will coincide with the bounds. + + Returns + ------- + discrepancy : float + Centered discrepancy. + + References + ---------- + [1] Fang et al. "Design and modeling for computer experiments", + Computer Science and Data Analysis Series Science and Data Analysis + Series, 2006. + """ + sample = np.asarray(sample) + n_sample, dim = sample.shape + + # Sample scaling from bounds to unit hypercube + if bounds is not None: + min_ = bounds.min(axis=0) + max_ = bounds.max(axis=0) + sample = (sample - min_) / (max_ - min_) + + abs_ = abs(sample - 0.5) + disc1 = np.sum(np.prod(1 + 0.5 * abs_ - 0.5 * abs_ ** 2, axis=1)) + + prod_arr = 1 + for i in range(dim): + s0 = sample[:, i] + prod_arr *= (1 + + 0.5 * abs(s0[:, None] - 0.5) + 0.5 * abs(s0 - 0.5) - + 0.5 * abs(s0[:, None] - s0)) + disc2 = prod_arr.sum() + + c2 = ((13.0 / 12.0) ** dim - 2.0 / n_sample * disc1 + + 1.0 / (n_sample ** 2) * disc2) + + return c2 + + +def primes_from_2_to(n): + """Prime numbers from 2 to *n*. + + Parameters + ---------- + n : int + Sup bound with ``n >= 6``. + + Returns + ------- + primes : list(int) + Primes in ``2 <= p < n``. + + References + ---------- + [1] `StackOverflow `_. + """ + sieve = np.ones(n // 3 + (n % 6 == 2), dtype=bool) + for i in range(1, int(n ** 0.5) // 3 + 1): + if sieve[i]: + k = 3 * i + 1 | 1 + sieve[k * k // 3::2 * k] = False + sieve[k * (k - 2 * (i & 1) + 4) // 3::2 * k] = False + return np.r_[2, 3, ((3 * np.nonzero(sieve)[0][1:] + 1) | 1)] + + +def n_primes(n): + """List of the n-first prime numbers. + + Parameters + ---------- + n : int + Number of prime numbers wanted. + + Returns + ------- + primes : list(int) + List of primes. + """ + primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, + 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, + 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, + 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, + 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, + 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, + 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, + 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, + 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, + 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, + 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, + 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, + 953, 967, 971, 977, 983, 991, 997][:n] + + if len(primes) < n: + big_number = 10 + while 'Not enought primes': + primes = primes_from_2_to(big_number)[:n] + if len(primes) == n: + break + big_number += 1000 + + return primes + + +def van_der_corput(n_sample, base=2, start_index=0): + """Van der Corput sequence. + + Pseudo-random number generator based on a b-adic expansion. + + Parameters + ---------- + n_sample : int + Number of element of the sequence. + base : int + Base of the sequence. + start_index : int + Index to start the sequence from. + + Returns + ------- + sequence : list (n_samples,) + Sequence of Van der Corput. + """ + sequence = [] + for i in range(start_index, start_index + n_sample): + n_th_number, denom = 0., 1. + quotient = i + while quotient > 0: + quotient, remainder = divmod(quotient, base) + denom *= base + n_th_number += remainder / denom + sequence.append(n_th_number) + + return sequence + + +def halton(dim, n_sample, bounds=None, start_index=0): + """Halton sequence. + + Pseudo-random number generator that generalize the Van der Corput sequence + for multiple dimensions. Halton sequence use base-two Van der Corput + sequence for the first dimension, base-three for its second and base-n for + its n-dimension. + + Parameters + ---------- + dim : int + Dimension of the parameter space. + n_sample : int + Number of samples to generate in the parametr space. + bounds : tuple or array_like ([min, k_vars], [max, k_vars]) + Desired range of transformed data. The transformation apply the bounds + on the sample and not the theoretical space, unit cube. Thus min and + max values of the sample will coincide with the bounds. + start_index : int + Index to start the sequence from. + + Returns + ------- + sequence : array_like (n_samples, k_vars) + Sequence of Halton. + + References + ---------- + [1] Halton, "On the efficiency of certain quasi-random sequences of points + in evaluating multi-dimensional integrals", Numerische Mathematik, 1960. + + Examples + -------- + Generate samples from a low discrepancy sequence of Halton. + + >>> from statsmodels.tools import sequences + >>> sample = sequences.halton(dim=2, n_sample=5) + + Compute the quality of the sample using the discrepancy criterion. + + >>> uniformity = sequences.discrepancy(sample) + + If some wants to continue an existing design, extra points can be obtained. + + >>> sample_continued = sequences.halton(dim=2, n_sample=5, start_index=5) + """ + base = n_primes(dim) + + # Generate a sample using a Van der Corput sequence per dimension. + sample = [van_der_corput(n_sample + 1, bdim, start_index) for bdim in base] + sample = np.array(sample).T[1:] + + # Sample scaling from unit hypercube to feature range + if bounds is not None: + min_ = bounds.min(axis=0) + max_ = bounds.max(axis=0) + sample = sample * (max_ - min_) + min_ + + return sample diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tools/sm_exceptions.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tools/sm_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..413ef8df691d3655a66e56f7a5eb0cd043effd39 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tools/sm_exceptions.py @@ -0,0 +1,260 @@ +""" +Contains custom errors and warnings. + +Errors should derive from Exception or another custom error. Custom errors are +only needed it standard errors, for example ValueError or TypeError, are not +accurate descriptions of the reason for the error. + +Warnings should derive from either an existing warning or another custom +warning, and should usually be accompanied by a sting using the format +warning_name_doc that services as a generic message to use when the warning is +raised. +""" + +import warnings + + +# Errors +class PerfectSeparationError(Exception): + """ + Error due to perfect prediction in discrete models + """ + + pass + + +class MissingDataError(Exception): + """ + Error raised if variables contain missing values when forbidden + """ + + pass + + +class X13NotFoundError(Exception): + """ + Error locating the X13 binary + """ + + pass + + +class X13Error(Exception): + """ + Error when running modes using X13 + """ + + pass + + +class ParseError(Exception): + """ + Error when parsing a docstring. + """ + + def __str__(self): + message = self.args[0] + if hasattr(self, "docstring"): + message = f"{message} in {self.docstring}" + return message + + +# Warning +class X13Warning(Warning): + """ + Unexpected conditions when using X13 + """ + pass + + +class IOWarning(RuntimeWarning): + """ + Resource not deleted + """ + + pass + + +class ModuleUnavailableWarning(Warning): + """ + Non-fatal import error + """ + pass + + +module_unavailable_doc = """ +The module {0} is not available. Cannot run in parallel. +""" + + +class ModelWarning(UserWarning): + """ + Base internal Warning class to simplify end-user filtering + """ + pass + + +class ConvergenceWarning(ModelWarning): + """ + Nonlinear optimizer failed to converge to a unique solution + """ + pass + + +convergence_doc = """ +Failed to converge on a solution. +""" + + +class CacheWriteWarning(ModelWarning): + """ + Attempting to write to a read-only cached value + """ + + pass + + +class IterationLimitWarning(ModelWarning): + """ + Iteration limit reached without convergence + """ + + pass + + +iteration_limit_doc = """ +Maximum iteration reached. +""" + + +class InvalidTestWarning(ModelWarning): + """ + Test not applicable to model + """ + + pass + + +class NotImplementedWarning(ModelWarning): + """ + Non-fatal function non-implementation + """ + + pass + + +class OutputWarning(ModelWarning): + """ + Function output contains atypical values + """ + + pass + + +class DomainWarning(ModelWarning): + """ + Variables are not compliant with required domain constraints + """ + + pass + + +class ValueWarning(ModelWarning): + """ + Non-fatal out-of-range value given + """ + + pass + + +class EstimationWarning(ModelWarning): + """ + Unexpected condition encountered during estimation + """ + + pass + + +class SingularMatrixWarning(ModelWarning): + """ + Non-fatal matrix inversion affects output results + """ + + pass + + +class HypothesisTestWarning(ModelWarning): + """ + Issue occurred when performing hypothesis test + """ + + pass + + +class InterpolationWarning(ModelWarning): + """ + Table granularity and limits restrict interpolation + """ + + pass + + +class PrecisionWarning(ModelWarning): + """ + Numerical implementation affects precision + """ + + pass + + +class SpecificationWarning(ModelWarning): + """ + Non-fatal model specification issue + """ + + pass + + +class HessianInversionWarning(ModelWarning): + """ + Hessian noninvertible and standard errors unavailable + """ + + pass + + +class CollinearityWarning(ModelWarning): + """ + Variables are highly collinear + """ + + pass + + +class PerfectSeparationWarning(ModelWarning): + """ + Perfect separation or prediction + """ + + pass + + +class InfeasibleTestError(RuntimeError): + """ + Test statistic cannot be computed + """ + + pass + + +recarray_exception = """ +recarray support has been removed from statsmodels. Use pandas DataFrames +for structured data. +""" + + +warnings.simplefilter("always", ModelWarning) +warnings.simplefilter("always", ConvergenceWarning) +warnings.simplefilter("always", CacheWriteWarning) +warnings.simplefilter("always", IterationLimitWarning) +warnings.simplefilter("always", InvalidTestWarning) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tools/transform_model.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tools/transform_model.py new file mode 100644 index 0000000000000000000000000000000000000000..63a8cd4214f399cb806147c119c9f5923cf943d5 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tools/transform_model.py @@ -0,0 +1,94 @@ +""" +Created on Tue May 27 13:23:24 2014 + +Author: Josef Perktold +License: BSD-3 + +""" + +import numpy as np + + +class StandardizeTransform: + """class to reparameterize a model for standardized exog + + Parameters + ---------- + data : array_like + data that is standardized along axis=0 + ddof : None or int + degrees of freedom for calculation of standard deviation. + default is 1, in contrast to numpy.std + const_idx : None or int + If None, then the presence of a constant is detected if the standard + deviation of a column is **equal** to zero. A constant column is + not transformed. If this is an integer, then the corresponding column + will not be transformed. + demean : bool, default is True + If demean is true, then the data will be demeaned, otherwise it will + only be rescaled. + + Notes + ----- + Warning: Not all options are tested and it is written for one use case. + API changes are expected. + + This can be used to transform only the design matrix, exog, in a model, + which is required in some discrete models when the endog cannot be rescaled + or demeaned. + The transformation is full rank and does not drop the constant. + """ + + def __init__(self, data, ddof=1, const_idx=None, demean=True): + data = np.asarray(data) + self.mean = data.mean(0) + self.scale = data.std(0, ddof=1) + + # do not transform a constant + if const_idx is None: + const_idx = np.nonzero(self.scale == 0)[0] + if len(const_idx) == 0: + const_idx = 'n' + else: + const_idx = int(np.squeeze(const_idx)) + + if const_idx != 'n': + self.mean[const_idx] = 0 + self.scale[const_idx] = 1 + + if demean is False: + self.mean = None + + self.const_idx = const_idx + + def transform(self, data): + """standardize the data using the stored transformation + """ + # could use scipy.stats.zscore instead + if self.mean is None: + return np.asarray(data) / self.scale + else: + return (np.asarray(data) - self.mean) / self.scale + + def transform_params(self, params): + """Transform parameters of the standardized model to the original model + + Parameters + ---------- + params : ndarray + parameters estimated with the standardized model + + Returns + ------- + params_new : ndarray + parameters transformed to the parameterization of the original + model + """ + + params_new = params / self.scale + if self.const_idx != 'n': + params_new[self.const_idx] -= (params_new * self.mean).sum() + + return params_new + + __call__ = transform diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tools/typing.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tools/typing.py new file mode 100644 index 0000000000000000000000000000000000000000..6643d562eed8b82d4568c77b10d2d73ad9d34c3e --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tools/typing.py @@ -0,0 +1,48 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Union +from collections.abc import Sequence + +from packaging.version import parse +from pandas import DataFrame, Series + +if TYPE_CHECKING: + import numpy as np + + if parse(np.__version__) < parse("1.22.0"): + raise NotImplementedError( + "NumPy 1.22.0 or later required for type checking" + ) + from numpy.typing import ( + ArrayLike as ArrayLike, + DTypeLike, + NDArray, + _FloatLike_co, + _UIntLike_co, + ) + + _ExtendedFloatLike_co = Union[_FloatLike_co, _UIntLike_co] + NumericArray = NDArray[Any, np.dtype[_ExtendedFloatLike_co]] + Float64Array = NDArray[Any, np.double] + ArrayLike1D = Union[Sequence[Union[float, int]], NumericArray, Series] + ArrayLike2D = Union[ + Sequence[Sequence[Union[float, int]]], NumericArray, DataFrame + ] +else: + ArrayLike = Any + DTypeLike = Any + Float64Array = Any + NumericArray = Any + ArrayLike1D = Any + ArrayLike2D = Any + NDArray = Any + +__all__ = [ + "ArrayLike", + "DTypeLike", + "Float64Array", + "ArrayLike1D", + "ArrayLike2D", + "NDArray", + "NumericArray", +] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tools/web.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tools/web.py new file mode 100644 index 0000000000000000000000000000000000000000..8722949370389958be71cb1e0c3b1c8dcd19fe8c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/tools/web.py @@ -0,0 +1,84 @@ +""" +Provides a function to open the system browser to either search or go directly +to a function's reference +""" +import webbrowser +from urllib.parse import urlencode + +BASE_URL = 'https://www.statsmodels.org/' + + +def _generate_url(func, stable): + """ + Parse inputs and return a correctly formatted URL or raises ValueError + if the input is not understandable + """ + url = BASE_URL + if stable: + url += 'stable/' + else: + url += 'devel/' + + if func is None: + return url + elif isinstance(func, str): + url += 'search.html?' + url += urlencode({'q': func}) + url += '&check_keywords=yes&area=default' + else: + try: + func = func + func_name = func.__name__ + func_module = func.__module__ + if not func_module.startswith('statsmodels.'): + raise ValueError('Function must be from statsmodels') + url += 'generated/' + url += func_module + '.' + func_name + '.html' + except AttributeError: + raise ValueError('Input not understood') + return url + + +def webdoc(func=None, stable=None): + """ + Opens a browser and displays online documentation + + Parameters + ---------- + func : {str, callable} + Either a string to search the documentation or a function + stable : bool + Flag indicating whether to use the stable documentation (True) or + the development documentation (False). If not provided, opens + the stable documentation if the current version of statsmodels is a + release + + Examples + -------- + >>> import statsmodels.api as sm + + Documentation site + + >>> sm.webdoc() + + Search for glm in docs + + >>> sm.webdoc('glm') + + Go to current generated help for OLS + + >>> sm.webdoc(sm.OLS, stable=False) + + Notes + ----- + By default, open stable documentation if the current version of + statsmodels is a release. Otherwise opens the development documentation. + + Uses the default system browser. + """ + from statsmodels._version import __version__ + + stable = __version__ if 'dev' not in __version__ else stable + url_or_error = _generate_url(func, stable) + webbrowser.open(url_or_error) + return None diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/treatment/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/treatment/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/treatment/treatment_effects.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/treatment/treatment_effects.py new file mode 100644 index 0000000000000000000000000000000000000000..8cb424e78ff4b0ab8b7672496bedea2325dc9ffb --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/statsmodels/treatment/treatment_effects.py @@ -0,0 +1,995 @@ +"""Treatment effect estimators + +follows largely Stata's teffects in Stata 13 manual + +Created on Tue Jun 9 22:45:23 2015 + +Author: Josef Perktold +License: BSD-3 + +currently available + + ATE POM_0 POM_1 +res_ipw 230.688598 3172.774059 3403.462658 +res_aipw -230.989201 3403.355253 3172.366052 +res_aipw_wls -227.195618 3403.250651 3176.055033 +res_ra -239.639211 3403.242272 3163.603060 +res_ipwra -229.967078 3403.335639 3173.368561 + + +Lots of todos, just the beginning, but most effects are available but not +standard errors, and no code structure that has a useful pattern + +see https://github.com/statsmodels/statsmodels/issues/2443 + +Note: script requires cattaneo2 data file from Stata 14, hardcoded file path +could be loaded with webuse + +""" + +import numpy as np +from statsmodels.compat.pandas import Substitution +from scipy.linalg import block_diag +from statsmodels.regression.linear_model import WLS +from statsmodels.sandbox.regression.gmm import GMM +from statsmodels.stats.contrast import ContrastResults +from statsmodels.tools.docstring import indent + + +def _mom_ate(params, endog, tind, prob, weighted=True): + """moment condition for average treatment effect + + This does not include a moment condition for potential outcome mean (POM). + + """ + w1 = (tind / prob) + w0 = (1. - tind) / (1. - prob) + if weighted: + w0 /= w0.mean() + w1 /= w1.mean() + + wdiff = w1 - w0 + + return endog * wdiff - params + + +def _mom_atm(params, endog, tind, prob, weighted=True): + """moment conditions for average treatment means (POM) + + moment conditions are POM0 and POM1 + """ + w1 = (tind / prob) + w0 = (1. - tind) / (1. - prob) + if weighted: + w1 /= w1.mean() + w0 /= w0.mean() + + return np.column_stack((endog * w0 - params[0], endog * w1 - params[1])) + + +def _mom_ols(params, endog, tind, prob, weighted=True): + """ + moment condition for average treatment mean based on OLS dummy regression + + moment conditions are POM0 and POM1 + + """ + w = tind / prob + (1-tind) / (1 - prob) + + treat_ind = np.column_stack((1 - tind, tind)) + mom = (w * (endog - treat_ind.dot(params)))[:, None] * treat_ind + + return mom + + +def _mom_ols_te(tm, endog, tind, prob, weighted=True): + """ + moment condition for average treatment mean based on OLS dummy regression + + first moment is ATE + second moment is POM0 (control) + + """ + w = tind / prob + (1-tind) / (1 - prob) + + treat_ind = np.column_stack((tind, np.ones(len(tind)))) + mom = (w * (endog - treat_ind.dot(tm)))[:, None] * treat_ind + + return mom + + +def _mom_olsex(params, model=None, exog=None, scale=None): + exog = exog if exog is not None else model.exog + fitted = model.predict(params, exog) + resid = model.endog - fitted + if scale is not None: + resid /= scale + mom = resid[:, None] * exog + return mom + + +def ate_ipw(endog, tind, prob, weighted=True, probt=None): + """average treatment effect based on basic inverse propensity weighting. + + """ + w1 = (tind / prob) + w0 = (1. - tind) / (1. - prob) + + if probt is not None: + w1 *= probt + w0 *= probt + + if weighted: + w0 /= w0.mean() + w1 /= w1.mean() + + wdiff = w1 - w0 + + return (endog * wdiff).mean(), (endog * w0).mean(), (endog * w1).mean() + + +class _TEGMMGeneric1(GMM): + """GMM class to get cov_params for treatment effects + + This combines moment conditions for the selection/treatment model and the + outcome model to get the standard errors for the treatment effect that + takes the first step estimation of the treatment model into account. + + this also matches standard errors of ATE and POM in Stata + + """ + + def __init__(self, endog, res_select, mom_outcome, exclude_tmoms=False, + **kwargs): + super().__init__(endog, None, None) + self.results_select = res_select + self.mom_outcome = mom_outcome + self.exclude_tmoms = exclude_tmoms + self.__dict__.update(kwargs) + + # add xnames so it's not None + # we don't have exog in init in this version + if self.data.xnames is None: + self.data.xnames = [] + + # need information about decomposition of parameters + if exclude_tmoms: + self.k_select = 0 + else: + self.k_select = len(res_select.model.data.param_names) + + if exclude_tmoms: + # fittedvalues is still linpred + self.prob = self.results_select.predict() + else: + self.prob = None + + def momcond(self, params): + k_outcome = len(params) - self.k_select + tm = params[:k_outcome] + p_tm = params[k_outcome:] + + tind = self.results_select.model.endog + + if self.exclude_tmoms: + prob = self.prob + else: + prob = self.results_select.model.predict(p_tm) + + moms_list = [] + mom_o = self.mom_outcome(tm, self.endog, tind, prob, weighted=True) + moms_list.append(mom_o) + + if not self.exclude_tmoms: + mom_t = self.results_select.model.score_obs(p_tm) + moms_list.append(mom_t) + + moms = np.column_stack(moms_list) + return moms + + +class _TEGMM(GMM): + """GMM class to get cov_params for treatment effects + + This combines moment conditions for the selection/treatment model and the + outcome model to get the standard errors for the treatment effect that + takes the first step estimation of the treatment model into account. + + this also matches standard errors of ATE and POM in Stata + + """ + + def __init__(self, endog, res_select, mom_outcome): + super().__init__(endog, None, None) + self.results_select = res_select + self.mom_outcome = mom_outcome + + # add xnames so it's not None + # we don't have exog in init in this version + if self.data.xnames is None: + self.data.xnames = [] + + def momcond(self, params): + tm = params[:2] + p_tm = params[2:] + + tind = self.results_select.model.endog + prob = self.results_select.model.predict(p_tm) + momt = self.mom_outcome(tm, self.endog, tind, prob) # weighted=True) + moms = np.column_stack((momt, + self.results_select.model.score_obs(p_tm))) + return moms + + +class _IPWGMM(_TEGMMGeneric1): + """ GMM for aipw treatment effect and potential outcome + + uses unweighted outcome regression + """ + + def momcond(self, params): + # Note: momcond in original order of observations + ra = self.teff + res_select = ra.results_select + tind = ra.treatment + endog = ra.model_pool.endog + effect_group = self.effect_group + + tm = params[:2] + ps = params[2:] + + prob_sel = np.asarray(res_select.model.predict(ps)) + prob_sel = np.clip(prob_sel, 0.01, 0.99) + prob = prob_sel + + if effect_group == "all": + probt = None + elif effect_group in [1, "treated"]: + probt = prob + elif effect_group in [0, "untreated", "control"]: + probt = 1 - prob + elif isinstance(effect_group, np.ndarray): + probt = probt + else: + raise ValueError("incorrect option for effect_group") + + w = tind / prob + (1 - tind) / (1 - prob) + # Are we supposed to use scaled weights? doesn't cloesely match Stata + # w1 = tind / prob + # w2 = (1 - tind) / (1 - prob) + # w = w1 / w1.sum() * tind.sum() + w2 / w2.sum() * (1 - tind).sum() + if probt is not None: + w *= probt + + treat_ind = np.column_stack((tind, np.ones(len(tind)))) + mm = (w * (endog - treat_ind.dot(tm)))[:, None] * treat_ind + + mom_select = res_select.model.score_obs(ps) + moms = np.column_stack((mm, mom_select)) + return moms + + +class _AIPWGMM(_TEGMMGeneric1): + """ GMM for aipw treatment effect and potential outcome + + uses unweighted outcome regression + """ + + def momcond(self, params): + ra = self.teff + treat_mask = ra.treat_mask + res_select = ra.results_select + + ppom = params[1] + mask = np.arange(len(params)) != 1 + params = params[mask] + + k = ra.results0.model.exog.shape[1] + pm = params[0] # ATE parameter + p0 = params[1:k+1] + p1 = params[k+1:2*k+1] + ps = params[2*k+1:] + mod0 = ra.results0.model + mod1 = ra.results1.model + # use reordered exog, endog so it matches sub models by group + exog = ra.exog_grouped + endog = ra.endog_grouped + + prob_sel = np.asarray(res_select.model.predict(ps)) + prob_sel = np.clip(prob_sel, 0.01, 0.99) + + prob0 = prob_sel[~treat_mask] + prob1 = prob_sel[treat_mask] + prob = np.concatenate((prob0, prob1)) + + # outcome models by treatment unweighted + fitted0 = mod0.predict(p0, exog) + mom0 = _mom_olsex(p0, model=mod0) + + fitted1 = mod1.predict(p1, exog) + mom1 = _mom_olsex(p1, model=mod1) + + mom_outcome = block_diag(mom0, mom1) + + # moments for target statistics, ATE and POM + tind = ra.treatment + tind = np.concatenate((tind[~treat_mask], tind[treat_mask])) + correct0 = (endog - fitted0) / (1 - prob) * (1 - tind) + correct1 = (endog - fitted1) / prob * tind + + tmean0 = fitted0 + correct0 + tmean1 = fitted1 + correct1 + ate = tmean1 - tmean0 + + mm = ate - pm + mpom = tmean0 - ppom + mm = np.column_stack((mm, mpom)) + + # Note: res_select has original data order, + # mom_outcome and mm use grouped observations + mom_select = res_select.model.score_obs(ps) + mom_select = np.concatenate((mom_select[~treat_mask], + mom_select[treat_mask]), axis=0) + + moms = np.column_stack((mm, mom_outcome, mom_select)) + return moms + + +class _AIPWWLSGMM(_TEGMMGeneric1): + """ GMM for aipw-wls treatment effect and potential outcome + + uses weighted outcome regression + """ + + def momcond(self, params): + ra = self.teff + treat_mask = ra.treat_mask + res_select = ra.results_select + + ppom = params[1] + mask = np.arange(len(params)) != 1 + params = params[mask] + + k = ra.results0.model.exog.shape[1] + pm = params[0] # ATE parameter + p0 = params[1:k+1] + p1 = params[k+1:2*k+1] + ps = params[-6:] + mod0 = ra.results0.model + mod1 = ra.results1.model + # use reordered exog, endog so it matches sub models by group + exog = ra.exog_grouped + endog = ra.endog_grouped + + # todo: need weights in outcome models + prob_sel = np.asarray(res_select.model.predict(ps)) + + prob_sel = np.clip(prob_sel, 0.001, 0.999) + + prob0 = prob_sel[~treat_mask] + prob1 = prob_sel[treat_mask] + prob = np.concatenate((prob0, prob1)) + + tind = 0 + ww0 = (1 - tind) / (1 - prob0) * ((1 - tind) / (1 - prob0) - 1) + tind = 1 + ww1 = tind / prob1 * (tind / prob1 - 1) + + # outcome models by treatment using IPW weights + fitted0 = mod0.predict(p0, exog) + mom0 = _mom_olsex(p0, model=mod0) * ww0[:, None] + + fitted1 = mod1.predict(p1, exog) + mom1 = _mom_olsex(p1, model=mod1) * ww1[:, None] + + mom_outcome = block_diag(mom0, mom1) + + # moments for target statistics, ATE and POM + tind = ra.treatment + tind = np.concatenate((tind[~treat_mask], tind[treat_mask])) + + correct0 = (endog - fitted0) / (1 - prob) * (1 - tind) + correct1 = (endog - fitted1) / prob * tind + + tmean0 = fitted0 + correct0 + tmean1 = fitted1 + correct1 + ate = tmean1 - tmean0 + + mm = ate - pm + mpom = tmean0 - ppom + mm = np.column_stack((mm, mpom)) + + # Note: res_select has original data order, + # mom_outcome and mm use grouped observations + mom_select = res_select.model.score_obs(ps) + mom_select = np.concatenate((mom_select[~treat_mask], + mom_select[treat_mask]), axis=0) + + moms = np.column_stack((mm, mom_outcome, mom_select)) + return moms + + +class _RAGMM(_TEGMMGeneric1): + """GMM for regression adjustment treatment effect and potential outcome + + uses unweighted outcome regression + """ + + def momcond(self, params): + ra = self.teff + + ppom = params[1] + mask = np.arange(len(params)) != 1 + params = params[mask] + + k = ra.results0.model.exog.shape[1] + pm = params[0] + p0 = params[1:k+1] + p1 = params[-k:] + mod0 = ra.results0.model + mod1 = ra.results1.model + # use reordered exog, endog so it matches sub models by group + exog = ra.exog_grouped + + fitted0 = mod0.predict(p0, exog) + mom0 = _mom_olsex(p0, model=mod0) + + fitted1 = mod1.predict(p1, exog) + mom1 = _mom_olsex(p1, model=mod1) + + momout = block_diag(mom0, mom1) + + mm = fitted1 - fitted0 - pm + mpom = fitted0 - ppom + mm = np.column_stack((mm, mpom)) + if self.probt is not None: + mm *= (self.probt / self.probt.mean())[:, None] + + moms = np.column_stack((mm, momout)) + return moms + + +class _IPWRAGMM(_TEGMMGeneric1): + """ GMM for ipwra treatment effect and potential outcome + """ + + def momcond(self, params): + ra = self.teff + treat_mask = ra.treat_mask + res_select = ra.results_select + + ppom = params[1] + mask = np.arange(len(params)) != 1 + params = params[mask] + + k = ra.results0.model.exog.shape[1] + pm = params[0] # ATE parameter + p0 = params[1:k+1] + p1 = params[k+1:2*k+1] + ps = params[-6:] + mod0 = ra.results0.model + mod1 = ra.results1.model + + # use reordered exog so it matches sub models by group + exog = ra.exog_grouped + tind = np.zeros(len(treat_mask)) + tind[-treat_mask.sum():] = 1 + + # selection probability by group, propensity score + prob_sel = np.asarray(res_select.model.predict(ps)) + prob_sel = np.clip(prob_sel, 0.001, 0.999) + prob0 = prob_sel[~treat_mask] + prob1 = prob_sel[treat_mask] + + effect_group = self.effect_group + if effect_group == "all": + w0 = 1 / (1 - prob0) + w1 = 1 / prob1 + sind = 1 + elif effect_group in [1, "treated"]: + w0 = prob0 / (1 - prob0) + w1 = prob1 / prob1 + # for averaging effect on treated + sind = tind / tind.mean() + elif effect_group in [0, "untreated", "control"]: + w0 = (1 - prob0) / (1 - prob0) + w1 = (1 - prob1) / prob1 + + sind = (1 - tind) + sind /= sind.mean() + else: + raise ValueError("incorrect option for effect_group") + + # outcome models by treatment using IPW weights + fitted0 = mod0.predict(p0, exog) + mom0 = _mom_olsex(p0, model=mod0) * w0[:, None] + + fitted1 = mod1.predict(p1, exog) + mom1 = _mom_olsex(p1, model=mod1) * w1[:, None] + + mom_outcome = block_diag(mom0, mom1) + + # moments for target statistics, ATE and POM + mm = (fitted1 - fitted0 - pm) * sind + mpom = (fitted0 - ppom) * sind + mm = np.column_stack((mm, mpom)) + + # Note: res_select has original data order, + # mom_outcome and mm use grouped observations + mom_select = res_select.model.score_obs(ps) + mom_select = np.concatenate((mom_select[~treat_mask], + mom_select[treat_mask]), axis=0) + + moms = np.column_stack((mm, mom_outcome, mom_select)) + return moms + + +class TreatmentEffectResults(ContrastResults): + """ + Results class for treatment effect estimation + + Parameters + ---------- + teff : instance of TreatmentEffect class + results_gmm : instance of GMMResults class + method : string + Method and estimator of treatment effect. + kwds: dict + Other keywords with additional information. + + Notes + ----- + This class is a subclass of ContrastResults and inherits methods like + summary, summary_frame and conf_int. Attributes correspond to a z-test + given by ``GMMResults.t_test``. + """ + + def __init__(self, teff, results_gmm, method, **kwds): + super().__init__() + k_params = len(results_gmm.params) + constraints = np.zeros((3, k_params)) + constraints[0, 0] = 1 + constraints[1, 1] = 1 + constraints[2, :2] = [1, 1] + tt = results_gmm.t_test(constraints) + self.__dict__.update(tt.__dict__) + self.teff = teff + self.results_gmm = results_gmm + self.method = method + # TODO: make those explicit? + self.__dict__.update(kwds) + + self.c_names = ["ATE", "POM0", "POM1"] + + +doc_params_returns = """\ +Parameters +---------- +return_results : bool + If True, then a results instance is returned. + If False, just ATE, POM0 and POM1 are returned. +effect_group : {"all", 0, 1} + ``effectgroup`` determines for which population the effects are + estimated. + If effect_group is "all", then sample average treatment effect and + potential outcomes are returned + If effect_group is 1 or "treated", then effects on treated are + returned. + If effect_group is 0, "treated" or "control", then effects on + untreated, i.e. control group, are returned. +disp : bool + Indicates whether the scipy optimizer should display the + optimization results + +Returns +------- +TreatmentEffectsResults instance or tuple (ATE, POM0, POM1) +""" + +doc_params_returns2 = """\ +Parameters +---------- +return_results : bool + If True, then a results instance is returned. + If False, just ATE, POM0 and POM1 are returned. +disp : bool + Indicates whether the scipy optimizer should display the + optimization results + +Returns +------- +TreatmentEffectsResults instance or tuple (ATE, POM0, POM1) +""" + + +class TreatmentEffect: + """ + Estimate average treatment effect under conditional independence + + .. versionadded:: 0.14.0 + + This class estimates treatment effect and potential outcome using 5 + different methods, ipw, ra, aipw, aipw-wls, ipw-ra. + Standard errors and inference are based on the joint GMM representation of + selection or treatment model, outcome model and effect functions. + + Parameters + ---------- + model : instance of a model class + The model class should contain endog and exog for the outcome model. + treatment : ndarray + indicator array for observations with treatment (1) or without (0) + results_select : results instance + The results instance for the treatment or selection model. + _cov_type : "HC0" + Internal keyword. The keyword oes not affect GMMResults which always + corresponds to HC0 standard errors. + kwds : keyword arguments + currently not used + + Notes + ----- + The outcome model is currently limited to a linear model based on OLS. + Other outcome models, like Logit and Poisson, will become available in + future. + + See `Treatment Effect notebook + <../examples/notebooks/generated/treatment_effect.html>`__ + for an overview. + + """ + + def __init__(self, model, treatment, results_select=None, _cov_type="HC0", + **kwds): + # Note _cov_type is only for preliminary estimators, + # cov in GMM alwasy corresponds to HC0 + self.__dict__.update(kwds) # currently not used + self.treatment = np.asarray(treatment) + self.treat_mask = treat_mask = (treatment == 1) + + if results_select is not None: + self.results_select = results_select + self.prob_select = results_select.predict() + + self.model_pool = model + endog = model.endog + exog = model.exog + self.nobs = endog.shape[0] + self._cov_type = _cov_type + + # no init keys are supported + mod0 = model.__class__(endog[~treat_mask], exog[~treat_mask]) + self.results0 = mod0.fit(cov_type=_cov_type) + mod1 = model.__class__(endog[treat_mask], exog[treat_mask]) + self.results1 = mod1.fit(cov_type=_cov_type) + # self.predict_mean0 = self.model_pool.predict(self.results0.params + # ).mean() + # self.predict_mean1 = self.model_pool.predict(self.results1.params + # ).mean() + + self.exog_grouped = np.concatenate((mod0.exog, mod1.exog), axis=0) + self.endog_grouped = np.concatenate((mod0.endog, mod1.endog), axis=0) + + @classmethod + def from_data(cls, endog, exog, treatment, model='ols', **kwds): + """create models from data + + not yet implemented + + """ + raise NotImplementedError + + def ipw(self, return_results=True, effect_group="all", disp=False): + """Inverse Probability Weighted treatment effect estimation. + + Parameters + ---------- + return_results : bool + If True, then a results instance is returned. + If False, just ATE, POM0 and POM1 are returned. + effect_group : {"all", 0, 1} + ``effectgroup`` determines for which population the effects are + estimated. + If effect_group is "all", then sample average treatment effect and + potential outcomes are returned. + If effect_group is 1 or "treated", then effects on treated are + returned. + If effect_group is 0, "treated" or "control", then effects on + untreated, i.e. control group, are returned. + disp : bool + Indicates whether the scipy optimizer should display the + optimization results + + Returns + ------- + TreatmentEffectsResults instance or tuple (ATE, POM0, POM1) + + See Also + -------- + TreatmentEffectsResults + """ + endog = self.model_pool.endog + tind = self.treatment + prob = self.prob_select + if effect_group == "all": + probt = None + elif effect_group in [1, "treated"]: + probt = prob + effect_group = 1 # standardize effect_group name + elif effect_group in [0, "untreated", "control"]: + probt = 1 - prob + effect_group = 0 # standardize effect_group name + elif isinstance(effect_group, np.ndarray): + probt = effect_group + effect_group = "user" # standardize effect_group name + else: + raise ValueError("incorrect option for effect_group") + + res_ipw = ate_ipw(endog, tind, prob, weighted=True, probt=probt) + + if not return_results: + return res_ipw + + # gmm = _TEGMMGeneric1(endog, self.results_select, _mom_ols_te, + # probt=probt) + gmm = _IPWGMM(endog, self.results_select, None, teff=self, + effect_group=effect_group) + start_params = np.concatenate((res_ipw[:2], + self.results_select.params)) + res_gmm = gmm.fit(start_params=start_params, + inv_weights=np.eye(len(start_params)), + optim_method='nm', + optim_args={"maxiter": 5000, "disp": disp}, + maxiter=1, + ) + + res = TreatmentEffectResults(self, res_gmm, "IPW", + start_params=start_params, + effect_group=effect_group, + ) + return res + + @Substitution(params_returns=indent(doc_params_returns, " " * 8)) + def ra(self, return_results=True, effect_group="all", disp=False): + """ + Regression Adjustment treatment effect estimation. + \n%(params_returns)s + See Also + -------- + TreatmentEffectsResults + """ + # need indicator for reordered observations + tind = np.zeros(len(self.treatment)) + tind[-self.treatment.sum():] = 1 + if effect_group == "all": + probt = None + elif effect_group in [1, "treated"]: + probt = tind + effect_group = 1 # standardize effect_group name + elif effect_group in [0, "untreated", "control"]: + probt = 1 - tind + effect_group = 0 # standardize effect_group name + elif isinstance(effect_group, np.ndarray): + # TODO: do we keep this? + probt = effect_group + effect_group = "user" # standardize effect_group name + else: + raise ValueError("incorrect option for effect_group") + + exog = self.exog_grouped + + # weight or indicator for effect_group + if probt is not None: + cw = (probt / probt.mean()) + else: + cw = 1 + + pom0 = (self.results0.predict(exog) * cw).mean() + pom1 = (self.results1.predict(exog) * cw).mean() + if not return_results: + return pom1 - pom0, pom0, pom1 + + endog = self.model_pool.endog + mod_gmm = _RAGMM(endog, self.results_select, None, teff=self, + probt=probt) + start_params = np.concatenate(( + # ate, tt0.effect, + [pom1 - pom0, pom0], + self.results0.params, + self.results1.params)) + res_gmm = mod_gmm.fit(start_params=start_params, + inv_weights=np.eye(len(start_params)), + optim_method='nm', + optim_args={"maxiter": 5000, "disp": disp}, + maxiter=1, + ) + res = TreatmentEffectResults(self, res_gmm, "IPW", + start_params=start_params, + effect_group=effect_group, + ) + return res + + @Substitution(params_returns=indent(doc_params_returns2, " " * 8)) + def aipw(self, return_results=True, disp=False): + """ + ATE and POM from double robust augmented inverse probability weighting + \n%(params_returns)s + See Also + -------- + TreatmentEffectsResults + + """ + + nobs = self.nobs + prob = self.prob_select + tind = self.treatment + exog = self.model_pool.exog # in original order + correct0 = (self.results0.resid / (1 - prob[tind == 0])).sum() / nobs + correct1 = (self.results1.resid / (prob[tind == 1])).sum() / nobs + tmean0 = self.results0.predict(exog).mean() + correct0 + tmean1 = self.results1.predict(exog).mean() + correct1 + ate = tmean1 - tmean0 + if not return_results: + return ate, tmean0, tmean1 + + endog = self.model_pool.endog + p2_aipw = np.asarray([ate, tmean0]) + + mag_aipw1 = _AIPWGMM(endog, self.results_select, None, teff=self) + start_params = np.concatenate(( + p2_aipw, + self.results0.params, self.results1.params, + self.results_select.params)) + res_gmm = mag_aipw1.fit( + start_params=start_params, + inv_weights=np.eye(len(start_params)), + optim_method='nm', + optim_args={"maxiter": 5000, "disp": disp}, + maxiter=1) + + res = TreatmentEffectResults(self, res_gmm, "IPW", + start_params=start_params, + effect_group="all", + ) + return res + + @Substitution(params_returns=indent(doc_params_returns2, " " * 8)) + def aipw_wls(self, return_results=True, disp=False): + """ + ATE and POM from double robust augmented inverse probability weighting. + + This uses weighted outcome regression, while `aipw` uses unweighted + outcome regression. + Option for effect on treated or on untreated is not available. + \n%(params_returns)s + See Also + -------- + TreatmentEffectsResults + + """ + nobs = self.nobs + prob = self.prob_select + + endog = self.model_pool.endog + exog = self.model_pool.exog + tind = self.treatment + treat_mask = self.treat_mask + + ww1 = tind / prob * (tind / prob - 1) + mod1 = WLS(endog[treat_mask], exog[treat_mask], + weights=ww1[treat_mask]) + result1 = mod1.fit(cov_type='HC1') + mean1_ipw2 = result1.predict(exog).mean() + + ww0 = (1 - tind) / (1 - prob) * ((1 - tind) / (1 - prob) - 1) + mod0 = WLS(endog[~treat_mask], exog[~treat_mask], + weights=ww0[~treat_mask]) + result0 = mod0.fit(cov_type='HC1') + mean0_ipw2 = result0.predict(exog).mean() + + self.results_ipwwls0 = result0 + self.results_ipwwls1 = result1 + + correct0 = (result0.resid / (1 - prob[tind == 0])).sum() / nobs + correct1 = (result1.resid / (prob[tind == 1])).sum() / nobs + tmean0 = mean0_ipw2 + correct0 + tmean1 = mean1_ipw2 + correct1 + ate = tmean1 - tmean0 + + if not return_results: + return ate, tmean0, tmean1 + + p2_aipw_wls = np.asarray([ate, tmean0]).squeeze() + + # GMM + mod_gmm = _AIPWWLSGMM(endog, self.results_select, None, + teff=self) + start_params = np.concatenate(( + p2_aipw_wls, + result0.params, + result1.params, + self.results_select.params)) + res_gmm = mod_gmm.fit( + start_params=start_params, + inv_weights=np.eye(len(start_params)), + optim_method='nm', + optim_args={"maxiter": 5000, "disp": disp}, + maxiter=1) + res = TreatmentEffectResults(self, res_gmm, "IPW", + start_params=start_params, + effect_group="all", + ) + return res + + @Substitution(params_returns=indent(doc_params_returns, " " * 8)) + def ipw_ra(self, return_results=True, effect_group="all", disp=False): + """ + ATE and POM from inverse probability weighted regression adjustment. + + \n%(params_returns)s + See Also + -------- + TreatmentEffectsResults + + """ + treat_mask = self.treat_mask + endog = self.model_pool.endog + exog = self.model_pool.exog + prob = self.prob_select + + prob0 = prob[~treat_mask] + prob1 = prob[treat_mask] + if effect_group == "all": + w0 = 1 / (1 - prob0) + w1 = 1 / prob1 + exogt = exog + elif effect_group in [1, "treated"]: + w0 = prob0 / (1 - prob0) + w1 = prob1 / prob1 + exogt = exog[treat_mask] + effect_group = 1 # standardize effect_group name + elif effect_group in [0, "untreated", "control"]: + w0 = (1 - prob0) / (1 - prob0) + w1 = (1 - prob1) / prob1 + exogt = exog[~treat_mask] + effect_group = 0 # standardize effect_group name + else: + raise ValueError("incorrect option for effect_group") + + mod0 = WLS(endog[~treat_mask], exog[~treat_mask], + weights=w0) + result0 = mod0.fit(cov_type='HC1') + # mean0_ipwra = (result0.predict(exog) * (prob / prob.mean())).mean() + mean0_ipwra = result0.predict(exogt).mean() + + mod1 = WLS(endog[treat_mask], exog[treat_mask], + weights=w1) + result1 = mod1.fit(cov_type='HC1') + # mean1_ipwra = (result1.predict(exog) * (prob / prob.mean())).mean() + mean1_ipwra = result1.predict(exogt).mean() + + if not return_results: + return mean1_ipwra - mean0_ipwra, mean0_ipwra, mean1_ipwra + + # GMM + mod_gmm = _IPWRAGMM(endog, self.results_select, None, teff=self, + effect_group=effect_group) + start_params = np.concatenate(( + [mean1_ipwra - mean0_ipwra, mean0_ipwra], + result0.params, + result1.params, + np.asarray(self.results_select.params) + )) + res_gmm = mod_gmm.fit( + start_params=start_params, + inv_weights=np.eye(len(start_params)), + optim_method='nm', + optim_args={"maxiter": 2000, "disp": disp}, + maxiter=1 + ) + + res = TreatmentEffectResults(self, res_gmm, "IPW", + start_params=start_params, + effect_group=effect_group, + ) + return res