Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions lint.sh
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,11 @@ if [ "$LINT" == true ]; then
statsmodels/graphics/tsaplots.py \
statsmodels/emplike/tests/ \
statsmodels/examples/tests/ \
statsmodels/iolib/openfile.py \
statsmodels/iolib/summary2.py \
statsmodels/iolib/smpickle.py \
statsmodels/iolib/table.py \
statsmodels/iolib/tableformatting.py \
statsmodels/iolib/tests/test_pickle.py \
statsmodels/iolib/tests/results/ \
statsmodels/multivariate/pca.py \
Expand Down
12 changes: 8 additions & 4 deletions statsmodels/iolib/openfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from numpy.lib._iotools import _is_string_like
from statsmodels.compat.python import PY3


class EmptyContextManager(object):
"""
This class is needed to allow file-like object to be used as
Expand All @@ -23,6 +24,7 @@ def __exit__(self, *args):
def __getattr__(self, name):
return getattr(self._obj, name)


if PY3:
def _open(fname, mode, encoding):
if fname.endswith('.gz'):
Expand All @@ -38,14 +40,15 @@ def _open(fname, mode, encoding):
else:
return open(fname, mode)


def get_file_obj(fname, mode='r', encoding=None):
"""
Light wrapper to handle strings and let files (anything else) pass through.

It also handle '.gz' files.

Parameters
==========
----------
fname: string or file-like object
File to open / forward
mode: string
Expand All @@ -54,9 +57,10 @@ def get_file_obj(fname, mode='r', encoding=None):
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*.
-------
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):
return _open(fname, mode, encoding)
Expand Down
46 changes: 26 additions & 20 deletions statsmodels/iolib/summary2.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,12 +111,12 @@ def add_title(self, title=None, results=None):
if isinstance(title, string_types):
self.title = title
else:
try:
if results is not None:
model = results.model.__class__.__name__
if model in _model_types:
model = _model_types[model]
self.title = 'Results: ' + model
except:
else:
self.title = ''

def add_base(self, results, alpha=0.05, float_format="%.4f", title=None,
Expand Down Expand Up @@ -191,8 +191,6 @@ def as_html(self):

tables = self.tables
settings = self.settings
#TODO: this isn't used anywhere
title = self.title

simple_tables = _simple_tables(tables, settings)
tab = [x.as_html() for x in simple_tables]
Expand All @@ -217,11 +215,11 @@ def as_latex(self):
tab = '\n\\hline\n'.join(tab)

to_replace = ('\\\\hline\\n\\\\hline\\n\\\\'
'end{tabular}\\n\\\\begin{tabular}{.*}\\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)
tab = re.sub(to_replace, r'\\midrule\n', tab)

out = '\\begin{table}', title, tab, '\\end{table}'
out = '\n'.join(out)
Expand Down Expand Up @@ -253,10 +251,10 @@ def _measure_tables(tables, settings):
return pad_sep, pad_index, max(length)


# Useful stuff
# Useful stuff # TODO: be more specific
_model_types = {'OLS': 'Ordinary least squares',
'GLS': 'Generalized least squares',
'GLSAR' : 'Generalized least squares with AR(p)',
'GLSAR': 'Generalized least squares with AR(p)',
'WLS': 'Weighted least squares',
'RLM': 'Robust linear model',
'NBin': 'Negative binomial model',
Expand Down Expand Up @@ -290,7 +288,7 @@ def time_now(*args, **kwds):

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
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
Expand Down Expand Up @@ -415,7 +413,7 @@ def _col_info(result, info_dict=None):
continue
try:
out.append(info_dict[i](result))
except:
except AttributeError:
out.append('')
index.append(i)
out = pd.DataFrame({str(result.model.endog_names): out}, index=index)
Expand Down Expand Up @@ -464,9 +462,9 @@ def summary_col(results, float_format='%.4f', model_names=(), stars=False,
list of names of the regressors in the desired order. All regressors
not specified will be appended to the end of the list.
drop_omitted : bool, optional
Includes regressors that are not specified in regressor_order. If False,
regressors not specified will be appended to end of the list. If True,
only regressors in regressors_list will be included.
Includes regressors that are not specified in regressor_order. If
False, regressors not specified will be appended to end of the list.
If True, only regressors in regressors_list will be included.
"""

if not isinstance(results, list):
Expand All @@ -483,8 +481,10 @@ def summary_col(results, float_format='%.4f', model_names=(), stars=False,
for i in range(len(cols)):
cols[i].columns = [colnames[i]]

merg = lambda x, y: x.merge(y, how='outer', right_index=True,
left_index=True)
def merg(x, y):
return x.merge(y, how='outer', right_index=True,
left_index=True)

summ = reduce(merg, cols)

if regressor_order:
Expand All @@ -493,7 +493,9 @@ def summary_col(results, float_format='%.4f', model_names=(), stars=False,
unordered = [x for x in varnames if x not in regressor_order + ['']]
order = ordered + list(np.unique(unordered))

f = lambda idx: sum([[x + 'coef', x + 'stde'] for x in idx], [])
def f(idx):
return sum([[x + 'coef', x + 'stde'] for x in idx], [])

summ.index = f(pd.unique(varnames))
summ = summ.reindex(f(order))
summ.index = [x[:-4] for x in summ.index]
Expand All @@ -513,8 +515,11 @@ def summary_col(results, float_format='%.4f', model_names=(), stars=False,
# use unique column names, otherwise the merge will not succeed
for df, name in zip(cols, _make_unique([df.columns[0] for df in cols])):
df.columns = [name]
merg = lambda x, y: x.merge(y, how='outer', right_index=True,
left_index=True)

def merg(x, y):
return x.merge(y, how='outer', right_index=True,
left_index=True)

info = reduce(merg, cols)
dat = pd.DataFrame(np.vstack([summ, info])) # pd.concat better, but error
dat.columns = summ.columns
Expand All @@ -536,7 +541,7 @@ def summary_col(results, float_format='%.4f', model_names=(), stars=False,
def _formatter(element, float_format='%.4f'):
try:
out = float_format % element
except:
except (ValueError, TypeError):
out = str(element)
return out.strip()

Expand All @@ -553,7 +558,8 @@ def _df_to_simpletable(df, align='r', float_format="%.4f", header=True,
if index:
stubs = [str(x) + int(pad_index) * ' ' for x in dat.index.tolist()]
else:
dat.iloc[:, 0] = [str(x) + int(pad_index) * ' ' for x in dat.iloc[:, 0]]
dat.iloc[:, 0] = [str(x) + int(pad_index) * ' '
for x in dat.iloc[:, 0]]
stubs = None
st = SimpleTable(np.array(dat), headers=headers, stubs=stubs,
ltx_fmt=fmt_latex, txt_fmt=fmt_txt)
Expand Down
1 change: 0 additions & 1 deletion statsmodels/iolib/table.py
Original file line number Diff line number Diff line change
Expand Up @@ -453,7 +453,6 @@ def as_latex_tabular(self, center=True, **fmt_dict):
# Replace $$ due to bug in GH 5444
return '\n'.join(formatted_rows).replace('$$', ' ')


def extend_right(self, table):
"""Return None.
Extend each row of `self` with corresponding row of `table`.
Expand Down
Loading