code
stringlengths
26
870k
docstring
stringlengths
1
65.6k
func_name
stringlengths
1
194
language
stringclasses
1 value
repo
stringlengths
8
68
path
stringlengths
5
194
url
stringlengths
46
254
license
stringclasses
4 values
def _store_changes(self, col, vals): """ Fill in dataset with imputed values. Parameters ---------- col : str Name of variable to be filled in. vals : ndarray Array of imputed values to use for filling-in missing values. """ ix = self.ix_miss[col] if len(ix) > 0: self.data.iloc[ix, self.data.columns.get_loc(col)] = np.atleast_1d(vals)
Fill in dataset with imputed values. Parameters ---------- col : str Name of variable to be filled in. vals : ndarray Array of imputed values to use for filling-in missing values.
_store_changes
python
statsmodels/statsmodels
statsmodels/imputation/mice.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/imputation/mice.py
BSD-3-Clause
def update_all(self, n_iter=1): """ Perform a specified number of MICE iterations. Parameters ---------- n_iter : int The number of updates to perform. Only the result of the final update will be available. Notes ----- The imputed values are stored in the class attribute `self.data`. """ for k in range(n_iter): for vname in self._cycle_order: self.update(vname) if self.history_callback is not None: hv = self.history_callback(self) self.history.append(hv)
Perform a specified number of MICE iterations. Parameters ---------- n_iter : int The number of updates to perform. Only the result of the final update will be available. Notes ----- The imputed values are stored in the class attribute `self.data`.
update_all
python
statsmodels/statsmodels
statsmodels/imputation/mice.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/imputation/mice.py
BSD-3-Clause
def get_split_data(self, vname): """ Return endog and exog for imputation of a given variable. Parameters ---------- vname : str The variable for which the split data is returned. Returns ------- endog_obs : DataFrame Observed values of the variable to be imputed. exog_obs : DataFrame Current values of the predictors where the variable to be imputed is observed. exog_miss : DataFrame Current values of the predictors where the variable to be Imputed is missing. init_kwds : dict-like The init keyword arguments for `vname`, processed through Patsy as required. fit_kwds : dict-like The fit keyword arguments for `vname`, processed through Patsy as required. """ formula = self.conditional_formula[vname] mgr = FormulaManager() endog, exog = mgr.get_matrices(formula, self.data, pandas=True) # Rows with observed endog ixo = self.ix_obs[vname] endog_obs = np.require(endog.iloc[ixo], requirements="W") exog_obs = np.require(exog.iloc[ixo, :], requirements="W") # Rows with missing endog ixm = self.ix_miss[vname] exog_miss = np.require(exog.iloc[ixm, :], requirements="W") predict_obs_kwds = {} if vname in self.predict_kwds: kwds = self.predict_kwds[vname] predict_obs_kwds = self._process_kwds(kwds, ixo) predict_miss_kwds = {} if vname in self.predict_kwds: kwds = self.predict_kwds[vname] predict_miss_kwds = self._process_kwds(kwds, ixo) return (endog_obs, exog_obs, exog_miss, predict_obs_kwds, predict_miss_kwds)
Return endog and exog for imputation of a given variable. Parameters ---------- vname : str The variable for which the split data is returned. Returns ------- endog_obs : DataFrame Observed values of the variable to be imputed. exog_obs : DataFrame Current values of the predictors where the variable to be imputed is observed. exog_miss : DataFrame Current values of the predictors where the variable to be Imputed is missing. init_kwds : dict-like The init keyword arguments for `vname`, processed through Patsy as required. fit_kwds : dict-like The fit keyword arguments for `vname`, processed through Patsy as required.
get_split_data
python
statsmodels/statsmodels
statsmodels/imputation/mice.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/imputation/mice.py
BSD-3-Clause
def get_fitting_data(self, vname): """ Return the data needed to fit a model for imputation. The data is used to impute variable `vname`, and therefore only includes cases for which `vname` is observed. Values of type `PatsyFormula` in `init_kwds` or `fit_kwds` are processed through Patsy and subset to align with the model's endog and exog. Parameters ---------- vname : str The variable for which the fitting data is returned. Returns ------- endog : DataFrame Observed values of `vname`. exog : DataFrame Regression design matrix for imputing `vname`. init_kwds : dict-like The init keyword arguments for `vname`, processed through Patsy as required. fit_kwds : dict-like The fit keyword arguments for `vname`, processed through Patsy as required. """ # Rows with observed endog ix = self.ix_obs[vname] formula = self.conditional_formula[vname] mgr = FormulaManager() endog, exog = mgr.get_matrices(formula, self.data, pandas=True) endog = np.require(endog.iloc[ix, 0], requirements="W") exog = np.require(exog.iloc[ix, :], requirements="W") init_kwds = self._process_kwds(self.init_kwds[vname], ix) fit_kwds = self._process_kwds(self.fit_kwds[vname], ix) return endog, exog, init_kwds, fit_kwds
Return the data needed to fit a model for imputation. The data is used to impute variable `vname`, and therefore only includes cases for which `vname` is observed. Values of type `PatsyFormula` in `init_kwds` or `fit_kwds` are processed through Patsy and subset to align with the model's endog and exog. Parameters ---------- vname : str The variable for which the fitting data is returned. Returns ------- endog : DataFrame Observed values of `vname`. exog : DataFrame Regression design matrix for imputing `vname`. init_kwds : dict-like The init keyword arguments for `vname`, processed through Patsy as required. fit_kwds : dict-like The fit keyword arguments for `vname`, processed through Patsy as required.
get_fitting_data
python
statsmodels/statsmodels
statsmodels/imputation/mice.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/imputation/mice.py
BSD-3-Clause
def plot_missing_pattern(self, ax=None, row_order="pattern", column_order="pattern", hide_complete_rows=False, hide_complete_columns=False, color_row_patterns=True): """ Generate an image showing the missing data pattern. Parameters ---------- ax : AxesSubplot Axes on which to draw the plot. row_order : str The method for ordering the rows. Must be one of 'pattern', 'proportion', or 'raw'. column_order : str The method for ordering the columns. Must be one of 'pattern', 'proportion', or 'raw'. hide_complete_rows : bool If True, rows with no missing values are not drawn. hide_complete_columns : bool If True, columns with no missing values are not drawn. color_row_patterns : bool If True, color the unique row patterns, otherwise use grey and white as colors. Returns ------- A figure containing a plot of the missing data pattern. """ # Create an indicator matrix for missing values. miss = np.zeros(self.data.shape) cols = self.data.columns for j, col in enumerate(cols): ix = self.ix_miss[col] miss[ix, j] = 1 # Order the columns as requested if column_order == "proportion": ix = np.argsort(miss.mean(0)) elif column_order == "pattern": cv = np.cov(miss.T) u, s, vt = np.linalg.svd(cv, 0) ix = np.argsort(cv[:, 0]) elif column_order == "raw": ix = np.arange(len(cols)) else: raise ValueError( column_order + " is not an allowed value for `column_order`.") miss = miss[:, ix] cols = [cols[i] for i in ix] # Order the rows as requested if row_order == "proportion": ix = np.argsort(miss.mean(1)) elif row_order == "pattern": x = 2**np.arange(miss.shape[1]) rky = np.dot(miss, x) ix = np.argsort(rky) elif row_order == "raw": ix = np.arange(miss.shape[0]) else: raise ValueError( row_order + " is not an allowed value for `row_order`.") miss = miss[ix, :] if hide_complete_rows: ix = np.flatnonzero((miss == 1).any(1)) miss = miss[ix, :] if hide_complete_columns: ix = np.flatnonzero((miss == 1).any(0)) miss = miss[:, ix] cols = [cols[i] for i in ix] from matplotlib.colors import LinearSegmentedColormap from statsmodels.graphics import utils as gutils if ax is None: fig, ax = gutils.create_mpl_ax(ax) else: fig = ax.get_figure() if color_row_patterns: x = 2**np.arange(miss.shape[1]) rky = np.dot(miss, x) _, rcol = np.unique(rky, return_inverse=True) miss *= 1 + rcol[:, None] ax.imshow(miss, aspect="auto", interpolation="nearest", cmap='gist_ncar_r') else: cmap = LinearSegmentedColormap.from_list("_", ["white", "darkgrey"]) ax.imshow(miss, aspect="auto", interpolation="nearest", cmap=cmap) ax.set_ylabel("Cases") ax.set_xticks(range(len(cols))) ax.set_xticklabels(cols, rotation=90) return fig
Generate an image showing the missing data pattern. Parameters ---------- ax : AxesSubplot Axes on which to draw the plot. row_order : str The method for ordering the rows. Must be one of 'pattern', 'proportion', or 'raw'. column_order : str The method for ordering the columns. Must be one of 'pattern', 'proportion', or 'raw'. hide_complete_rows : bool If True, rows with no missing values are not drawn. hide_complete_columns : bool If True, columns with no missing values are not drawn. color_row_patterns : bool If True, color the unique row patterns, otherwise use grey and white as colors. Returns ------- A figure containing a plot of the missing data pattern.
plot_missing_pattern
python
statsmodels/statsmodels
statsmodels/imputation/mice.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/imputation/mice.py
BSD-3-Clause
def plot_bivariate(self, col1_name, col2_name, lowess_args=None, lowess_min_n=40, jitter=None, plot_points=True, ax=None): """ Plot observed and imputed values for two variables. Displays a scatterplot of one variable against another. The points are colored according to whether the values are observed or imputed. Parameters ---------- col1_name : str The variable to be plotted on the horizontal axis. col2_name : str The variable to be plotted on the vertical axis. lowess_args : dictionary A dictionary of dictionaries, keys are 'ii', 'io', 'oi' and 'oo', where 'o' denotes 'observed' and 'i' denotes imputed. See Notes for details. lowess_min_n : int Minimum sample size to plot a lowess fit jitter : float or tuple Standard deviation for jittering points in the plot. Either a single scalar applied to both axes, or a tuple containing x-axis jitter and y-axis jitter, respectively. plot_points : bool If True, the data points are plotted. ax : AxesSubplot Axes on which to plot, created if not provided. Returns ------- The matplotlib figure on which the plot id drawn. """ from statsmodels.graphics import utils as gutils from statsmodels.nonparametric.smoothers_lowess import lowess if lowess_args is None: lowess_args = {} if ax is None: fig, ax = gutils.create_mpl_ax(ax) else: fig = ax.get_figure() ax.set_position([0.1, 0.1, 0.7, 0.8]) ix1i = self.ix_miss[col1_name] ix1o = self.ix_obs[col1_name] ix2i = self.ix_miss[col2_name] ix2o = self.ix_obs[col2_name] ix_ii = np.intersect1d(ix1i, ix2i) ix_io = np.intersect1d(ix1i, ix2o) ix_oi = np.intersect1d(ix1o, ix2i) ix_oo = np.intersect1d(ix1o, ix2o) vec1 = np.require(self.data[col1_name], requirements="W") vec2 = np.require(self.data[col2_name], requirements="W") if jitter is not None: if np.isscalar(jitter): jitter = (jitter, jitter) vec1 += jitter[0] * np.random.normal(size=len(vec1)) vec2 += jitter[1] * np.random.normal(size=len(vec2)) # Plot the points keys = ['oo', 'io', 'oi', 'ii'] lak = {'i': 'imp', 'o': 'obs'} ixs = {'ii': ix_ii, 'io': ix_io, 'oi': ix_oi, 'oo': ix_oo} color = {'oo': 'grey', 'ii': 'red', 'io': 'orange', 'oi': 'lime'} if plot_points: for ky in keys: ix = ixs[ky] lab = lak[ky[0]] + "/" + lak[ky[1]] ax.plot(vec1[ix], vec2[ix], 'o', color=color[ky], label=lab, alpha=0.6) # Plot the lowess fits for ky in keys: ix = ixs[ky] if len(ix) < lowess_min_n: continue if ky in lowess_args: la = lowess_args[ky] else: la = {} ix = ixs[ky] lfit = lowess(vec2[ix], vec1[ix], **la) if plot_points: ax.plot(lfit[:, 0], lfit[:, 1], '-', color=color[ky], alpha=0.6, lw=4) else: lab = lak[ky[0]] + "/" + lak[ky[1]] ax.plot(lfit[:, 0], lfit[:, 1], '-', color=color[ky], alpha=0.6, lw=4, label=lab) ha, la = ax.get_legend_handles_labels() pad = 0.0001 if plot_points else 0.5 leg = fig.legend(ha, la, loc='center right', numpoints=1, handletextpad=pad) leg.draw_frame(False) ax.set_xlabel(col1_name) ax.set_ylabel(col2_name) return fig
Plot observed and imputed values for two variables. Displays a scatterplot of one variable against another. The points are colored according to whether the values are observed or imputed. Parameters ---------- col1_name : str The variable to be plotted on the horizontal axis. col2_name : str The variable to be plotted on the vertical axis. lowess_args : dictionary A dictionary of dictionaries, keys are 'ii', 'io', 'oi' and 'oo', where 'o' denotes 'observed' and 'i' denotes imputed. See Notes for details. lowess_min_n : int Minimum sample size to plot a lowess fit jitter : float or tuple Standard deviation for jittering points in the plot. Either a single scalar applied to both axes, or a tuple containing x-axis jitter and y-axis jitter, respectively. plot_points : bool If True, the data points are plotted. ax : AxesSubplot Axes on which to plot, created if not provided. Returns ------- The matplotlib figure on which the plot id drawn.
plot_bivariate
python
statsmodels/statsmodels
statsmodels/imputation/mice.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/imputation/mice.py
BSD-3-Clause
def plot_fit_obs(self, col_name, lowess_args=None, lowess_min_n=40, jitter=None, plot_points=True, ax=None): """ Plot fitted versus imputed or observed values as a scatterplot. Parameters ---------- col_name : str The variable to be plotted on the horizontal axis. lowess_args : dict-like Keyword arguments passed to lowess fit. A dictionary of dictionaries, keys are 'o' and 'i' denoting 'observed' and 'imputed', respectively. lowess_min_n : int Minimum sample size to plot a lowess fit jitter : float or tuple Standard deviation for jittering points in the plot. Either a single scalar applied to both axes, or a tuple containing x-axis jitter and y-axis jitter, respectively. plot_points : bool If True, the data points are plotted. ax : AxesSubplot Axes on which to plot, created if not provided. Returns ------- The matplotlib figure on which the plot is drawn. """ from statsmodels.graphics import utils as gutils from statsmodels.nonparametric.smoothers_lowess import lowess if lowess_args is None: lowess_args = {} if ax is None: fig, ax = gutils.create_mpl_ax(ax) else: fig = ax.get_figure() ax.set_position([0.1, 0.1, 0.7, 0.8]) ixi = self.ix_miss[col_name] ixo = self.ix_obs[col_name] vec1 = np.require(self.data[col_name], requirements="W") # Fitted values formula = self.conditional_formula[col_name] mgr = FormulaManager() endog, exog = mgr.get_matrices(formula, self.data, pandas=True) results = self.results[col_name] vec2 = results.predict(exog=exog) vec2 = self._get_predicted(vec2) if jitter is not None: if np.isscalar(jitter): jitter = (jitter, jitter) vec1 += jitter[0] * np.random.normal(size=len(vec1)) vec2 += jitter[1] * np.random.normal(size=len(vec2)) # Plot the points keys = ['o', 'i'] ixs = {'o': ixo, 'i': ixi} lak = {'o': 'obs', 'i': 'imp'} color = {'o': 'orange', 'i': 'lime'} if plot_points: for ky in keys: ix = ixs[ky] ax.plot(vec1[ix], vec2[ix], 'o', color=color[ky], label=lak[ky], alpha=0.6) # Plot the lowess fits for ky in keys: ix = ixs[ky] if len(ix) < lowess_min_n: continue if ky in lowess_args: la = lowess_args[ky] else: la = {} ix = ixs[ky] lfit = lowess(vec2[ix], vec1[ix], **la) ax.plot(lfit[:, 0], lfit[:, 1], '-', color=color[ky], alpha=0.6, lw=4, label=lak[ky]) ha, la = ax.get_legend_handles_labels() leg = fig.legend(ha, la, loc='center right', numpoints=1) leg.draw_frame(False) ax.set_xlabel(col_name + " observed or imputed") ax.set_ylabel(col_name + " fitted") return fig
Plot fitted versus imputed or observed values as a scatterplot. Parameters ---------- col_name : str The variable to be plotted on the horizontal axis. lowess_args : dict-like Keyword arguments passed to lowess fit. A dictionary of dictionaries, keys are 'o' and 'i' denoting 'observed' and 'imputed', respectively. lowess_min_n : int Minimum sample size to plot a lowess fit jitter : float or tuple Standard deviation for jittering points in the plot. Either a single scalar applied to both axes, or a tuple containing x-axis jitter and y-axis jitter, respectively. plot_points : bool If True, the data points are plotted. ax : AxesSubplot Axes on which to plot, created if not provided. Returns ------- The matplotlib figure on which the plot is drawn.
plot_fit_obs
python
statsmodels/statsmodels
statsmodels/imputation/mice.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/imputation/mice.py
BSD-3-Clause
def plot_imputed_hist(self, col_name, ax=None, imp_hist_args=None, obs_hist_args=None, all_hist_args=None): """ Display imputed values for one variable as a histogram. Parameters ---------- col_name : str The name of the variable to be plotted. ax : AxesSubplot An axes on which to draw the histograms. If not provided, one is created. imp_hist_args : dict Keyword arguments to be passed to pyplot.hist when creating the histogram for imputed values. obs_hist_args : dict Keyword arguments to be passed to pyplot.hist when creating the histogram for observed values. all_hist_args : dict Keyword arguments to be passed to pyplot.hist when creating the histogram for all values. Returns ------- The matplotlib figure on which the histograms were drawn """ from statsmodels.graphics import utils as gutils if imp_hist_args is None: imp_hist_args = {} if obs_hist_args is None: obs_hist_args = {} if all_hist_args is None: all_hist_args = {} if ax is None: fig, ax = gutils.create_mpl_ax(ax) else: fig = ax.get_figure() ax.set_position([0.1, 0.1, 0.7, 0.8]) ixm = self.ix_miss[col_name] ixo = self.ix_obs[col_name] imp = self.data[col_name].iloc[ixm] obs = self.data[col_name].iloc[ixo] for di in imp_hist_args, obs_hist_args, all_hist_args: if 'histtype' not in di: di['histtype'] = 'step' ha, la = [], [] if len(imp) > 0: h = ax.hist(np.asarray(imp), **imp_hist_args) ha.append(h[-1][0]) la.append("Imp") h1 = ax.hist(np.asarray(obs), **obs_hist_args) h2 = ax.hist(np.asarray(self.data[col_name]), **all_hist_args) ha.extend([h1[-1][0], h2[-1][0]]) la.extend(["Obs", "All"]) leg = fig.legend(ha, la, loc='center right', numpoints=1) leg.draw_frame(False) ax.set_xlabel(col_name) ax.set_ylabel("Frequency") return fig
Display imputed values for one variable as a histogram. Parameters ---------- col_name : str The name of the variable to be plotted. ax : AxesSubplot An axes on which to draw the histograms. If not provided, one is created. imp_hist_args : dict Keyword arguments to be passed to pyplot.hist when creating the histogram for imputed values. obs_hist_args : dict Keyword arguments to be passed to pyplot.hist when creating the histogram for observed values. all_hist_args : dict Keyword arguments to be passed to pyplot.hist when creating the histogram for all values. Returns ------- The matplotlib figure on which the histograms were drawn
plot_imputed_hist
python
statsmodels/statsmodels
statsmodels/imputation/mice.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/imputation/mice.py
BSD-3-Clause
def _perturb_bootstrap(self, vname): """ Perturbs the model's parameters using a bootstrap. """ endog, exog, init_kwds, fit_kwds = self.get_fitting_data(vname) m = len(endog) rix = np.random.randint(0, m, m) endog = endog[rix] exog = exog[rix, :] init_kwds = self._boot_kwds(init_kwds, rix) fit_kwds = self._boot_kwds(fit_kwds, rix) klass = self.model_class[vname] self.models[vname] = klass(endog, exog, **init_kwds) if vname in self.regularized and self.regularized[vname]: self.results[vname] = ( self.models[vname].fit_regularized(**fit_kwds)) else: self.results[vname] = self.models[vname].fit(**fit_kwds) self.params[vname] = self.results[vname].params
Perturbs the model's parameters using a bootstrap.
_perturb_bootstrap
python
statsmodels/statsmodels
statsmodels/imputation/mice.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/imputation/mice.py
BSD-3-Clause
def _perturb_gaussian(self, vname): """ Gaussian perturbation of model parameters. The normal approximation to the sampling distribution of the parameter estimates is used to define the mean and covariance structure of the perturbation distribution. """ endog, exog, init_kwds, fit_kwds = self.get_fitting_data(vname) klass = self.model_class[vname] self.models[vname] = klass(endog, exog, **init_kwds) self.results[vname] = self.models[vname].fit(**fit_kwds) cov = self.results[vname].cov_params() mu = self.results[vname].params self.params[vname] = np.random.multivariate_normal(mean=mu, cov=cov)
Gaussian perturbation of model parameters. The normal approximation to the sampling distribution of the parameter estimates is used to define the mean and covariance structure of the perturbation distribution.
_perturb_gaussian
python
statsmodels/statsmodels
statsmodels/imputation/mice.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/imputation/mice.py
BSD-3-Clause
def update(self, vname): """ Impute missing values for a single variable. This is a two-step process in which first the parameters are perturbed, then the missing values are re-imputed. Parameters ---------- vname : str The name of the variable to be updated. """ self.perturb_params(vname) self.impute(vname)
Impute missing values for a single variable. This is a two-step process in which first the parameters are perturbed, then the missing values are re-imputed. Parameters ---------- vname : str The name of the variable to be updated.
update
python
statsmodels/statsmodels
statsmodels/imputation/mice.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/imputation/mice.py
BSD-3-Clause
def impute_pmm(self, vname): """ Use predictive mean matching to impute missing values. Notes ----- The `perturb_params` method must be called first to define the model. """ k_pmm = self.k_pmm endog_obs, exog_obs, exog_miss, predict_obs_kwds, predict_miss_kwds = ( self.get_split_data(vname)) # Predict imputed variable for both missing and non-missing # observations model = self.models[vname] pendog_obs = model.predict(self.params[vname], exog_obs, **predict_obs_kwds) pendog_miss = model.predict(self.params[vname], exog_miss, **predict_miss_kwds) pendog_obs = self._get_predicted(pendog_obs) pendog_miss = self._get_predicted(pendog_miss) # Jointly sort the observed and predicted endog values for the # cases with observed values. ii = np.argsort(pendog_obs) endog_obs = endog_obs[ii] pendog_obs = pendog_obs[ii] # Find the closest match to the predicted endog values for # cases with missing endog values. ix = np.searchsorted(pendog_obs, pendog_miss) # Get the indices for the closest k_pmm values on # either side of the closest index. ixm = ix[:, None] + np.arange(-k_pmm, k_pmm)[None, :] # Account for boundary effects msk = np.nonzero((ixm < 0) | (ixm > len(endog_obs) - 1)) ixm = np.clip(ixm, 0, len(endog_obs) - 1) # Get the distances dx = pendog_miss[:, None] - pendog_obs[ixm] dx = np.abs(dx) dx[msk] = np.inf # Closest positions in ix, row-wise. dxi = np.argsort(dx, 1)[:, 0:k_pmm] # Choose a column for each row. ir = np.random.randint(0, k_pmm, len(pendog_miss)) # Unwind the indices jj = np.arange(dxi.shape[0]) ix = dxi[(jj, ir)] iz = ixm[(jj, ix)] imputed_miss = np.array(endog_obs[iz]).squeeze() self._store_changes(vname, imputed_miss)
Use predictive mean matching to impute missing values. Notes ----- The `perturb_params` method must be called first to define the model.
impute_pmm
python
statsmodels/statsmodels
statsmodels/imputation/mice.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/imputation/mice.py
BSD-3-Clause
def next_sample(self): """ Perform one complete MICE iteration. A single MICE iteration updates all missing values using their respective imputation models, then fits the analysis model to the imputed data. Returns ------- params : array_like The model parameters for the analysis model. Notes ----- This function fits the analysis model and returns its parameter estimate. The parameter vector is not stored by the class and is not used in any subsequent calls to `combine`. Use `fit` to run all MICE steps together and obtain summary results. The complete cycle of missing value imputation followed by fitting the analysis model is repeated `n_skip + 1` times and the analysis model parameters from the final fit are returned. """ # Impute missing values self.data.update_all(self.n_skip + 1) start_params = None if len(self.results_list) > 0: start_params = self.results_list[-1].params # Fit the analysis model. model = self.model_class.from_formula(self.model_formula, self.data.data, **self.init_kwds) self.fit_kwds.update({"start_params": start_params}) result = model.fit(**self.fit_kwds) return result
Perform one complete MICE iteration. A single MICE iteration updates all missing values using their respective imputation models, then fits the analysis model to the imputed data. Returns ------- params : array_like The model parameters for the analysis model. Notes ----- This function fits the analysis model and returns its parameter estimate. The parameter vector is not stored by the class and is not used in any subsequent calls to `combine`. Use `fit` to run all MICE steps together and obtain summary results. The complete cycle of missing value imputation followed by fitting the analysis model is repeated `n_skip + 1` times and the analysis model parameters from the final fit are returned.
next_sample
python
statsmodels/statsmodels
statsmodels/imputation/mice.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/imputation/mice.py
BSD-3-Clause
def fit(self, n_burnin=10, n_imputations=10): """ Fit a model using MICE. Parameters ---------- n_burnin : int The number of burn-in cycles to skip. n_imputations : int The number of data sets to impute """ # Run without fitting the analysis model self.data.update_all(n_burnin) for j in range(n_imputations): result = self.next_sample() self.results_list.append(result) self.endog_names = result.model.endog_names self.exog_names = result.model.exog_names return self.combine()
Fit a model using MICE. Parameters ---------- n_burnin : int The number of burn-in cycles to skip. n_imputations : int The number of data sets to impute
fit
python
statsmodels/statsmodels
statsmodels/imputation/mice.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/imputation/mice.py
BSD-3-Clause
def combine(self): """ Pools MICE imputation results. This method can only be used after the `run` method has been called. Returns estimates and standard errors of the analysis model parameters. Returns a MICEResults instance. """ # Extract a few things from the models that were fit to # imputed data sets. params_list = [] cov_within = 0. scale_list = [] for results in self.results_list: results_uw = results._results params_list.append(results_uw.params) cov_within += results_uw.cov_params() scale_list.append(results.scale) params_list = np.asarray(params_list) scale_list = np.asarray(scale_list) # The estimated parameters for the MICE analysis params = params_list.mean(0) # The average of the within-imputation covariances cov_within /= len(self.results_list) # The between-imputation covariance cov_between = np.cov(params_list.T) # The estimated covariance matrix for the MICE analysis f = 1 + 1 / float(len(self.results_list)) cov_params = cov_within + f * cov_between # Fraction of missing information fmi = f * np.diag(cov_between) / np.diag(cov_params) # Set up a results instance scale = np.mean(scale_list) results = MICEResults(self, params, cov_params / scale) results.scale = scale results.frac_miss_info = fmi results.exog_names = self.exog_names results.endog_names = self.endog_names results.model_class = self.model_class return results
Pools MICE imputation results. This method can only be used after the `run` method has been called. Returns estimates and standard errors of the analysis model parameters. Returns a MICEResults instance.
combine
python
statsmodels/statsmodels
statsmodels/imputation/mice.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/imputation/mice.py
BSD-3-Clause
def summary(self, title=None, alpha=.05): """ Summarize the results of running MICE. Parameters ---------- 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. """ from statsmodels.iolib import summary2 smry = summary2.Summary() float_format = "%8.3f" info = {} info["Method:"] = "MICE" info["Model:"] = self.model_class.__name__ info["Dependent variable:"] = self.endog_names info["Sample size:"] = "%d" % self.model.data.data.shape[0] info["Scale"] = "%.2f" % self.scale info["Num. imputations"] = "%d" % len(self.model.results_list) smry.add_dict(info, align='l', float_format=float_format) param = summary2.summary_params(self, alpha=alpha) param["FMI"] = self.frac_miss_info smry.add_df(param, float_format=float_format) smry.add_title(title=title, results=self) return smry
Summarize the results of running MICE. Parameters ---------- 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.
summary
python
statsmodels/statsmodels
statsmodels/imputation/mice.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/imputation/mice.py
BSD-3-Clause
def gendat(): """ Create a data set with missing values. """ gen = np.random.RandomState(34243) n = 200 p = 5 exog = gen.normal(size=(n, p)) exog[:, 0] = exog[:, 1] - exog[:, 2] + 2*exog[:, 4] exog[:, 0] += gen.normal(size=n) exog[:, 2] = 1*(exog[:, 2] > 0) endog = exog.sum(1) + gen.normal(size=n) df = pd.DataFrame(exog) df.columns = ["x%d" % k for k in range(1, p+1)] df["y"] = endog # loc is inclusive of right end, so needed to lower index by 1 df.loc[0:59, "x1"] = np.nan df.loc[0:39, "x2"] = np.nan df.loc[10:29:2, "x3"] = np.nan df.loc[20:49:3, "x4"] = np.nan df.loc[40:44, "x5"] = np.nan df.loc[30:99:2, "y"] = np.nan return df
Create a data set with missing values.
gendat
python
statsmodels/statsmodels
statsmodels/imputation/tests/test_mice.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/imputation/tests/test_mice.py
BSD-3-Clause
def csv2st(csvfile, headers=False, stubs=False, title=None): """Return SimpleTable instance, created from the data in `csvfile`, which is in comma separated values format. The first row may contain headers: set headers=True. The first column may contain stubs: set stubs=True. Can also supply headers and stubs as tuples of strings. """ rows = list() with open(csvfile, encoding="utf-8") as fh: reader = csv.reader(fh) if headers is True: headers = next(reader) elif headers is False: headers = () if stubs is True: stubs = list() for row in reader: if row: stubs.append(row[0]) rows.append(row[1:]) else: # no stubs, or stubs provided for row in reader: if row: rows.append(row) if stubs is False: stubs = () ncols = len(rows[0]) if any(len(row) != ncols for row in rows): raise OSError('All rows of CSV file must have same length.') return SimpleTable(data=rows, headers=headers, stubs=stubs)
Return SimpleTable instance, created from the data in `csvfile`, which is in comma separated values format. The first row may contain headers: set headers=True. The first column may contain stubs: set stubs=True. Can also supply headers and stubs as tuples of strings.
csv2st
python
statsmodels/statsmodels
statsmodels/iolib/table.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/table.py
BSD-3-Clause
def __init__(self, data, headers=None, stubs=None, title='', datatypes=None, csv_fmt=None, txt_fmt=None, ltx_fmt=None, html_fmt=None, celltype=None, rowtype=None, **fmt_dict): """ Parameters ---------- data : list of lists or 2d array (not matrix!) R rows by K columns of table elements headers : list (or tuple) of str sequence of K strings, one per header stubs : list (or tuple) of str sequence of R strings, one per stub title : str title of the table datatypes : list of int indexes to `data_fmts` txt_fmt : dict text formatting options ltx_fmt : dict latex formatting options csv_fmt : dict csv formatting options hmtl_fmt : dict hmtl formatting options celltype : class the cell class for the table (default: Cell) rowtype : class the row class for the table (default: Row) fmt_dict : dict general formatting options """ self.title = title self._datatypes = datatypes if self._datatypes is None: self._datatypes = [] if len(data) == 0 else lrange(len(data[0])) # start with default formatting self._txt_fmt = default_txt_fmt.copy() self._latex_fmt = default_latex_fmt.copy() self._csv_fmt = default_csv_fmt.copy() self._html_fmt = default_html_fmt.copy() # substitute any general user specified formatting # :note: these will be overridden by output specific arguments self._csv_fmt.update(fmt_dict) self._txt_fmt.update(fmt_dict) self._latex_fmt.update(fmt_dict) self._html_fmt.update(fmt_dict) # substitute any output-type specific formatting self._csv_fmt.update(csv_fmt or dict()) self._txt_fmt.update(txt_fmt or dict()) self._latex_fmt.update(ltx_fmt or dict()) self._html_fmt.update(html_fmt or dict()) self.output_formats = dict( txt=self._txt_fmt, csv=self._csv_fmt, html=self._html_fmt, latex=self._latex_fmt ) self._Cell = celltype or Cell self._Row = rowtype or Row rows = self._data2rows(data) # a list of Row instances list.__init__(self, rows) self._add_headers_stubs(headers, stubs) self._colwidths = dict()
Parameters ---------- data : list of lists or 2d array (not matrix!) R rows by K columns of table elements headers : list (or tuple) of str sequence of K strings, one per header stubs : list (or tuple) of str sequence of R strings, one per stub title : str title of the table datatypes : list of int indexes to `data_fmts` txt_fmt : dict text formatting options ltx_fmt : dict latex formatting options csv_fmt : dict csv formatting options hmtl_fmt : dict hmtl formatting options celltype : class the cell class for the table (default: Cell) rowtype : class the row class for the table (default: Row) fmt_dict : dict general formatting options
__init__
python
statsmodels/statsmodels
statsmodels/iolib/table.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/table.py
BSD-3-Clause
def _add_headers_stubs(self, headers, stubs): """Return None. Adds headers and stubs to table, if these were provided at initialization. Parameters ---------- headers : list[str] K strings, where K is number of columns stubs : list[str] R strings, where R is number of non-header rows :note: a header row does not receive a stub! """ if headers: self.insert_header_row(0, headers, dec_below='header_dec_below') if stubs: self.insert_stubs(0, stubs)
Return None. Adds headers and stubs to table, if these were provided at initialization. Parameters ---------- headers : list[str] K strings, where K is number of columns stubs : list[str] R strings, where R is number of non-header rows :note: a header row does not receive a stub!
_add_headers_stubs
python
statsmodels/statsmodels
statsmodels/iolib/table.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/table.py
BSD-3-Clause
def insert(self, idx, row, datatype=None): """Return None. Insert a row into a table. """ if datatype is None: try: datatype = row.datatype except AttributeError: pass row = self._Row(row, datatype=datatype, table=self) list.insert(self, idx, row)
Return None. Insert a row into a table.
insert
python
statsmodels/statsmodels
statsmodels/iolib/table.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/table.py
BSD-3-Clause
def insert_header_row(self, rownum, headers, dec_below='header_dec_below'): """Return None. Insert a row of headers, where ``headers`` is a sequence of strings. (The strings may contain newlines, to indicated multiline headers.) """ header_rows = [header.split('\n') for header in headers] # rows in reverse order rows = list(zip_longest(*header_rows, **dict(fillvalue=''))) rows.reverse() for i, row in enumerate(rows): self.insert(rownum, row, datatype='header') if i == 0: self[rownum].dec_below = dec_below else: self[rownum].dec_below = None
Return None. Insert a row of headers, where ``headers`` is a sequence of strings. (The strings may contain newlines, to indicated multiline headers.)
insert_header_row
python
statsmodels/statsmodels
statsmodels/iolib/table.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/table.py
BSD-3-Clause
def insert_stubs(self, loc, stubs): """Return None. Insert column of stubs at column `loc`. If there is a header row, it gets an empty cell. So ``len(stubs)`` should equal the number of non-header rows. """ _Cell = self._Cell stubs = iter(stubs) for row in self: if row.datatype == 'header': empty_cell = _Cell('', datatype='empty') row.insert(loc, empty_cell) else: try: row.insert_stub(loc, next(stubs)) except StopIteration: raise ValueError('length of stubs must match table length')
Return None. Insert column of stubs at column `loc`. If there is a header row, it gets an empty cell. So ``len(stubs)`` should equal the number of non-header rows.
insert_stubs
python
statsmodels/statsmodels
statsmodels/iolib/table.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/table.py
BSD-3-Clause
def _data2rows(self, raw_data): """Return list of Row, the raw data as rows of cells. """ _Cell = self._Cell _Row = self._Row rows = [] for datarow in raw_data: dtypes = cycle(self._datatypes) newrow = _Row(datarow, datatype='data', table=self, celltype=_Cell) for cell in newrow: cell.datatype = next(dtypes) cell.row = newrow # a cell knows its row rows.append(newrow) return rows
Return list of Row, the raw data as rows of cells.
_data2rows
python
statsmodels/statsmodels
statsmodels/iolib/table.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/table.py
BSD-3-Clause
def pad(self, s, width, align): """DEPRECATED: just use the pad function""" return pad(s, width, align)
DEPRECATED: just use the pad function
pad
python
statsmodels/statsmodels
statsmodels/iolib/table.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/table.py
BSD-3-Clause
def _get_colwidths(self, output_format, **fmt_dict): """Return list, the calculated widths of each column.""" output_format = get_output_format(output_format) fmt = self.output_formats[output_format].copy() fmt.update(fmt_dict) ncols = max(len(row) for row in self) request = fmt.get('colwidths') if request == 0: # assume no extra space desired (e.g, CSV) return [0] * ncols elif request is None: # assume no extra space desired (e.g, CSV) request = [0] * ncols elif isinstance(request, int): request = [request] * ncols elif len(request) < ncols: request = [request[i % len(request)] for i in range(ncols)] min_widths = [] for col in zip(*self): maxwidth = max(len(c.format(0, output_format, **fmt)) for c in col) min_widths.append(maxwidth) result = lmap(max, min_widths, request) return result
Return list, the calculated widths of each column.
_get_colwidths
python
statsmodels/statsmodels
statsmodels/iolib/table.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/table.py
BSD-3-Clause
def get_colwidths(self, output_format, **fmt_dict): """Return list, the widths of each column.""" call_args = [output_format] for k, v in sorted(fmt_dict.items()): if isinstance(v, list): call_args.append((k, tuple(v))) elif isinstance(v, dict): call_args.append((k, tuple(sorted(v.items())))) else: call_args.append((k, v)) key = tuple(call_args) try: return self._colwidths[key] except KeyError: self._colwidths[key] = self._get_colwidths(output_format, **fmt_dict) return self._colwidths[key]
Return list, the widths of each column.
get_colwidths
python
statsmodels/statsmodels
statsmodels/iolib/table.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/table.py
BSD-3-Clause
def _get_fmt(self, output_format, **fmt_dict): """Return dict, the formatting options. """ output_format = get_output_format(output_format) # first get the default formatting try: fmt = self.output_formats[output_format].copy() except KeyError: raise ValueError('Unknown format: %s' % output_format) # then, add formatting specific to this call fmt.update(fmt_dict) return fmt
Return dict, the formatting options.
_get_fmt
python
statsmodels/statsmodels
statsmodels/iolib/table.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/table.py
BSD-3-Clause
def as_csv(self, **fmt_dict): """Return string, the table in CSV format. Currently only supports comma separator.""" # fetch the format, which may just be default_csv_format fmt = self._get_fmt('csv', **fmt_dict) return self.as_text(**fmt)
Return string, the table in CSV format. Currently only supports comma separator.
as_csv
python
statsmodels/statsmodels
statsmodels/iolib/table.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/table.py
BSD-3-Clause
def as_text(self, **fmt_dict): """Return string, the table as text.""" # fetch the text format, override with fmt_dict fmt = self._get_fmt('txt', **fmt_dict) # get rows formatted as strings formatted_rows = [row.as_string('text', **fmt) for row in self] rowlen = len(formatted_rows[-1]) # do not use header row # place decoration above the table body, if desired table_dec_above = fmt.get('table_dec_above', '=') if table_dec_above: formatted_rows.insert(0, table_dec_above * rowlen) # next place a title at the very top, if desired # :note: user can include a newlines at end of title if desired title = self.title if title: title = pad(self.title, rowlen, fmt.get('title_align', 'c')) formatted_rows.insert(0, title) # add decoration below the table, if desired table_dec_below = fmt.get('table_dec_below', '-') if table_dec_below: formatted_rows.append(table_dec_below * rowlen) return '\n'.join(formatted_rows)
Return string, the table as text.
as_text
python
statsmodels/statsmodels
statsmodels/iolib/table.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/table.py
BSD-3-Clause
def as_html(self, **fmt_dict): """Return string. This is the default formatter for HTML tables. An HTML table formatter must accept as arguments a table and a format dictionary. """ # fetch the text format, override with fmt_dict fmt = self._get_fmt('html', **fmt_dict) formatted_rows = ['<table class="simpletable">'] if self.title: title = '<caption>%s</caption>' % self.title formatted_rows.append(title) formatted_rows.extend(row.as_string('html', **fmt) for row in self) formatted_rows.append('</table>') return '\n'.join(formatted_rows)
Return string. This is the default formatter for HTML tables. An HTML table formatter must accept as arguments a table and a format dictionary.
as_html
python
statsmodels/statsmodels
statsmodels/iolib/table.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/table.py
BSD-3-Clause
def as_latex_tabular(self, center=True, **fmt_dict): '''Return string, the table as a LaTeX tabular environment. Note: will require the booktabs package.''' # fetch the text format, override with fmt_dict fmt = self._get_fmt('latex', **fmt_dict) formatted_rows = [] if center: formatted_rows.append(r'\begin{center}') table_dec_above = fmt['table_dec_above'] or '' table_dec_below = fmt['table_dec_below'] or '' prev_aligns = None last = None for row in self + [last]: if row == last: aligns = None else: aligns = row.get_aligns('latex', **fmt) if aligns != prev_aligns: # When the number/type of columns changes... if prev_aligns: # ... if there is a tabular to close, close it... formatted_rows.append(table_dec_below) formatted_rows.append(r'\end{tabular}') if aligns: # ... and if there are more lines, open a new one: formatted_rows.append(r'\begin{tabular}{%s}' % aligns) if not prev_aligns: # (with a nice line if it's the top of the whole table) formatted_rows.append(table_dec_above) if row != last: formatted_rows.append( row.as_string(output_format='latex', **fmt)) prev_aligns = aligns # tabular does not support caption, but make it available for # figure environment if self.title: title = r'%%\caption{%s}' % self.title formatted_rows.append(title) if center: formatted_rows.append(r'\end{center}') # Replace $$ due to bug in GH 5444 return '\n'.join(formatted_rows).replace('$$', ' ')
Return string, the table as a LaTeX tabular environment. Note: will require the booktabs package.
as_latex_tabular
python
statsmodels/statsmodels
statsmodels/iolib/table.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/table.py
BSD-3-Clause
def extend_right(self, table): """Return None. Extend each row of `self` with corresponding row of `table`. Does **not** import formatting from ``table``. This generally makes sense only if the two tables have the same number of rows, but that is not enforced. :note: To extend append a table below, just use `extend`, which is the ordinary list method. This generally makes sense only if the two tables have the same number of columns, but that is not enforced. """ for row1, row2 in zip(self, table): row1.extend(row2)
Return None. Extend each row of `self` with corresponding row of `table`. Does **not** import formatting from ``table``. This generally makes sense only if the two tables have the same number of rows, but that is not enforced. :note: To extend append a table below, just use `extend`, which is the ordinary list method. This generally makes sense only if the two tables have the same number of columns, but that is not enforced.
extend_right
python
statsmodels/statsmodels
statsmodels/iolib/table.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/table.py
BSD-3-Clause
def label_cells(self, func): """Return None. Labels cells based on `func`. If ``func(cell) is None`` then its datatype is not changed; otherwise it is set to ``func(cell)``. """ for row in self: for cell in row: label = func(cell) if label is not None: cell.datatype = label
Return None. Labels cells based on `func`. If ``func(cell) is None`` then its datatype is not changed; otherwise it is set to ``func(cell)``.
label_cells
python
statsmodels/statsmodels
statsmodels/iolib/table.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/table.py
BSD-3-Clause
def pad(s, width, align): """Return string padded with spaces, based on alignment parameter.""" if align == 'l': s = s.ljust(width) elif align == 'r': s = s.rjust(width) else: s = s.center(width) return s
Return string padded with spaces, based on alignment parameter.
pad
python
statsmodels/statsmodels
statsmodels/iolib/table.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/table.py
BSD-3-Clause
def __init__(self, seq, datatype='data', table=None, celltype=None, dec_below='row_dec_below', **fmt_dict): """ Parameters ---------- seq : sequence of data or cells table : SimpleTable datatype : str ('data' or 'header') dec_below : str (e.g., 'header_dec_below' or 'row_dec_below') decoration tag, identifies the decoration to go below the row. (Decoration is repeated as needed for text formats.) """ self.datatype = datatype self.table = table if celltype is None: if table is None: celltype = Cell else: celltype = table._Cell self._Cell = celltype self._fmt = fmt_dict self.special_fmts = dict() # special formatting for any output format self.dec_below = dec_below list.__init__(self, (celltype(cell, row=self) for cell in seq))
Parameters ---------- seq : sequence of data or cells table : SimpleTable datatype : str ('data' or 'header') dec_below : str (e.g., 'header_dec_below' or 'row_dec_below') decoration tag, identifies the decoration to go below the row. (Decoration is repeated as needed for text formats.)
__init__
python
statsmodels/statsmodels
statsmodels/iolib/table.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/table.py
BSD-3-Clause
def add_format(self, output_format, **fmt_dict): """ Return None. Adds row-instance specific formatting for the specified output format. Example: myrow.add_format('txt', row_dec_below='+-') """ output_format = get_output_format(output_format) if output_format not in self.special_fmts: self.special_fmts[output_format] = dict() self.special_fmts[output_format].update(fmt_dict)
Return None. Adds row-instance specific formatting for the specified output format. Example: myrow.add_format('txt', row_dec_below='+-')
add_format
python
statsmodels/statsmodels
statsmodels/iolib/table.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/table.py
BSD-3-Clause
def insert_stub(self, loc, stub): """Return None. Inserts a stub cell in the row at `loc`. """ _Cell = self._Cell if not isinstance(stub, _Cell): stub = stub stub = _Cell(stub, datatype='stub', row=self) self.insert(loc, stub)
Return None. Inserts a stub cell in the row at `loc`.
insert_stub
python
statsmodels/statsmodels
statsmodels/iolib/table.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/table.py
BSD-3-Clause
def _get_fmt(self, output_format, **fmt_dict): """Return dict, the formatting options. """ output_format = get_output_format(output_format) # first get the default formatting try: fmt = default_fmts[output_format].copy() except KeyError: raise ValueError('Unknown format: %s' % output_format) # second get table specific formatting (if possible) try: fmt.update(self.table.output_formats[output_format]) except AttributeError: pass # finally, add formatting for this row and this call fmt.update(self._fmt) fmt.update(fmt_dict) special_fmt = self.special_fmts.get(output_format, None) if special_fmt is not None: fmt.update(special_fmt) return fmt
Return dict, the formatting options.
_get_fmt
python
statsmodels/statsmodels
statsmodels/iolib/table.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/table.py
BSD-3-Clause
def get_aligns(self, output_format, **fmt_dict): """Return string, sequence of column alignments. Ensure comformable data_aligns in `fmt_dict`.""" fmt = self._get_fmt(output_format, **fmt_dict) return ''.join(cell.alignment(output_format, **fmt) for cell in self)
Return string, sequence of column alignments. Ensure comformable data_aligns in `fmt_dict`.
get_aligns
python
statsmodels/statsmodels
statsmodels/iolib/table.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/table.py
BSD-3-Clause
def as_string(self, output_format='txt', **fmt_dict): """Return string: the formatted row. This is the default formatter for rows. Override this to get different formatting. A row formatter must accept as arguments a row (self) and an output format, one of ('html', 'txt', 'csv', 'latex'). """ fmt = self._get_fmt(output_format, **fmt_dict) # get column widths try: colwidths = self.table.get_colwidths(output_format, **fmt) except AttributeError: colwidths = fmt.get('colwidths') if colwidths is None: colwidths = (0,) * len(self) colsep = fmt['colsep'] row_pre = fmt.get('row_pre', '') row_post = fmt.get('row_post', '') formatted_cells = [] for cell, width in zip(self, colwidths): content = cell.format(width, output_format=output_format, **fmt) formatted_cells.append(content) formatted_row = row_pre + colsep.join(formatted_cells) + row_post formatted_row = self._decorate_below(formatted_row, output_format, **fmt) return formatted_row
Return string: the formatted row. This is the default formatter for rows. Override this to get different formatting. A row formatter must accept as arguments a row (self) and an output format, one of ('html', 'txt', 'csv', 'latex').
as_string
python
statsmodels/statsmodels
statsmodels/iolib/table.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/table.py
BSD-3-Clause
def _decorate_below(self, row_as_string, output_format, **fmt_dict): """This really only makes sense for the text and latex output formats. """ dec_below = fmt_dict.get(self.dec_below, None) if dec_below is None: result = row_as_string else: output_format = get_output_format(output_format) if output_format == 'txt': row0len = len(row_as_string) dec_len = len(dec_below) repeat, addon = divmod(row0len, dec_len) result = row_as_string + "\n" + (dec_below * repeat + dec_below[:addon]) elif output_format == 'latex': result = row_as_string + "\n" + dec_below else: raise ValueError("I cannot decorate a %s header." % output_format) return result
This really only makes sense for the text and latex output formats.
_decorate_below
python
statsmodels/statsmodels
statsmodels/iolib/table.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/table.py
BSD-3-Clause
def _get_fmt(self, output_format, **fmt_dict): """Return dict, the formatting options. """ output_format = get_output_format(output_format) # first get the default formatting try: fmt = default_fmts[output_format].copy() except KeyError: raise ValueError('Unknown format: %s' % output_format) # then get any table specific formtting try: fmt.update(self.row.table.output_formats[output_format]) except AttributeError: pass # then get any row specific formtting try: fmt.update(self.row._fmt) except AttributeError: pass # finally add formatting for this instance and call fmt.update(self._fmt) fmt.update(fmt_dict) return fmt
Return dict, the formatting options.
_get_fmt
python
statsmodels/statsmodels
statsmodels/iolib/table.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/table.py
BSD-3-Clause
def format(self, width, output_format='txt', **fmt_dict): """Return string. This is the default formatter for cells. Override this to get different formating. A cell formatter must accept as arguments a cell (self) and an output format, one of ('html', 'txt', 'csv', 'latex'). It will generally respond to the datatype, one of (int, 'header', 'stub'). """ fmt = self._get_fmt(output_format, **fmt_dict) data = self.data datatype = self.datatype data_fmts = fmt.get('data_fmts') if data_fmts is None: # chk allow for deprecated use of data_fmt data_fmt = fmt.get('data_fmt') if data_fmt is None: data_fmt = '%s' data_fmts = [data_fmt] if isinstance(datatype, int): datatype = datatype % len(data_fmts) # constrain to indexes data_fmt = data_fmts[datatype] if isinstance(data_fmt, str): content = data_fmt % (data,) elif callable(data_fmt): content = data_fmt(data) else: raise TypeError("Must be a string or a callable") if datatype == 0: content = self._latex_escape(content, fmt, output_format) elif datatype in fmt: data = self._latex_escape(data, fmt, output_format) dfmt = fmt.get(datatype) try: content = dfmt % (data,) except TypeError: # dfmt is not a substitution string content = dfmt else: raise ValueError('Unknown cell datatype: %s' % datatype) align = self.alignment(output_format, **fmt) return pad(content, width, align)
Return string. This is the default formatter for cells. Override this to get different formating. A cell formatter must accept as arguments a cell (self) and an output format, one of ('html', 'txt', 'csv', 'latex'). It will generally respond to the datatype, one of (int, 'header', 'stub').
format
python
statsmodels/statsmodels
statsmodels/iolib/table.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/table.py
BSD-3-Clause
def savetxt(fname, X, names=None, fmt='%.18e', delimiter=' '): """ Save an array to a text file. This is just a copy of numpy.savetxt patched to support structured arrays or a header of names. Does not include py3 support now in savetxt. Parameters ---------- fname : filename or file handle If the filename ends in ``.gz``, the file is automatically saved in compressed gzip format. `loadtxt` understands gzipped files transparently. X : array_like Data to be saved to a text file. names : list, optional If given names will be the column header in the text file. fmt : str or sequence of strs A single format (%10.5f), a sequence of formats, or a multi-format string, e.g. 'Iteration %d -- %10.5f', in which case `delimiter` is ignored. delimiter : str Character separating columns. See Also -------- save : Save an array to a binary file in NumPy ``.npy`` format savez : Save several arrays into a ``.npz`` compressed archive Notes ----- Further explanation of the `fmt` parameter (``%[flag]width[.precision]specifier``): flags: ``-`` : left justify ``+`` : Forces to preceed result with + or -. ``0`` : Left pad the number with zeros instead of space (see width). width: Minimum number of characters to be printed. The value is not truncated if it has more characters. precision: - For integer specifiers (eg. ``d,i,o,x``), the minimum number of digits. - For ``e, E`` and ``f`` specifiers, the number of digits to print after the decimal point. - For ``g`` and ``G``, the maximum number of significant digits. - For ``s``, the maximum number of characters. specifiers: ``c`` : character ``d`` or ``i`` : signed decimal integer ``e`` or ``E`` : scientific notation with ``e`` or ``E``. ``f`` : decimal floating point ``g,G`` : use the shorter of ``e,E`` or ``f`` ``o`` : signed octal ``s`` : str of characters ``u`` : unsigned decimal integer ``x,X`` : unsigned hexadecimal integer This explanation of ``fmt`` is not complete, for an exhaustive specification see [1]_. References ---------- .. [1] `Format Specification Mini-Language <http://docs.python.org/library/string.html# format-specification-mini-language>`_, Python Documentation. Examples -------- >>> savetxt('test.out', x, delimiter=',') # x is an array >>> savetxt('test.out', (x,y,z)) # x,y,z equal sized 1D arrays >>> savetxt('test.out', x, fmt='%1.4e') # use exponential notation """ with get_file_obj(fname, 'w') as fh: X = np.asarray(X) # Handle 1-dimensional arrays if X.ndim == 1: # Common case -- 1d array of numbers if X.dtype.names is None: X = np.atleast_2d(X).T ncol = 1 # Complex dtype -- each field indicates a separate column else: ncol = len(X.dtype.descr) else: ncol = X.shape[1] # `fmt` can be a string with multiple insertion points or a list of formats. # E.g. '%10.5f\t%10d' or ('%10.5f', '$10d') if isinstance(fmt, (list, tuple)): if len(fmt) != ncol: raise AttributeError('fmt has wrong shape. %s' % str(fmt)) format = delimiter.join(fmt) elif isinstance(fmt, str): if fmt.count('%') == 1: fmt = [fmt, ]*ncol format = delimiter.join(fmt) elif fmt.count('%') != ncol: raise AttributeError('fmt has wrong number of %% formats. %s' % fmt) else: format = fmt # handle names if names is None and X.dtype.names: names = X.dtype.names if names is not None: fh.write(delimiter.join(names) + '\n') for row in X: fh.write(format % tuple(row) + '\n')
Save an array to a text file. This is just a copy of numpy.savetxt patched to support structured arrays or a header of names. Does not include py3 support now in savetxt. Parameters ---------- fname : filename or file handle If the filename ends in ``.gz``, the file is automatically saved in compressed gzip format. `loadtxt` understands gzipped files transparently. X : array_like Data to be saved to a text file. names : list, optional If given names will be the column header in the text file. fmt : str or sequence of strs A single format (%10.5f), a sequence of formats, or a multi-format string, e.g. 'Iteration %d -- %10.5f', in which case `delimiter` is ignored. delimiter : str Character separating columns. See Also -------- save : Save an array to a binary file in NumPy ``.npy`` format savez : Save several arrays into a ``.npz`` compressed archive Notes ----- Further explanation of the `fmt` parameter (``%[flag]width[.precision]specifier``): flags: ``-`` : left justify ``+`` : Forces to preceed result with + or -. ``0`` : Left pad the number with zeros instead of space (see width). width: Minimum number of characters to be printed. The value is not truncated if it has more characters. precision: - For integer specifiers (eg. ``d,i,o,x``), the minimum number of digits. - For ``e, E`` and ``f`` specifiers, the number of digits to print after the decimal point. - For ``g`` and ``G``, the maximum number of significant digits. - For ``s``, the maximum number of characters. specifiers: ``c`` : character ``d`` or ``i`` : signed decimal integer ``e`` or ``E`` : scientific notation with ``e`` or ``E``. ``f`` : decimal floating point ``g,G`` : use the shorter of ``e,E`` or ``f`` ``o`` : signed octal ``s`` : str of characters ``u`` : unsigned decimal integer ``x,X`` : unsigned hexadecimal integer This explanation of ``fmt`` is not complete, for an exhaustive specification see [1]_. References ---------- .. [1] `Format Specification Mini-Language <http://docs.python.org/library/string.html# format-specification-mini-language>`_, Python Documentation. Examples -------- >>> savetxt('test.out', x, delimiter=',') # x is an array >>> savetxt('test.out', (x,y,z)) # x,y,z equal sized 1D arrays >>> savetxt('test.out', x, fmt='%1.4e') # use exponential notation
savetxt
python
statsmodels/statsmodels
statsmodels/iolib/foreign.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/foreign.py
BSD-3-Clause
def _repr_html_(self): """Display as HTML in IPython notebook.""" return self.as_html()
Display as HTML in IPython notebook.
_repr_html_
python
statsmodels/statsmodels
statsmodels/iolib/summary2.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/summary2.py
BSD-3-Clause
def _repr_latex_(self): '''Display as LaTeX when converting IPython notebook to PDF.''' return self.as_latex()
Display as LaTeX when converting IPython notebook to PDF.
_repr_latex_
python
statsmodels/statsmodels
statsmodels/iolib/summary2.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/summary2.py
BSD-3-Clause
def add_df(self, df, index=True, header=True, float_format='%.4f', align='r'): """ Add the contents of a DataFrame to summary table Parameters ---------- df : DataFrame header : bool Reproduce the DataFrame column labels in summary table index : bool Reproduce the DataFrame row labels in summary table float_format : str Formatting to float data columns align : str Data alignment (l/c/r) """ settings = {'index': index, 'header': header, 'float_format': float_format, 'align': align} self.tables.append(df) self.settings.append(settings)
Add the contents of a DataFrame to summary table Parameters ---------- df : DataFrame header : bool Reproduce the DataFrame column labels in summary table index : bool Reproduce the DataFrame row labels in summary table float_format : str Formatting to float data columns align : str Data alignment (l/c/r)
add_df
python
statsmodels/statsmodels
statsmodels/iolib/summary2.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/summary2.py
BSD-3-Clause
def add_array(self, array, align='r', float_format="%.4f"): """Add the contents of a Numpy array to summary table Parameters ---------- array : numpy array (2D) float_format : str Formatting to array if type is float align : str Data alignment (l/c/r) """ table = pd.DataFrame(array) self.add_df(table, index=False, header=False, float_format=float_format, align=align)
Add the contents of a Numpy array to summary table Parameters ---------- array : numpy array (2D) float_format : str Formatting to array if type is float align : str Data alignment (l/c/r)
add_array
python
statsmodels/statsmodels
statsmodels/iolib/summary2.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/summary2.py
BSD-3-Clause
def add_dict(self, d, ncols=2, align='l', float_format="%.4f"): """Add the contents of a Dict to summary table Parameters ---------- d : dict Keys and values are automatically coerced to strings with str(). Users are encouraged to format them before using add_dict. ncols : int Number of columns of the output table align : str Data alignment (l/c/r) float_format : str Formatting to float data columns """ keys = [_formatter(x, float_format) for x in d.keys()] vals = [_formatter(x, float_format) for x in d.values()] data = np.array(lzip(keys, vals)) if data.shape[0] % ncols != 0: pad = ncols - (data.shape[0] % ncols) data = np.vstack([data, np.array(pad * [['', '']])]) data = np.split(data, ncols) data = reduce(lambda x, y: np.hstack([x, y]), data) self.add_array(data, align=align)
Add the contents of a Dict to summary table Parameters ---------- d : dict Keys and values are automatically coerced to strings with str(). Users are encouraged to format them before using add_dict. ncols : int Number of columns of the output table align : str Data alignment (l/c/r) float_format : str Formatting to float data columns
add_dict
python
statsmodels/statsmodels
statsmodels/iolib/summary2.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/summary2.py
BSD-3-Clause
def add_text(self, string): """Append a note to the bottom of the summary table. In ASCII tables, the note will be wrapped to table width. Notes are not indented. """ self.extra_txt.append(string)
Append a note to the bottom of the summary table. In ASCII tables, the note will be wrapped to table width. Notes are not indented.
add_text
python
statsmodels/statsmodels
statsmodels/iolib/summary2.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/summary2.py
BSD-3-Clause
def add_title(self, title=None, results=None): """Insert a title on top of the summary table. If a string is provided in the title argument, that string is printed. If no title string is provided but a results instance is provided, statsmodels attempts to construct a useful title automatically. """ if isinstance(title, str): self.title = title else: if results is not None: model = results.model.__class__.__name__ if model in _model_types: model = _model_types[model] self.title = 'Results: ' + model else: self.title = ''
Insert a title on top of the summary table. If a string is provided in the title argument, that string is printed. If no title string is provided but a results instance is provided, statsmodels attempts to construct a useful title automatically.
add_title
python
statsmodels/statsmodels
statsmodels/iolib/summary2.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/summary2.py
BSD-3-Clause
def add_base(self, results, alpha=0.05, float_format="%.4f", title=None, xname=None, yname=None): """Try to construct a basic summary instance. Parameters ---------- results : Model results instance alpha : float significance level for the confidence intervals (optional) float_format: str Float formatting for summary of parameters (optional) title : str Title of the summary table (optional) xname : list[str] of length equal to the number of parameters Names of the independent variables (optional) yname : str Name of the dependent variable (optional) """ param = summary_params(results, alpha=alpha, use_t=results.use_t) info = summary_model(results) if xname is not None: param.index = xname if yname is not None: info['Dependent Variable:'] = yname self.add_dict(info, align='l') self.add_df(param, float_format=float_format) self.add_title(title=title, results=results)
Try to construct a basic summary instance. Parameters ---------- results : Model results instance alpha : float significance level for the confidence intervals (optional) float_format: str Float formatting for summary of parameters (optional) title : str Title of the summary table (optional) xname : list[str] of length equal to the number of parameters Names of the independent variables (optional) yname : str Name of the dependent variable (optional)
add_base
python
statsmodels/statsmodels
statsmodels/iolib/summary2.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/summary2.py
BSD-3-Clause
def as_text(self): """Generate ASCII Summary Table """ tables = self.tables settings = self.settings title = self.title extra_txt = self.extra_txt pad_col, pad_index, widest = _measure_tables(tables, settings) rule_equal = widest * '=' simple_tables = _simple_tables(tables, settings, pad_col, pad_index) tab = [x.as_text() for x in simple_tables] tab = '\n'.join(tab) tab = tab.split('\n') tab[0] = rule_equal tab.append(rule_equal) tab = '\n'.join(tab) if title is not None: title = title if len(title) < widest: title = ' ' * int(widest / 2 - len(title) / 2) + title else: title = '' txt = [textwrap.wrap(x, widest) for x in extra_txt] txt = ['\n'.join(x) for x in txt] txt = '\n'.join(txt) out = '\n'.join([title, tab, txt]) return out
Generate ASCII Summary Table
as_text
python
statsmodels/statsmodels
statsmodels/iolib/summary2.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/summary2.py
BSD-3-Clause
def as_html(self): """Generate HTML Summary Table """ tables = self.tables settings = self.settings simple_tables = _simple_tables(tables, settings) tab = [x.as_html() for x in simple_tables] tab = '\n'.join(tab) temp_txt = [st.replace('\n', '<br/>\n')for st in self.extra_txt] txt = '<br/>\n'.join(temp_txt) out = '<br/>\n'.join([tab, txt]) return out
Generate HTML Summary Table
as_html
python
statsmodels/statsmodels
statsmodels/iolib/summary2.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/summary2.py
BSD-3-Clause
def as_latex(self, label=''): """Generate LaTeX Summary Table Parameters ---------- label : str Label of the summary table that can be referenced in a latex document (optional) """ tables = self.tables settings = self.settings title = self.title if title is not None: title = '\\caption{' + title + '}' else: title = '\\caption{}' label = '\\label{' + label + '}' simple_tables = _simple_tables(tables, settings) tab = [x.as_latex_tabular() for x in simple_tables] tab = '\n\n'.join(tab) to_replace = ('\\\\hline\\n\\\\hline\\n\\\\' 'end{tabular}\\n\\\\begin{tabular}{.*}\\n') if self._merge_latex: # create single tabular object for summary_col tab = re.sub(to_replace, r'\\midrule\n', tab) non_captioned = '\\begin{table}', title, label, tab, '\\end{table}' non_captioned = '\n'.join(non_captioned) txt = ' \\newline \n'.join(self.extra_txt) out = non_captioned + '\n\\bigskip\n' + txt return out
Generate LaTeX Summary Table Parameters ---------- label : str Label of the summary table that can be referenced in a latex document (optional)
as_latex
python
statsmodels/statsmodels
statsmodels/iolib/summary2.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/summary2.py
BSD-3-Clause
def _measure_tables(tables, settings): """Compare width of ascii tables in a list and calculate padding values. We add space to each col_sep to get us as close as possible to the width of the largest table. Then, we add a few spaces to the first column to pad the rest. """ simple_tables = _simple_tables(tables, settings) tab = [x.as_text() for x in simple_tables] length = [len(x.splitlines()[0]) for x in tab] len_max = max(length) pad_sep = [] pad_index = [] for i in range(len(tab)): nsep = max(tables[i].shape[1] - 1, 1) pad = int((len_max - length[i]) / nsep) pad_sep.append(pad) len_new = length[i] + nsep * pad pad_index.append(len_max - len_new) return pad_sep, pad_index, max(length)
Compare width of ascii tables in a list and calculate padding values. We add space to each col_sep to get us as close as possible to the width of the largest table. Then, we add a few spaces to the first column to pad the rest.
_measure_tables
python
statsmodels/statsmodels
statsmodels/iolib/summary2.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/summary2.py
BSD-3-Clause
def summary_model(results): """ Create a dict with information about the model """ def time_now(*args, **kwds): now = datetime.datetime.now() return now.strftime('%Y-%m-%d %H:%M') info = {} info['Model:'] = lambda x: x.model.__class__.__name__ info['Model Family:'] = lambda x: x.family.__class.__name__ info['Link Function:'] = lambda x: x.family.link.__class__.__name__ info['Dependent Variable:'] = lambda x: x.model.endog_names info['Date:'] = time_now info['No. Observations:'] = lambda x: "%#6d" % x.nobs info['Df Model:'] = lambda x: "%#6d" % x.df_model info['Df Residuals:'] = lambda x: "%#6d" % x.df_resid info['Converged:'] = lambda x: x.mle_retvals['converged'] info['No. Iterations:'] = lambda x: x.mle_retvals['iterations'] info['Method:'] = lambda x: x.method info['Norm:'] = lambda x: x.fit_options['norm'] info['Scale Est.:'] = lambda x: x.fit_options['scale_est'] info['Cov. Type:'] = lambda x: x.fit_options['cov'] rsquared_type = '' if results.k_constant else ' (uncentered)' info['R-squared' + rsquared_type + ':'] = lambda x: "%#8.3f" % x.rsquared info['Adj. R-squared' + rsquared_type + ':'] = lambda x: "%#8.3f" % x.rsquared_adj # noqa:E501 info['Pseudo R-squared:'] = lambda x: "%#8.3f" % x.prsquared info['AIC:'] = lambda x: "%8.4f" % x.aic info['BIC:'] = lambda x: "%8.4f" % x.bic info['Log-Likelihood:'] = lambda x: "%#8.5g" % x.llf info['LL-Null:'] = lambda x: "%#8.5g" % x.llnull info['LLR p-value:'] = lambda x: "%#8.5g" % x.llr_pvalue info['Deviance:'] = lambda x: "%#8.5g" % x.deviance info['Pearson chi2:'] = lambda x: "%#6.3g" % x.pearson_chi2 info['F-statistic:'] = lambda x: "%#8.4g" % x.fvalue info['Prob (F-statistic):'] = lambda x: "%#6.3g" % x.f_pvalue info['Scale:'] = lambda x: "%#8.5g" % x.scale out = {} for key, func in info.items(): try: out[key] = func(results) except (AttributeError, KeyError, NotImplementedError): # NOTE: some models do not have loglike defined (RLM), # so raise NotImplementedError pass return out
Create a dict with information about the model
summary_model
python
statsmodels/statsmodels
statsmodels/iolib/summary2.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/summary2.py
BSD-3-Clause
def summary_params(results, yname=None, xname=None, alpha=.05, use_t=True, skip_header=False, float_format="%.4f"): """create a summary table of parameters from results instance Parameters ---------- res : results instance some required information is directly taken from the result instance yname : {str, None} optional name for the endogenous variable, default is "y" xname : {list[str], None} optional names for the exogenous variables, default is "var_xx" alpha : float significance level for the confidence intervals use_t : bool indicator whether the p-values are based on the Student-t distribution (if True) or on the normal distribution (if False) skip_header : bool If false (default), then the header row is added. If true, then no header row is added. float_format : str float formatting options (e.g. ".3g") Returns ------- params_table : SimpleTable instance """ if isinstance(results, tuple): results, params, bse, tvalues, pvalues, conf_int = results else: params = results.params bse = results.bse tvalues = results.tvalues pvalues = results.pvalues conf_int = results.conf_int(alpha) data = np.array([params, bse, tvalues, pvalues]).T data = np.hstack([data, conf_int]) data = pd.DataFrame(data) if use_t: data.columns = ['Coef.', 'Std.Err.', 't', 'P>|t|', '[' + str(alpha / 2), str(1 - alpha / 2) + ']'] else: data.columns = ['Coef.', 'Std.Err.', 'z', 'P>|z|', '[' + str(alpha / 2), str(1 - alpha / 2) + ']'] if not xname: try: data.index = results.model.data.param_names except AttributeError: data.index = results.model.exog_names else: data.index = xname return data
create a summary table of parameters from results instance Parameters ---------- res : results instance some required information is directly taken from the result instance yname : {str, None} optional name for the endogenous variable, default is "y" xname : {list[str], None} optional names for the exogenous variables, default is "var_xx" alpha : float significance level for the confidence intervals use_t : bool indicator whether the p-values are based on the Student-t distribution (if True) or on the normal distribution (if False) skip_header : bool If false (default), then the header row is added. If true, then no header row is added. float_format : str float formatting options (e.g. ".3g") Returns ------- params_table : SimpleTable instance
summary_params
python
statsmodels/statsmodels
statsmodels/iolib/summary2.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/summary2.py
BSD-3-Clause
def _col_params(result, float_format='%.4f', stars=True, include_r2=False): """Stack coefficients and standard errors in single column """ # Extract parameters res = summary_params(result) # Format float for col in res.columns[:2]: res[col] = res[col].apply(lambda x: float_format % x) # Std.Errors in parentheses res.iloc[:, 1] = '(' + res.iloc[:, 1] + ')' # Significance stars if stars: idx = res.iloc[:, 3] < .1 res.loc[idx, res.columns[0]] = res.loc[idx, res.columns[0]] + '*' idx = res.iloc[:, 3] < .05 res.loc[idx, res.columns[0]] = res.loc[idx, res.columns[0]] + '*' idx = res.iloc[:, 3] < .01 res.loc[idx, res.columns[0]] = res.loc[idx, res.columns[0]] + '*' # Stack Coefs and Std.Errors res = res.iloc[:, :2] res = res.stack(**FUTURE_STACK) # Add R-squared if include_r2: rsquared = getattr(result, 'rsquared', np.nan) rsquared_adj = getattr(result, 'rsquared_adj', np.nan) r2 = pd.Series({('R-squared', ""): rsquared, ('R-squared Adj.', ""): rsquared_adj}) if r2.notnull().any(): r2 = r2.apply(lambda x: float_format % x) res = pd.concat([res, r2], axis=0) res = pd.DataFrame(res) res.columns = [str(result.model.endog_names)] return res
Stack coefficients and standard errors in single column
_col_params
python
statsmodels/statsmodels
statsmodels/iolib/summary2.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/summary2.py
BSD-3-Clause
def _col_info(result, info_dict=None): """Stack model info in a column """ if info_dict is None: info_dict = {} out = [] index = [] for i in info_dict: if isinstance(info_dict[i], dict): # this is a specific model info_dict, but not for this result... continue try: out.append(info_dict[i](result)) except AttributeError: out.append('') index.append(i) out = pd.DataFrame({str(result.model.endog_names): out}, index=index) return out
Stack model info in a column
_col_info
python
statsmodels/statsmodels
statsmodels/iolib/summary2.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/summary2.py
BSD-3-Clause
def __enter__(self): """When entering, return the embedded object""" return self._obj
When entering, return the embedded object
__enter__
python
statsmodels/statsmodels
statsmodels/iolib/openfile.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/openfile.py
BSD-3-Clause
def __exit__(self, *args): """Do not hide anything""" return False
Do not hide anything
__exit__
python
statsmodels/statsmodels
statsmodels/iolib/openfile.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/openfile.py
BSD-3-Clause
def get_file_obj(fname, mode="r", encoding=None): """ Light wrapper to handle strings, path objects and let files (anything else) pass through. It also handle '.gz' files. Parameters ---------- fname : str, path object or file-like object File to open / forward mode : str Argument passed to the 'open' or 'gzip.open' function encoding : str For Python 3 only, specify the encoding of the file Returns ------- A file-like object that is always a context-manager. If the `fname` was already a file-like object, the returned context manager *will not close the file*. """ if _is_string_like(fname): fname = Path(fname) if isinstance(fname, Path): return fname.open(mode=mode, encoding=encoding) elif hasattr(fname, "open"): return fname.open(mode=mode, encoding=encoding) try: return open(fname, mode, encoding=encoding) except TypeError: try: # Make sure the object has the write methods if "r" in mode: fname.read if "w" in mode or "a" in mode: fname.write except AttributeError: raise ValueError("fname must be a string or a file-like object") return EmptyContextManager(fname)
Light wrapper to handle strings, path objects and let files (anything else) pass through. It also handle '.gz' files. Parameters ---------- fname : str, path object or file-like object File to open / forward mode : str Argument passed to the 'open' or 'gzip.open' function encoding : str For Python 3 only, specify the encoding of the file Returns ------- A file-like object that is always a context-manager. If the `fname` was already a file-like object, the returned context manager *will not close the file*.
get_file_obj
python
statsmodels/statsmodels
statsmodels/iolib/openfile.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/openfile.py
BSD-3-Clause
def d_or_f(x, width=6): """convert number to string with either integer of float formatting This is used internally for nobs and degrees of freedom which are usually integers but can be float in some cases. Parameters ---------- x : int or float width : int only used if x is nan Returns ------- str : str number as formatted string """ if np.isnan(x): return (width - 3) * ' ' + 'NaN' if x // 1 == x: return "%#6d" % x else: return "%#8.2f" % x
convert number to string with either integer of float formatting This is used internally for nobs and degrees of freedom which are usually integers but can be float in some cases. Parameters ---------- x : int or float width : int only used if x is nan Returns ------- str : str number as formatted string
d_or_f
python
statsmodels/statsmodels
statsmodels/iolib/summary.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/summary.py
BSD-3-Clause
def ols_printer(): """ print summary table for ols models """ table = str(general_table)+'\n'+str(parameter_table) return table
print summary table for ols models
summary.ols_printer
python
statsmodels/statsmodels
statsmodels/iolib/summary.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/summary.py
BSD-3-Clause
def summary(self, yname=None, xname=None, title=0, alpha=.05, returns='text', model_info=None): """ Parameters ---------- yname : str optional, Default is `Y` xname : list[str] optional, Default is `X.#` for # in p the number of regressors Confidance interval : (0,1) not implimented title : str optional, Defualt is 'Generalized linear model' returns : str 'text', 'table', 'csv', 'latex', 'html' Returns ------- Default : returns='print' Prints the summarirized results Option : returns='text' Prints the summarirized results Option : returns='table' SimpleTable instance : summarizing the fit of a linear model. Option : returns='csv' returns a string of csv of the results, to import into a spreadsheet Option : returns='latex' Not implimented yet Option : returns='HTML' Not implimented yet Examples (needs updating) -------- >>> import statsmodels as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> ols_results = sm.OLS(data.endog, data.exog).results >>> print ols_results.summary() ... Notes ----- conf_int calculated from normal dist. """ if title == 0: title = _model_types[self.model.__class__.__name__] if xname is not None and len(xname) != len(self.params): # GH 2298 raise ValueError('User supplied xnames must have the same number of ' 'entries as the number of model parameters ' '({})'.format(len(self.params))) yname, xname = _getnames(self, yname, xname) time_now = time.localtime() time_of_day = [time.strftime("%H:%M:%S", time_now)] date = time.strftime("%a, %d %b %Y", time_now) modeltype = self.model.__class__.__name__ nobs = self.nobs df_model = self.df_model df_resid = self.df_resid #General part of the summary table, Applicable to all? models #------------------------------------------------------------ # TODO: define this generically, overwrite in model classes #replace definition of stubs data by single list #e.g. gen_left = [('Model type:', [modeltype]), ('Date:', [date]), ('Dependent Variable:', yname), # TODO: What happens with multiple names? ('df model', [df_model]) ] gen_stubs_left, gen_data_left = zip_longest(*gen_left) #transpose row col gen_title = title gen_header = None gen_table_left = SimpleTable(gen_data_left, gen_header, gen_stubs_left, title=gen_title, txt_fmt=gen_fmt ) gen_stubs_right = ('Method:', 'Time:', 'Number of Obs:', 'df resid') gen_data_right = ([modeltype], #was dist family need to look at more time_of_day, [nobs], [df_resid] ) gen_table_right = SimpleTable(gen_data_right, gen_header, gen_stubs_right, title=gen_title, txt_fmt=gen_fmt ) gen_table_left.extend_right(gen_table_right) general_table = gen_table_left # Parameters part of the summary table # ------------------------------------ # Note: this is not necessary since we standardized names, # only t versus normal tstats = {'OLS': self.t(), 'GLS': self.t(), 'GLSAR': self.t(), 'WLS': self.t(), 'RLM': self.t(), 'GLM': self.t()} prob_stats = {'OLS': self.pvalues, 'GLS': self.pvalues, 'GLSAR': self.pvalues, 'WLS': self.pvalues, 'RLM': self.pvalues, 'GLM': self.pvalues } # Dictionary to store the header names for the parameter part of the # summary table. look up by modeltype alp = str((1-alpha)*100)+'%' param_header = { 'OLS' : ['coef', 'std err', 't', 'P>|t|', alp + ' Conf. Interval'], 'GLS' : ['coef', 'std err', 't', 'P>|t|', alp + ' Conf. Interval'], 'GLSAR' : ['coef', 'std err', 't', 'P>|t|', alp + ' Conf. Interval'], 'WLS' : ['coef', 'std err', 't', 'P>|t|', alp + ' Conf. Interval'], 'GLM' : ['coef', 'std err', 't', 'P>|t|', alp + ' Conf. Interval'], #glm uses t-distribution 'RLM' : ['coef', 'std err', 'z', 'P>|z|', alp + ' Conf. Interval'] #checke z } params_stubs = xname params = self.params conf_int = self.conf_int(alpha) std_err = self.bse exog_len = lrange(len(xname)) tstat = tstats[modeltype] prob_stat = prob_stats[modeltype] # Simpletable should be able to handle the formating params_data = lzip(["%#6.4g" % (params[i]) for i in exog_len], ["%#6.4f" % (std_err[i]) for i in exog_len], ["%#6.4f" % (tstat[i]) for i in exog_len], ["%#6.4f" % (prob_stat[i]) for i in exog_len], ["(%#5g, %#5g)" % tuple(conf_int[i]) for i in exog_len]) parameter_table = SimpleTable(params_data, param_header[modeltype], params_stubs, title=None, txt_fmt=fmt_2 ) #special table #------------- #TODO: exists in linear_model, what about other models #residual diagnostics #output options #-------------- #TODO: JP the rest needs to be fixed, similar to summary in linear_model def ols_printer(): """ print summary table for ols models """ table = str(general_table)+'\n'+str(parameter_table) return table def glm_printer(): table = str(general_table)+'\n'+str(parameter_table) return table printers = {'OLS': ols_printer, 'GLM': glm_printer} if returns == 'print': try: return printers[modeltype]() except KeyError: return printers['OLS']()
Parameters ---------- yname : str optional, Default is `Y` xname : list[str] optional, Default is `X.#` for # in p the number of regressors Confidance interval : (0,1) not implimented title : str optional, Defualt is 'Generalized linear model' returns : str 'text', 'table', 'csv', 'latex', 'html' Returns ------- Default : returns='print' Prints the summarirized results Option : returns='text' Prints the summarirized results Option : returns='table' SimpleTable instance : summarizing the fit of a linear model. Option : returns='csv' returns a string of csv of the results, to import into a spreadsheet Option : returns='latex' Not implimented yet Option : returns='HTML' Not implimented yet Examples (needs updating) -------- >>> import statsmodels as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> ols_results = sm.OLS(data.endog, data.exog).results >>> print ols_results.summary() ... Notes ----- conf_int calculated from normal dist.
summary
python
statsmodels/statsmodels
statsmodels/iolib/summary.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/summary.py
BSD-3-Clause
def _getnames(self, yname=None, xname=None): '''extract names from model or construct names ''' if yname is None: if getattr(self.model, 'endog_names', None) is not None: yname = self.model.endog_names else: yname = 'y' if xname is None: if getattr(self.model, 'exog_names', None) is not None: xname = self.model.exog_names else: xname = ['var_%d' % i for i in range(len(self.params))] return yname, xname
extract names from model or construct names
_getnames
python
statsmodels/statsmodels
statsmodels/iolib/summary.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/summary.py
BSD-3-Clause
def summary_top(results, title=None, gleft=None, gright=None, yname=None, xname=None): '''generate top table(s) TODO: this still uses predefined model_methods ? allow gleft, gright to be 1 element tuples instead of filling with None? ''' #change of names ? gen_left, gen_right = gleft, gright # time and names are always included time_now = time.localtime() time_of_day = [time.strftime("%H:%M:%S", time_now)] date = time.strftime("%a, %d %b %Y", time_now) yname, xname = _getnames(results, yname=yname, xname=xname) # create dictionary with default # use lambdas because some values raise exception if they are not available default_items = dict([ ('Dependent Variable:', lambda: [yname]), ('Dep. Variable:', lambda: [yname]), ('Model:', lambda: [results.model.__class__.__name__]), ('Date:', lambda: [date]), ('Time:', lambda: time_of_day), ('Number of Obs:', lambda: [results.nobs]), ('No. Observations:', lambda: [d_or_f(results.nobs)]), ('Df Model:', lambda: [d_or_f(results.df_model)]), ('Df Residuals:', lambda: [d_or_f(results.df_resid)]), ('Log-Likelihood:', lambda: ["%#8.5g" % results.llf]) # does not exist for RLM - exception ]) if title is None: title = results.model.__class__.__name__ + 'Regression Results' if gen_left is None: # default: General part of the summary table, Applicable to all? models gen_left = [('Dep. Variable:', None), ('Model type:', None), ('Date:', None), ('No. Observations:', None), ('Df model:', None), ('Df resid:', None)] try: llf = results.llf # noqa: F841 gen_left.append(('Log-Likelihood', None)) except (AttributeError, NotImplementedError): # Might not have a log-likelihood pass gen_right = [] gen_title = title gen_header = None # replace missing (None) values with default values gen_left_ = [] for item, value in gen_left: if value is None: value = default_items[item]() # let KeyErrors raise exception gen_left_.append((item, value)) gen_left = gen_left_ if gen_right: gen_right_ = [] for item, value in gen_right: if value is None: value = default_items[item]() # let KeyErrors raise exception gen_right_.append((item, value)) gen_right = gen_right_ # check nothing was missed missing_values = [k for k,v in gen_left + gen_right if v is None] assert missing_values == [], missing_values # pad both tables to equal number of rows if gen_right: if len(gen_right) < len(gen_left): # fill up with blank lines to same length gen_right += [(' ', ' ')] * (len(gen_left) - len(gen_right)) elif len(gen_right) > len(gen_left): # fill up with blank lines to same length, just to keep it symmetric gen_left += [(' ', ' ')] * (len(gen_right) - len(gen_left)) # padding in SimpleTable does not work like I want #force extra spacing and exact string length in right table gen_right = [('%-21s' % (' '+k), v) for k,v in gen_right] gen_stubs_right, gen_data_right = zip_longest(*gen_right) #transpose row col gen_table_right = SimpleTable(gen_data_right, gen_header, gen_stubs_right, title=gen_title, txt_fmt=fmt_2cols ) else: gen_table_right = [] #because .extend_right seems works with [] #moved below so that we can pad if needed to match length of gen_right #transpose rows and columns, `unzip` gen_stubs_left, gen_data_left = zip_longest(*gen_left) #transpose row col gen_table_left = SimpleTable(gen_data_left, gen_header, gen_stubs_left, title=gen_title, txt_fmt=fmt_2cols ) gen_table_left.extend_right(gen_table_right) general_table = gen_table_left return general_table
generate top table(s) TODO: this still uses predefined model_methods ? allow gleft, gright to be 1 element tuples instead of filling with None?
summary_top
python
statsmodels/statsmodels
statsmodels/iolib/summary.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/summary.py
BSD-3-Clause
def summary_params(results, yname=None, xname=None, alpha=.05, use_t=True, skip_header=False, title=None): '''create a summary table for the parameters Parameters ---------- res : results instance some required information is directly taken from the result instance yname : {str, None} optional name for the endogenous variable, default is "y" xname : {list[str], None} optional names for the exogenous variables, default is "var_xx" alpha : float significance level for the confidence intervals use_t : bool indicator whether the p-values are based on the Student-t distribution (if True) or on the normal distribution (if False) skip_headers : bool If false (default), then the header row is added. If true, then no header row is added. Returns ------- params_table : SimpleTable instance ''' # Parameters part of the summary table # ------------------------------------ # Note: this is not necessary since we standardized names, # only t versus normal if isinstance(results, tuple): # for multivariate endog # TODO: check whether I do not want to refactor this #we need to give parameter alpha to conf_int results, params, std_err, tvalues, pvalues, conf_int = results else: params = np.asarray(results.params) std_err = np.asarray(results.bse) tvalues = np.asarray(results.tvalues) # is this sometimes called zvalues pvalues = np.asarray(results.pvalues) conf_int = np.asarray(results.conf_int(alpha)) if params.size == 0: return SimpleTable([['No Model Parameters']]) # Dictionary to store the header names for the parameter part of the # summary table. look up by modeltype if use_t: param_header = ['coef', 'std err', 't', 'P>|t|', '[' + str(alpha/2), str(1-alpha/2) + ']'] else: param_header = ['coef', 'std err', 'z', 'P>|z|', '[' + str(alpha/2), str(1-alpha/2) + ']'] if skip_header: param_header = None _, xname = _getnames(results, yname=yname, xname=xname) if len(xname) != len(params): raise ValueError('xnames and params do not have the same length') params_stubs = xname exog_idx = lrange(len(xname)) params = np.asarray(params) std_err = np.asarray(std_err) tvalues = np.asarray(tvalues) pvalues = np.asarray(pvalues) conf_int = np.asarray(conf_int) params_data = lzip([forg(params[i], prec=4) for i in exog_idx], [forg(std_err[i]) for i in exog_idx], [forg(tvalues[i]) for i in exog_idx], ["%#6.3f" % (pvalues[i]) for i in exog_idx], [forg(conf_int[i,0]) for i in exog_idx], [forg(conf_int[i,1]) for i in exog_idx]) parameter_table = SimpleTable(params_data, param_header, params_stubs, title=title, txt_fmt=fmt_params ) return parameter_table
create a summary table for the parameters Parameters ---------- res : results instance some required information is directly taken from the result instance yname : {str, None} optional name for the endogenous variable, default is "y" xname : {list[str], None} optional names for the exogenous variables, default is "var_xx" alpha : float significance level for the confidence intervals use_t : bool indicator whether the p-values are based on the Student-t distribution (if True) or on the normal distribution (if False) skip_headers : bool If false (default), then the header row is added. If true, then no header row is added. Returns ------- params_table : SimpleTable instance
summary_params
python
statsmodels/statsmodels
statsmodels/iolib/summary.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/summary.py
BSD-3-Clause
def summary_params_frame(results, yname=None, xname=None, alpha=.05, use_t=True): """ Create a summary table for the parameters Parameters ---------- res : results instance some required information is directly taken from the result instance yname : {str, None} optional name for the endogenous variable, default is "y" xname : {list[str], None} optional names for the exogenous variables, default is "var_xx" alpha : float significance level for the confidence intervals use_t : bool indicator whether the p-values are based on the Student-t distribution (if True) or on the normal distribution (if False) skip_headers : bool If false (default), then the header row is added. If true, then no header row is added. Returns ------- params_table : SimpleTable instance """ # Parameters part of the summary table # ------------------------------------ # Note: this is not necessary since we standardized names, # only t versus normal if isinstance(results, tuple): # for multivariate endog # TODO: check whether I do not want to refactor this #we need to give parameter alpha to conf_int results, params, std_err, tvalues, pvalues, conf_int = results else: params = results.params std_err = results.bse tvalues = results.tvalues #is this sometimes called zvalues pvalues = results.pvalues conf_int = results.conf_int(alpha) # Dictionary to store the header names for the parameter part of the # summary table. look up by modeltype if use_t: param_header = ['coef', 'std err', 't', 'P>|t|', 'Conf. Int. Low', 'Conf. Int. Upp.'] else: param_header = ['coef', 'std err', 'z', 'P>|z|', 'Conf. Int. Low', 'Conf. Int. Upp.'] _, xname = _getnames(results, yname=yname, xname=xname) from pandas import DataFrame table = np.column_stack((params, std_err, tvalues, pvalues, conf_int)) return DataFrame(table, columns=param_header, index=xname)
Create a summary table for the parameters Parameters ---------- res : results instance some required information is directly taken from the result instance yname : {str, None} optional name for the endogenous variable, default is "y" xname : {list[str], None} optional names for the exogenous variables, default is "var_xx" alpha : float significance level for the confidence intervals use_t : bool indicator whether the p-values are based on the Student-t distribution (if True) or on the normal distribution (if False) skip_headers : bool If false (default), then the header row is added. If true, then no header row is added. Returns ------- params_table : SimpleTable instance
summary_params_frame
python
statsmodels/statsmodels
statsmodels/iolib/summary.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/summary.py
BSD-3-Clause
def summary_params_2d(result, extras=None, endog_names=None, exog_names=None, title=None): """create summary table of regression parameters with several equations This allows interleaving of parameters with bse and/or tvalues Parameters ---------- result : result instance the result instance with params and attributes in extras extras : list[str] additional attributes to add below a parameter row, e.g. bse or tvalues endog_names : {list[str], None} names for rows of the parameter array (multivariate endog) exog_names : {list[str], None} names for columns of the parameter array (exog) alpha : float level for confidence intervals, default 0.95 title : None or string Returns ------- tables : list of SimpleTable this contains a list of all seperate Subtables table_all : SimpleTable the merged table with results concatenated for each row of the parameter array """ if endog_names is None: # TODO: note the [1:] is specific to current MNLogit endog_names = ['endog_%d' % i for i in np.unique(result.model.endog)[1:]] if exog_names is None: exog_names = ['var%d' % i for i in range(len(result.params))] # TODO: check formatting options with different values res_params = [[forg(item, prec=4) for item in row] for row in result.params] if extras: extras_list = [[['%10s' % ('(' + forg(v, prec=3).strip() + ')') for v in col] for col in getattr(result, what)] for what in extras ] data = lzip(res_params, *extras_list) data = [i for j in data for i in j] #flatten stubs = lzip(endog_names, *[['']*len(endog_names)]*len(extras)) stubs = [i for j in stubs for i in j] #flatten else: data = res_params stubs = endog_names txt_fmt = copy.deepcopy(fmt_params) txt_fmt["data_fmts"] = ["%s"]*result.params.shape[1] return SimpleTable(data, headers=exog_names, stubs=stubs, title=title, txt_fmt=txt_fmt)
create summary table of regression parameters with several equations This allows interleaving of parameters with bse and/or tvalues Parameters ---------- result : result instance the result instance with params and attributes in extras extras : list[str] additional attributes to add below a parameter row, e.g. bse or tvalues endog_names : {list[str], None} names for rows of the parameter array (multivariate endog) exog_names : {list[str], None} names for columns of the parameter array (exog) alpha : float level for confidence intervals, default 0.95 title : None or string Returns ------- tables : list of SimpleTable this contains a list of all seperate Subtables table_all : SimpleTable the merged table with results concatenated for each row of the parameter array
summary_params_2d
python
statsmodels/statsmodels
statsmodels/iolib/summary.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/summary.py
BSD-3-Clause
def summary_params_2dflat(result, endog_names=None, exog_names=None, alpha=0.05, use_t=True, keep_headers=True, endog_cols=False): """summary table for parameters that are 2d, e.g. multi-equation models Parameters ---------- result : result instance the result instance with params, bse, tvalues and conf_int endog_names : {list[str], None} names for rows of the parameter array (multivariate endog) exog_names : {list[str], None} names for columns of the parameter array (exog) alpha : float level for confidence intervals, default 0.95 use_t : bool indicator whether the p-values are based on the Student-t distribution (if True) or on the normal distribution (if False) keep_headers : bool If true (default), then sub-tables keep their headers. If false, then only the first headers are kept, the other headerse are blanked out endog_cols : bool If false (default) then params and other result statistics have equations by rows. If true, then equations are assumed to be in columns. Not implemented yet. Returns ------- tables : list of SimpleTable this contains a list of all seperate Subtables table_all : SimpleTable the merged table with results concatenated for each row of the parameter array """ res = result params = res.params if params.ndim == 2: # we've got multiple equations n_equ = params.shape[1] if len(endog_names) != params.shape[1]: raise ValueError('endog_names has wrong length') else: if len(endog_names) != len(params): raise ValueError('endog_names has wrong length') n_equ = 1 #VAR does not have conf_int #params = res.params.T # this is a convention for multi-eq models # check that we have the right length of names if not isinstance(endog_names, list): # TODO: this might be specific to multinomial logit type, move? # TODO: note, the [1:] is specific to current MNLogit endog_names = res.model.endog_names[1:] tables = [] for eq in range(n_equ): restup = (res, res.params[:,eq], res.bse[:,eq], res.tvalues[:,eq], res.pvalues[:,eq], res.conf_int(alpha)[eq]) skiph = False tble = summary_params(restup, yname=endog_names[eq], xname=exog_names, alpha=alpha, use_t=use_t, skip_header=skiph) tables.append(tble) # add titles, they will be moved to header lines in table_extend for i in range(len(endog_names)): tables[i].title = endog_names[i] table_all = table_extend(tables, keep_headers=keep_headers) return tables, table_all
summary table for parameters that are 2d, e.g. multi-equation models Parameters ---------- result : result instance the result instance with params, bse, tvalues and conf_int endog_names : {list[str], None} names for rows of the parameter array (multivariate endog) exog_names : {list[str], None} names for columns of the parameter array (exog) alpha : float level for confidence intervals, default 0.95 use_t : bool indicator whether the p-values are based on the Student-t distribution (if True) or on the normal distribution (if False) keep_headers : bool If true (default), then sub-tables keep their headers. If false, then only the first headers are kept, the other headerse are blanked out endog_cols : bool If false (default) then params and other result statistics have equations by rows. If true, then equations are assumed to be in columns. Not implemented yet. Returns ------- tables : list of SimpleTable this contains a list of all seperate Subtables table_all : SimpleTable the merged table with results concatenated for each row of the parameter array
summary_params_2dflat
python
statsmodels/statsmodels
statsmodels/iolib/summary.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/summary.py
BSD-3-Clause
def table_extend(tables, keep_headers=True): """extend a list of SimpleTables, adding titles to header of subtables This function returns the merged table as a deepcopy, in contrast to the SimpleTable extend method. Parameters ---------- tables : list of SimpleTable instances keep_headers : bool If true, then all headers are kept. If falls, then the headers of subtables are blanked out. Returns ------- table_all : SimpleTable merged tables as a single SimpleTable instance """ from copy import deepcopy for ii, t in enumerate(tables[:]): #[1:]: t = deepcopy(t) #move title to first cell of header # TODO: check if we have multiline headers if t[0].datatype == 'header': t[0][0].data = t.title t[0][0]._datatype = None t[0][0].row = t[0][1].row if not keep_headers and (ii > 0): for c in t[0][1:]: c.data = '' # add separating line and extend tables if ii == 0: table_all = t else: r1 = table_all[-1] r1.add_format('txt', row_dec_below='-') table_all.extend(t) table_all.title = None return table_all
extend a list of SimpleTables, adding titles to header of subtables This function returns the merged table as a deepcopy, in contrast to the SimpleTable extend method. Parameters ---------- tables : list of SimpleTable instances keep_headers : bool If true, then all headers are kept. If falls, then the headers of subtables are blanked out. Returns ------- table_all : SimpleTable merged tables as a single SimpleTable instance
table_extend
python
statsmodels/statsmodels
statsmodels/iolib/summary.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/summary.py
BSD-3-Clause
def _repr_html_(self): """Display as HTML in IPython notebook.""" return self.as_html()
Display as HTML in IPython notebook.
_repr_html_
python
statsmodels/statsmodels
statsmodels/iolib/summary.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/summary.py
BSD-3-Clause
def _repr_latex_(self): """Display as LaTeX when converting IPython notebook to PDF.""" return self.as_latex()
Display as LaTeX when converting IPython notebook to PDF.
_repr_latex_
python
statsmodels/statsmodels
statsmodels/iolib/summary.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/summary.py
BSD-3-Clause
def add_table_2cols(self, res, title=None, gleft=None, gright=None, yname=None, xname=None): """ Add a double table, 2 tables with one column merged horizontally Parameters ---------- res : results instance some required information is directly taken from the result instance title : str, optional if None, then a default title is used. gleft : list[tuple], optional elements for the left table, tuples are (name, value) pairs If gleft is None, then a default table is created gright : list[tuple], optional elements for the right table, tuples are (name, value) pairs yname : str, optional optional name for the endogenous variable, default is "y" xname : list[str], optional optional names for the exogenous variables, default is "var_xx". Must match the number of parameters in the model. """ table = summary_top(res, title=title, gleft=gleft, gright=gright, yname=yname, xname=xname) self.tables.append(table)
Add a double table, 2 tables with one column merged horizontally Parameters ---------- res : results instance some required information is directly taken from the result instance title : str, optional if None, then a default title is used. gleft : list[tuple], optional elements for the left table, tuples are (name, value) pairs If gleft is None, then a default table is created gright : list[tuple], optional elements for the right table, tuples are (name, value) pairs yname : str, optional optional name for the endogenous variable, default is "y" xname : list[str], optional optional names for the exogenous variables, default is "var_xx". Must match the number of parameters in the model.
add_table_2cols
python
statsmodels/statsmodels
statsmodels/iolib/summary.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/summary.py
BSD-3-Clause
def add_table_params(self, res, yname=None, xname=None, alpha=.05, use_t=True): """create and add a table for the parameter estimates Parameters ---------- res : results instance some required information is directly taken from the result instance yname : {str, None} optional name for the endogenous variable, default is "y" xname : {list[str], None} optional names for the exogenous variables, default is "var_xx" alpha : float significance level for the confidence intervals use_t : bool indicator whether the p-values are based on the Student-t distribution (if True) or on the normal distribution (if False) Returns ------- None : table is attached """ if res.params.ndim == 1: table = summary_params(res, yname=yname, xname=xname, alpha=alpha, use_t=use_t) elif res.params.ndim == 2: _, table = summary_params_2dflat(res, endog_names=yname, exog_names=xname, alpha=alpha, use_t=use_t) else: raise ValueError('params has to be 1d or 2d') self.tables.append(table)
create and add a table for the parameter estimates Parameters ---------- res : results instance some required information is directly taken from the result instance yname : {str, None} optional name for the endogenous variable, default is "y" xname : {list[str], None} optional names for the exogenous variables, default is "var_xx" alpha : float significance level for the confidence intervals use_t : bool indicator whether the p-values are based on the Student-t distribution (if True) or on the normal distribution (if False) Returns ------- None : table is attached
add_table_params
python
statsmodels/statsmodels
statsmodels/iolib/summary.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/summary.py
BSD-3-Clause
def add_extra_txt(self, etext): """add additional text that will be added at the end in text format Parameters ---------- etext : list[str] string with lines that are added to the text output. """ self.extra_txt = '\n'.join(etext)
add additional text that will be added at the end in text format Parameters ---------- etext : list[str] string with lines that are added to the text output.
add_extra_txt
python
statsmodels/statsmodels
statsmodels/iolib/summary.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/summary.py
BSD-3-Clause
def as_text(self): """return tables as string Returns ------- txt : str summary tables and extra text as one string """ txt = summary_return(self.tables, return_fmt='text') if self.extra_txt is not None: txt = txt + '\n\n' + self.extra_txt return txt
return tables as string Returns ------- txt : str summary tables and extra text as one string
as_text
python
statsmodels/statsmodels
statsmodels/iolib/summary.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/summary.py
BSD-3-Clause
def as_latex(self): """return tables as string Returns ------- latex : str summary tables and extra text as string of Latex Notes ----- This currently merges tables with different number of columns. It is recommended to use `as_latex_tabular` directly on the individual tables. """ latex = summary_return(self.tables, return_fmt='latex') if self.extra_txt is not None: latex = latex + '\n\n' + self.extra_txt.replace('\n', ' \\newline\n ') return latex
return tables as string Returns ------- latex : str summary tables and extra text as string of Latex Notes ----- This currently merges tables with different number of columns. It is recommended to use `as_latex_tabular` directly on the individual tables.
as_latex
python
statsmodels/statsmodels
statsmodels/iolib/summary.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/summary.py
BSD-3-Clause
def as_csv(self): """return tables as string Returns ------- csv : str concatenated summary tables in comma delimited format """ csv = summary_return(self.tables, return_fmt='csv') if self.extra_txt is not None: csv = csv + '\n\n' + self.extra_txt return csv
return tables as string Returns ------- csv : str concatenated summary tables in comma delimited format
as_csv
python
statsmodels/statsmodels
statsmodels/iolib/summary.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/summary.py
BSD-3-Clause
def as_html(self): """return tables as string Returns ------- html : str concatenated summary tables in HTML format """ html = summary_return(self.tables, return_fmt='html') if self.extra_txt is not None: html = html + '<br/><br/>' + self.extra_txt.replace('\n', '<br/>') return html
return tables as string Returns ------- html : str concatenated summary tables in HTML format
as_html
python
statsmodels/statsmodels
statsmodels/iolib/summary.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/summary.py
BSD-3-Clause
def save_pickle(obj, fname): """ Save the object to file via pickling. Parameters ---------- fname : {str, pathlib.Path} Filename to pickle to """ import pickle with get_file_obj(fname, "wb") as fout: pickle.dump(obj, fout, protocol=-1)
Save the object to file via pickling. Parameters ---------- fname : {str, pathlib.Path} Filename to pickle to
save_pickle
python
statsmodels/statsmodels
statsmodels/iolib/smpickle.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/smpickle.py
BSD-3-Clause
def load_pickle(fname): """ Load a previously saved object .. 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, pathlib.Path} Filename to unpickle Notes ----- This method can be used to load *both* models and results. """ import pickle with get_file_obj(fname, "rb") as fin: return pickle.load(fin)
Load a previously saved object .. 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, pathlib.Path} Filename to unpickle Notes ----- This method can be used to load *both* models and results.
load_pickle
python
statsmodels/statsmodels
statsmodels/iolib/smpickle.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/smpickle.py
BSD-3-Clause
def test_html_fmt1(self): # Limited test of custom html_fmt desired = """ <table class="simpletable"> <tr> <td></td> <th>header1</th> <th>header2</th> </tr> <tr> <th>stub1</th> <td>0.0</td> <td>1</td> </tr> <tr> <th>stub2</th> <td>2</td> <td>3.333</td> </tr> </table> """ #the previous has significant trailing whitespace that got removed #desired = '''\n<table class="simpletable">\n<tr>\n <td></td> <th>header1</th> <th>header2</th>\n</tr>\n<tr>\n <th>stub1</th> <td>0.0</td> <td>1</td> \n</tr>\n<tr>\n <th>stub2</th> <td>2</td> <td>3.333</td> \n</tr>\n</table>\n''' actual = '\n%s\n' % tbl.as_html() actual = '\n'.join(line.rstrip() for line in actual.split('\n')) #print(actual) #print(desired) #print len(actual), len(desired) assert_equal(actual, desired)
#the previous has significant trailing whitespace that got removed #desired = '''\n<table class="simpletable">\n<tr>\n <td></td> <th>header1</th> <th>header2</th>\n</tr>\n<tr>\n <th>stub1</th> <td>0.0</td> <td>1</td> \n</tr>\n<tr>\n <th>stub2</th> <td>2</td> <td>3.333</td> \n</tr>\n</table>\n
test_html_fmt1
python
statsmodels/statsmodels
statsmodels/iolib/tests/test_table_econpy.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/tests/test_table_econpy.py
BSD-3-Clause
def test_ltx_fmt1(self): # Limited test of custom ltx_fmt desired = r""" \begin{tabular}{lcc} \toprule & \textbf{header1} & \textbf{header2} \\ \midrule \textbf{stub1} & 0.0 & 1 \\ \textbf{stub2} & 2 & 3.333 \\ \bottomrule \end{tabular} """ actual = '\n%s\n' % tbl.as_latex_tabular(center=False) #print(actual) #print(desired) assert_equal(actual, desired) # Test "center=True" (the default): desired_centered = r""" \begin{center} %s \end{center} """ % desired[1:-1] actual_centered = '\n%s\n' % tbl.as_latex_tabular() assert_equal(actual_centered, desired_centered)
actual = '\n%s\n' % tbl.as_latex_tabular(center=False) #print(actual) #print(desired) assert_equal(actual, desired) # Test "center=True" (the default): desired_centered = r
test_simple_table_4.test_ltx_fmt1
python
statsmodels/statsmodels
statsmodels/iolib/tests/test_table.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/tests/test_table.py
BSD-3-Clause
def test_simple_table_4(self): # Basic test, test_simple_table_4 test uses custom txt_fmt txt_fmt1 = dict(data_fmts = ['%3.2f', '%d'], empty_cell = ' ', colwidths = 1, colsep=' * ', row_pre = '* ', row_post = ' *', table_dec_above='*', table_dec_below='*', header_dec_below='*', header_fmt = '%s', stub_fmt = '%s', title_align='r', header_align = 'r', data_aligns = "r", stubs_align = "l", fmt = 'txt' ) ltx_fmt1 = default_latex_fmt.copy() html_fmt1 = default_html_fmt.copy() cell0data = 0.0000 cell1data = 1 row0data = [cell0data, cell1data] row1data = [2, 3.333] table1data = [ row0data, row1data ] test1stubs = ('stub1', 'stub2') test1header = ('header1', 'header2') tbl = SimpleTable(table1data, test1header, test1stubs,txt_fmt=txt_fmt1, ltx_fmt=ltx_fmt1, html_fmt=html_fmt1) def test_txt_fmt1(self): # Limited test of custom txt_fmt desired = """ ***************************** * * header1 * header2 * ***************************** * stub1 * 0.00 * 1 * * stub2 * 2.00 * 3 * ***************************** """ actual = '\n%s\n' % tbl.as_text() #print(actual) #print(desired) assert_equal(actual, desired) def test_ltx_fmt1(self): # Limited test of custom ltx_fmt desired = r""" \begin{tabular}{lcc} \toprule & \textbf{header1} & \textbf{header2} \\ \midrule \textbf{stub1} & 0.0 & 1 \\ \textbf{stub2} & 2 & 3.333 \\ \bottomrule \end{tabular} """ actual = '\n%s\n' % tbl.as_latex_tabular(center=False) #print(actual) #print(desired) assert_equal(actual, desired) # Test "center=True" (the default): desired_centered = r""" \begin{center} %s \end{center} """ % desired[1:-1] actual_centered = '\n%s\n' % tbl.as_latex_tabular() assert_equal(actual_centered, desired_centered) def test_html_fmt1(self): # Limited test of custom html_fmt desired = """ <table class="simpletable"> <tr> <td></td> <th>header1</th> <th>header2</th> </tr> <tr> <th>stub1</th> <td>0.0</td> <td>1</td> </tr> <tr> <th>stub2</th> <td>2</td> <td>3.333</td> </tr> </table> """ # noqa:W291 actual = '\n%s\n' % tbl.as_html() assert_equal(actual, desired) test_txt_fmt1(self) test_ltx_fmt1(self) test_html_fmt1(self)
actual = '\n%s\n' % tbl.as_text() #print(actual) #print(desired) assert_equal(actual, desired) def test_ltx_fmt1(self): # Limited test of custom ltx_fmt desired = r
test_simple_table_4
python
statsmodels/statsmodels
statsmodels/iolib/tests/test_table.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/iolib/tests/test_table.py
BSD-3-Clause
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
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
_inverse_transform
python
statsmodels/statsmodels
statsmodels/graphics/functional.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/graphics/functional.py
BSD-3-Clause
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
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`.
_curve_constrained
python
statsmodels/statsmodels
statsmodels/graphics/functional.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/graphics/functional.py
BSD-3-Clause
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
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`
_min_max_band
python
statsmodels/statsmodels
statsmodels/graphics/functional.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/graphics/functional.py
BSD-3-Clause
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
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)
hdrboxplot._band_quantiles
python
statsmodels/statsmodels
statsmodels/graphics/functional.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/graphics/functional.py
BSD-3-Clause
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
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
hdrboxplot
python
statsmodels/statsmodels
statsmodels/graphics/functional.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/graphics/functional.py
BSD-3-Clause
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
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
fboxplot
python
statsmodels/statsmodels
statsmodels/graphics/functional.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/graphics/functional.py
BSD-3-Clause
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
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
rainbowplot
python
statsmodels/statsmodels
statsmodels/graphics/functional.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/graphics/functional.py
BSD-3-Clause
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
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.
banddepth
python
statsmodels/statsmodels
statsmodels/graphics/functional.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/graphics/functional.py
BSD-3-Clause
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()
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.
rainbow
python
statsmodels/statsmodels
statsmodels/graphics/plottools.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/graphics/plottools.py
BSD-3-Clause
def _import_mpl(): """This function is not needed outside this utils module.""" try: import matplotlib.pyplot as plt except ImportError: raise ImportError("Matplotlib is not found.") return plt
This function is not needed outside this utils module.
_import_mpl
python
statsmodels/statsmodels
statsmodels/graphics/utils.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/graphics/utils.py
BSD-3-Clause
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
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)
create_mpl_ax
python
statsmodels/statsmodels
statsmodels/graphics/utils.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/graphics/utils.py
BSD-3-Clause
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
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
create_mpl_fig
python
statsmodels/statsmodels
statsmodels/graphics/utils.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/graphics/utils.py
BSD-3-Clause