"""A table of penalized fits: their selected coefficients side by side.
Penalized coefficients have no standard errors, so the table has one number per
cell, and pyfixest's `etable` (which `hdfe_stream.etable` extends, and which
`double_selection_stream`'s results use) does not apply. This one keeps its
names and its defaults: Great Tables output, ``keep``/``drop`` patterns,
``labels``, fixed-effect rows.
"""
from __future__ import annotations
import re
from pathlib import Path
from typing import Any
import polars as pl
from .results import PenalizedResult
TYPES = ("gt", "df", "md", "html", "tex")
_RULES = {"lambda_min": "CV, lambda_min", "lambda_1se": "CV, lambda_1se", "aic": "AIC",
"bic": "BIC", "ebic": "EBIC", "aicc": "AICc", "rigorous": "plug-in",
"given": "given"}
def _columns(models, which):
"""(fit, which) per column: each fit at its chosen penalty, or at each of
`which` (one column each)."""
if isinstance(models, PenalizedResult):
models = [models]
models = list(models)
if not models:
raise ValueError("give at least one fit")
bad = [type(m).__name__ for m in models if not isinstance(m, PenalizedResult)]
if bad:
raise TypeError(f"etable takes PenalizedResult fits; got {bad}. For "
"double_selection_stream's results use hdfe_stream.etable")
if which is None:
return [(m, None) for m in models]
whiches = [which] if isinstance(which, (str, int)) else list(which)
return [(m, w) for m in models for w in whiches]
def _matches(name, patterns):
return any(re.search(p, name) for p in patterns)
def _rule(fit, which):
if which is None:
return _RULES.get(fit.penalty_rule, fit.penalty_rule)
return _RULES.get(which, str(which))
def table_frame(models, *, which=None, keep=None, drop=None, labels=None,
felabels=None, show_fe=True, show_intercept=True, digits=3,
model_heads=None) -> pl.DataFrame:
"""The table's content, one row per line: ``section`` (``coef``, ``fe`` or
``stats``), ``term`` and one string column per fit, ``(1)``, ``(2)``, ..."""
cols = _columns(models, which)
names = [f"({i + 1})" for i in range(len(cols))]
labels, felabels = dict(labels or {}), dict(felabels or {})
keep = [keep] if isinstance(keep, str) else list(keep or [])
drop = [drop] if isinstance(drop, str) else list(drop or [])
coefs = [fit.coef(w) for fit, w in cols]
# the design order, across the fits; a term any fit selected
order = list(dict.fromkeys(t for c in coefs for t in c))
if "Intercept" in order: # first, as in a regression table
order.remove("Intercept")
order.insert(0, "Intercept")
terms = []
for term in order:
if not any(c.get(term, 0.0) != 0.0 for c in coefs):
continue
if term == "Intercept" and not show_intercept:
continue
if keep and not _matches(term, keep):
continue
if drop and _matches(term, drop):
continue
terms.append(term)
fmt = f"{{:.{digits}f}}"
rows = []
for term in terms:
cells = [fmt.format(c[term]) if c.get(term, 0.0) != 0.0 else "" for c in coefs]
marks = ["" if term not in fit.unpenalized else "†" for fit, _ in cols]
cells = [v + m if v else v for v, m in zip(cells, marks, strict=True)]
rows.append({"section": "coef", "term": labels.get(term, term),
**dict(zip(names, cells, strict=True))})
if show_fe:
fes = list(dict.fromkeys(d for fit, _ in cols for d in fit.fe_names))
for d in fes:
rows.append({"section": "fe", "term": felabels.get(d, d),
**{n: ("x" if d in fit.fe_names else "-")
for n, (fit, _) in zip(names, cols, strict=True)}})
def stat(label, values):
rows.append({"section": "stats", "term": label,
**dict(zip(names, values, strict=True))})
stat("Method", [fit.method + (f" ({fit.l1_ratio:g})"
if fit.method.startswith("Elastic net") else "")
for fit, _ in cols])
stat("Penalty", [f"{float(fit.lambdas[fit._index(w)]):.4g}" for fit, w in cols])
stat("Chosen by", [_rule(fit, w) for fit, w in cols])
stat("Selected", [f"{len(fit.selected(w))} of {len(fit.coefnames)}" for fit, w in cols])
if any(fit.cv_mean is not None for fit, _ in cols):
measures = {fit.cv_measure for fit, _ in cols if fit.cv_mean is not None}
stat("CV " + (measures.pop() if len(measures) == 1 else "error"),
[f"{float(fit.cv_mean[fit._index(w)]):.4g}" if fit.cv_mean is not None else ""
for fit, w in cols])
stat("Observations", [f"{fit.n_obs:,}" for fit, _ in cols])
frame = pl.DataFrame(rows, schema={"section": pl.Utf8, "term": pl.Utf8,
**{n: pl.Utf8 for n in names}})
heads = model_heads or [fit.depvar for fit, _ in cols]
if len(heads) != len(cols):
raise ValueError(f"model_heads has {len(heads)} entries for {len(cols)} columns")
frame.heads = heads # read by etable; not part of the frame's data
return frame
def _notes(cols, notes):
out = []
if any(fit.unpenalized for fit, _ in cols):
out.append("† unpenalized.")
out.append("Blank: not selected. Penalized coefficients have no standard errors.")
if notes:
out.append(notes)
return " ".join(out)
def _markdown(frame, heads, notes):
names = [c for c in frame.columns if c not in ("section", "term")]
lines = ["| | " + " | ".join(f"{h} {n}" for h, n in zip(heads, names, strict=True))
+ " |", "|---|" + "---|" * len(names)]
last = None
for row in frame.iter_rows(named=True):
if last is not None and row["section"] != last:
lines.append("| | " + " | ".join("" for _ in names) + " |")
last = row["section"]
lines.append(f"| {row['term']} | " + " | ".join(row[n] for n in names) + " |")
return "\n".join(lines) + f"\n\n{notes}\n"
[docs]
def etable(models: Any, *, which=None, type: str = "gt", keep=None, drop=None,
labels: dict | None = None, felabels: dict | None = None, show_fe: bool = True,
show_intercept: bool = True, digits: int = 3, model_heads: list | None = None,
notes: str = "", file_name: str | Path | None = None) -> Any:
"""A table of penalized fits: their selected coefficients side by side,
with the fixed effects and each fit's penalty, how it was chosen, the
number selected, the cross-validated error and N.
Parameters
----------
models : PenalizedResult or list of them
One column each.
which : str or list, optional
Where on each fit's path: by default its chosen penalty;
``"lambda_min"``, ``"lambda_1se"``, a criterion or a path index; a
list makes one column per fit and entry (``["lambda_min",
"lambda_1se"]`` puts the two side by side).
type : {"gt", "df", "md", "html", "tex"}, default "gt"
A Great Tables table, a Polars DataFrame (columns ``section``,
``term``, ``(1)``, ...), Markdown, HTML or LaTeX text.
keep, drop : str or list of str, optional
Regular expressions: keep only the coefficients that match one of
`keep`, then drop those that match one of `drop` (as pyfixest's).
labels, felabels : dict, optional
New names for coefficients and fixed effects.
show_fe : bool, default True
Rows marking which fixed effects each fit partials out.
show_intercept : bool, default True
The intercept's row (fits without fixed effects).
digits : int, default 3
Decimals of the coefficients.
model_heads : list of str, optional
Column headings; default the outcome of each fit.
notes : str, optional
Added to the table's notes.
file_name : str or Path, optional
Also write the table there (HTML, Markdown or LaTeX by `type`; with
``type="gt"``, HTML).
Returns
-------
great_tables.GT, polars.DataFrame or str
"""
if type not in TYPES:
raise ValueError(f"type must be one of {TYPES}")
cols = _columns(models, which)
frame = table_frame(models, which=which, keep=keep, drop=drop, labels=labels,
felabels=felabels, show_fe=show_fe, show_intercept=show_intercept,
digits=digits, model_heads=model_heads)
heads = frame.heads
text_notes = _notes(cols, notes)
if type == "df":
return frame
if type == "md":
out = _markdown(frame, heads, text_notes)
if file_name is not None:
Path(file_name).write_text(out)
return out
gt = _great_table(frame, heads, text_notes)
if type == "gt":
if file_name is not None:
Path(file_name).write_text(gt.as_raw_html())
return gt
out = gt.as_raw_html() if type == "html" else gt.as_latex()
if file_name is not None:
Path(file_name).write_text(out)
return out
def _great_table(frame, heads, notes):
try:
from great_tables import GT
except ImportError as exc:
raise ImportError("etable(type='gt', 'html' or 'tex') needs great_tables; install "
"it (pip install great_tables), or use type='df' or 'md'") from exc
names = [c for c in frame.columns if c not in ("section", "term")]
groups = {"coef": "Coefficients", "fe": "Fixed effects", "stats": "Fit"}
data = frame.with_columns(pl.col("section").replace_strict(groups))
gt = GT(data, rowname_col="term", groupname_col="section")
# a spanner per run of columns with the same heading, as pyfixest's etable
start = 0
for i in range(1, len(names) + 1):
if i == len(names) or heads[i] != heads[start]:
gt = gt.tab_spanner(label=heads[start], columns=names[start:i],
id=f"head{start}")
start = i
gt = gt.cols_align(align="center", columns=names).tab_source_note(notes)
return gt