paneldx 0.3.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- paneldx/__init__.py +28 -0
- paneldx/audit.py +157 -0
- paneldx/cli.py +135 -0
- paneldx/keys.py +314 -0
- paneldx/py.typed +0 -0
- paneldx/report.py +188 -0
- paneldx/traps.py +267 -0
- paneldx-0.3.1.dist-info/METADATA +239 -0
- paneldx-0.3.1.dist-info/RECORD +13 -0
- paneldx-0.3.1.dist-info/WHEEL +4 -0
- paneldx-0.3.1.dist-info/entry_points.txt +2 -0
- paneldx-0.3.1.dist-info/licenses/LICENSE +202 -0
- paneldx-0.3.1.dist-info/licenses/NOTICE +15 -0
paneldx/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
from .audit import AuditResult, audit
|
|
2
|
+
from .keys import KeyReport, discover_keys, entity_key, validate_key
|
|
3
|
+
from .report import to_html
|
|
4
|
+
from .traps import (
|
|
5
|
+
BaselineReport,
|
|
6
|
+
CounterReport,
|
|
7
|
+
LeakageReport,
|
|
8
|
+
detect_counters,
|
|
9
|
+
persistence_baseline,
|
|
10
|
+
target_leakage,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"AuditResult",
|
|
15
|
+
"BaselineReport",
|
|
16
|
+
"CounterReport",
|
|
17
|
+
"KeyReport",
|
|
18
|
+
"LeakageReport",
|
|
19
|
+
"audit",
|
|
20
|
+
"detect_counters",
|
|
21
|
+
"discover_keys",
|
|
22
|
+
"entity_key",
|
|
23
|
+
"persistence_baseline",
|
|
24
|
+
"target_leakage",
|
|
25
|
+
"to_html",
|
|
26
|
+
"validate_key",
|
|
27
|
+
]
|
|
28
|
+
__version__ = "0.3.1"
|
paneldx/audit.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"""Run every check in one pass and collect the findings."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
|
|
8
|
+
import pandas as pd
|
|
9
|
+
|
|
10
|
+
from .keys import KeyReport, discover_keys, validate_key
|
|
11
|
+
from .traps import (
|
|
12
|
+
BaselineReport,
|
|
13
|
+
CounterReport,
|
|
14
|
+
LeakageReport,
|
|
15
|
+
detect_counters,
|
|
16
|
+
persistence_baseline,
|
|
17
|
+
target_leakage,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
__all__ = ["AuditResult", "audit"]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class AuditResult:
|
|
25
|
+
"""Result of a full audit."""
|
|
26
|
+
|
|
27
|
+
n_rows: int
|
|
28
|
+
n_columns: int
|
|
29
|
+
time_col: str
|
|
30
|
+
n_periods: int
|
|
31
|
+
key_was_supplied: bool
|
|
32
|
+
key_reports: list[KeyReport] = field(default_factory=list)
|
|
33
|
+
counters: CounterReport | None = None
|
|
34
|
+
leakage: LeakageReport | None = None
|
|
35
|
+
baseline: BaselineReport | None = None
|
|
36
|
+
target: str | None = None
|
|
37
|
+
source: str | None = None
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def chosen(self) -> KeyReport | None:
|
|
41
|
+
"""Key the rest of the audit ran under."""
|
|
42
|
+
return self.key_reports[0] if self.key_reports else None
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def findings(self) -> list[tuple[str, str, str]]:
|
|
46
|
+
"""(severity, headline, detail) tuples, most severe first."""
|
|
47
|
+
out: list[tuple[str, str, str]] = []
|
|
48
|
+
key = self.chosen
|
|
49
|
+
|
|
50
|
+
if key is None:
|
|
51
|
+
out.append(("fail", "No usable entity key",
|
|
52
|
+
"Nothing in this table behaves like an entity tracked over time."))
|
|
53
|
+
elif key.verdict.startswith(("NOT SUPPORTED", "invalid")):
|
|
54
|
+
out.append((
|
|
55
|
+
"fail",
|
|
56
|
+
f"Entity key is not supported by the data ({' + '.join(key.key)})",
|
|
57
|
+
"Lags, differences, trajectories and grouped splits built on "
|
|
58
|
+
"this key are unreliable. " + key.verdict,
|
|
59
|
+
))
|
|
60
|
+
elif key.verdict.startswith("weak"):
|
|
61
|
+
out.append((
|
|
62
|
+
"warn",
|
|
63
|
+
f"Entity key is only weakly supported ({' + '.join(key.key)})",
|
|
64
|
+
f"Explains {key.evidence_frac:.0%} of columns. Inspect the listed "
|
|
65
|
+
"invariants and counters before relying on it.",
|
|
66
|
+
))
|
|
67
|
+
else:
|
|
68
|
+
out.append((
|
|
69
|
+
"pass",
|
|
70
|
+
f"Entity key holds up ({' + '.join(key.key)})",
|
|
71
|
+
f"Explains {key.evidence_frac:.0%} of columns across "
|
|
72
|
+
f"{key.n_entities:,} entities.",
|
|
73
|
+
))
|
|
74
|
+
|
|
75
|
+
if self.leakage is not None:
|
|
76
|
+
if self.leakage.verdict.startswith("LEAKING"):
|
|
77
|
+
out.insert(0, ("fail", f"Target '{self.target}' is inside its own features",
|
|
78
|
+
self.leakage.verdict))
|
|
79
|
+
elif self.leakage.verdict.startswith("SUSPECT"):
|
|
80
|
+
out.append(("warn", f"Target '{self.target}' is largely reconstructible",
|
|
81
|
+
self.leakage.verdict))
|
|
82
|
+
else:
|
|
83
|
+
out.append(("pass", f"Target '{self.target}' is not linearly reconstructible",
|
|
84
|
+
self.leakage.verdict))
|
|
85
|
+
|
|
86
|
+
if self.baseline is not None and self.baseline.n_pairs >= 20:
|
|
87
|
+
sev = "warn" if self.baseline.persistence_r2 >= 0.70 else "pass"
|
|
88
|
+
out.append((
|
|
89
|
+
sev,
|
|
90
|
+
f"Carry-forward alone scores R2 {self.baseline.persistence_r2:.3f} "
|
|
91
|
+
f"on '{self.target}'",
|
|
92
|
+
self.baseline.verdict,
|
|
93
|
+
))
|
|
94
|
+
|
|
95
|
+
if self.counters and self.counters.counters:
|
|
96
|
+
out.append((
|
|
97
|
+
"warn",
|
|
98
|
+
f"{len(self.counters.counters)} cumulative counter(s) among the features",
|
|
99
|
+
"Lifetime totals barely move between periods. Difference them into "
|
|
100
|
+
"per-period flows before modelling.",
|
|
101
|
+
))
|
|
102
|
+
|
|
103
|
+
order = {"fail": 0, "warn": 1, "pass": 2}
|
|
104
|
+
return sorted(out, key=lambda f: order[f[0]])
|
|
105
|
+
|
|
106
|
+
@property
|
|
107
|
+
def worst(self) -> str:
|
|
108
|
+
"""Overall severity: 'fail', 'warn' or 'pass'."""
|
|
109
|
+
sev = {f[0] for f in self.findings}
|
|
110
|
+
return "fail" if "fail" in sev else "warn" if "warn" in sev else "pass"
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def audit(
|
|
114
|
+
df: pd.DataFrame,
|
|
115
|
+
time_col: str,
|
|
116
|
+
*,
|
|
117
|
+
key: str | Sequence[str] | None = None,
|
|
118
|
+
target: str | None = None,
|
|
119
|
+
max_columns: int = 2,
|
|
120
|
+
top_k: int = 3,
|
|
121
|
+
source: str | None = None,
|
|
122
|
+
) -> AuditResult:
|
|
123
|
+
"""Check a panel end to end.
|
|
124
|
+
|
|
125
|
+
Validates `key` if given, otherwise searches for one and runs the rest of
|
|
126
|
+
the audit under the best candidate.
|
|
127
|
+
"""
|
|
128
|
+
if time_col not in df.columns:
|
|
129
|
+
raise KeyError(f"time column {time_col!r} not in frame")
|
|
130
|
+
|
|
131
|
+
result = AuditResult(
|
|
132
|
+
n_rows=len(df),
|
|
133
|
+
n_columns=len(df.columns),
|
|
134
|
+
time_col=time_col,
|
|
135
|
+
n_periods=int(df[time_col].nunique()),
|
|
136
|
+
key_was_supplied=key is not None,
|
|
137
|
+
target=target,
|
|
138
|
+
source=source,
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
if key is not None:
|
|
142
|
+
result.key_reports = [validate_key(df, key, time_col)]
|
|
143
|
+
else:
|
|
144
|
+
result.key_reports = discover_keys(
|
|
145
|
+
df, time_col, max_columns=max_columns, top_k=top_k
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
chosen = result.chosen
|
|
149
|
+
if chosen is not None:
|
|
150
|
+
result.counters = detect_counters(df, list(chosen.key), time_col)
|
|
151
|
+
|
|
152
|
+
if target is not None:
|
|
153
|
+
result.leakage = target_leakage(df, target)
|
|
154
|
+
if chosen is not None:
|
|
155
|
+
result.baseline = persistence_baseline(df, list(chosen.key), time_col, target)
|
|
156
|
+
|
|
157
|
+
return result
|
paneldx/cli.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"""Command line entry point.
|
|
2
|
+
|
|
3
|
+
paneldx audit data.csv --time quarter
|
|
4
|
+
paneldx audit panel.xlsx --time t --key patient_id --target risk --html out.html
|
|
5
|
+
|
|
6
|
+
Exits 1 when the audit finds a defect that invalidates within-entity analysis.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import argparse
|
|
12
|
+
import sys
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
import pandas as pd
|
|
16
|
+
|
|
17
|
+
from .audit import audit
|
|
18
|
+
from .report import to_html
|
|
19
|
+
|
|
20
|
+
_LOADERS = {
|
|
21
|
+
".csv": pd.read_csv,
|
|
22
|
+
".tsv": lambda p: pd.read_csv(p, sep="\t"),
|
|
23
|
+
".parquet": pd.read_parquet,
|
|
24
|
+
".feather": pd.read_feather,
|
|
25
|
+
".json": pd.read_json,
|
|
26
|
+
}
|
|
27
|
+
_EXCEL = {".xlsx", ".xls", ".xlsm"}
|
|
28
|
+
|
|
29
|
+
_CHIP = {"fail": "FAIL", "warn": "WARN", "pass": "PASS"}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _load(path: Path, sheet: str | int | None) -> pd.DataFrame:
|
|
33
|
+
suffix = path.suffix.lower()
|
|
34
|
+
if suffix in _EXCEL:
|
|
35
|
+
return pd.read_excel(path, sheet_name=sheet if sheet is not None else 0)
|
|
36
|
+
loader = _LOADERS.get(suffix)
|
|
37
|
+
if loader is None:
|
|
38
|
+
raise SystemExit(
|
|
39
|
+
f"paneldx: don't know how to read {suffix or 'a file with no extension'!r}. "
|
|
40
|
+
f"Supported: {', '.join(sorted(set(_LOADERS) | _EXCEL))}"
|
|
41
|
+
)
|
|
42
|
+
return loader(path)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _add_audit_args(p: argparse.ArgumentParser) -> None:
|
|
46
|
+
p.add_argument("data", type=Path, help="CSV, TSV, Excel, Parquet, Feather or JSON")
|
|
47
|
+
p.add_argument("--time", required=True, metavar="COL",
|
|
48
|
+
help="column holding the period")
|
|
49
|
+
p.add_argument("--key", nargs="+", metavar="COL",
|
|
50
|
+
help="entity key to validate (omit to search for one)")
|
|
51
|
+
p.add_argument("--target", metavar="COL",
|
|
52
|
+
help="target column, to test for leakage and persistence")
|
|
53
|
+
p.add_argument("--html", type=Path, metavar="PATH",
|
|
54
|
+
help="also write a standalone HTML report here")
|
|
55
|
+
p.add_argument("--sheet", default=None, help="Excel sheet name or index")
|
|
56
|
+
p.add_argument("--max-columns", type=int, default=2, metavar="N",
|
|
57
|
+
help="largest key combination to search (default 2)")
|
|
58
|
+
p.add_argument("--top-k", type=int, default=3, metavar="N",
|
|
59
|
+
help="how many key candidates to report (default 3)")
|
|
60
|
+
p.add_argument("--quiet", action="store_true", help="print findings only")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _run_audit(args: argparse.Namespace) -> int:
|
|
64
|
+
if not args.data.exists():
|
|
65
|
+
raise SystemExit(f"paneldx: no such file: {args.data}")
|
|
66
|
+
|
|
67
|
+
try:
|
|
68
|
+
df = _load(args.data, args.sheet)
|
|
69
|
+
except SystemExit:
|
|
70
|
+
raise
|
|
71
|
+
except Exception as exc:
|
|
72
|
+
raise SystemExit(f"paneldx: could not read {args.data.name}: {exc}") from exc
|
|
73
|
+
|
|
74
|
+
try:
|
|
75
|
+
result = audit(
|
|
76
|
+
df,
|
|
77
|
+
args.time,
|
|
78
|
+
key=args.key,
|
|
79
|
+
target=args.target,
|
|
80
|
+
max_columns=args.max_columns,
|
|
81
|
+
top_k=args.top_k,
|
|
82
|
+
source=args.data.name,
|
|
83
|
+
)
|
|
84
|
+
except (KeyError, ValueError) as exc:
|
|
85
|
+
# Bad input, not a crash: a missing column or too few periods deserves
|
|
86
|
+
# one clear line, not a traceback.
|
|
87
|
+
msg = exc.args[0] if exc.args else exc
|
|
88
|
+
raise SystemExit(f"paneldx: {msg}") from exc
|
|
89
|
+
|
|
90
|
+
print(f"\n{args.data.name}: {result.n_rows:,} rows x {result.n_columns} columns, "
|
|
91
|
+
f"{result.n_periods} periods of '{result.time_col}'\n")
|
|
92
|
+
|
|
93
|
+
for sev, head, detail in result.findings:
|
|
94
|
+
print(f" [{_CHIP[sev]}] {head}")
|
|
95
|
+
print(f" {detail}\n")
|
|
96
|
+
|
|
97
|
+
if not args.quiet:
|
|
98
|
+
if result.chosen is not None:
|
|
99
|
+
print("─" * 62)
|
|
100
|
+
print(result.chosen)
|
|
101
|
+
if result.counters is not None and result.counters.counters:
|
|
102
|
+
print("\n" + "─" * 62)
|
|
103
|
+
print(result.counters)
|
|
104
|
+
if result.leakage is not None:
|
|
105
|
+
print("\n" + "─" * 62)
|
|
106
|
+
print(result.leakage)
|
|
107
|
+
if result.baseline is not None:
|
|
108
|
+
print("\n" + "─" * 62)
|
|
109
|
+
print(result.baseline)
|
|
110
|
+
|
|
111
|
+
if args.html:
|
|
112
|
+
args.html.write_text(to_html(result, title=f"paneldx: {args.data.name}"),
|
|
113
|
+
encoding="utf-8")
|
|
114
|
+
print(f"\nreport written to {args.html}")
|
|
115
|
+
|
|
116
|
+
return 1 if result.worst == "fail" else 0
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def main(argv: list[str] | None = None) -> int:
|
|
120
|
+
parser = argparse.ArgumentParser(
|
|
121
|
+
prog="paneldx",
|
|
122
|
+
description="Check that a longitudinal dataset is what it claims to be.",
|
|
123
|
+
)
|
|
124
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
125
|
+
_add_audit_args(sub.add_parser("audit", help="run every check over a panel"))
|
|
126
|
+
|
|
127
|
+
args = parser.parse_args(argv)
|
|
128
|
+
if args.command == "audit":
|
|
129
|
+
return _run_audit(args)
|
|
130
|
+
parser.error(f"unknown command {args.command!r}")
|
|
131
|
+
return 2
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
if __name__ == "__main__":
|
|
135
|
+
sys.exit(main())
|
paneldx/keys.py
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
"""Entity key discovery and validation for panel data."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterable, Sequence
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from itertools import combinations
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
import pandas as pd
|
|
11
|
+
|
|
12
|
+
__all__ = ["KeyReport", "discover_keys", "entity_key", "validate_key"]
|
|
13
|
+
|
|
14
|
+
# Loose on purpose: real keys collide, and real columns carry typos and backfills.
|
|
15
|
+
_INVARIANT_TOL = 0.02
|
|
16
|
+
_MONOTONE_TOL = 0.05
|
|
17
|
+
_DUPLICATE_TOL = 0.01
|
|
18
|
+
_NULL_GAP_TOL = 0.05
|
|
19
|
+
|
|
20
|
+
_MIN_ENTITIES = 20
|
|
21
|
+
_MIN_PERIODS_PER_ENTITY = 2
|
|
22
|
+
|
|
23
|
+
_SUPPORTED = 0.40
|
|
24
|
+
_WEAK = 0.15
|
|
25
|
+
|
|
26
|
+
_SEP = "\x1f"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class KeyReport:
|
|
31
|
+
"""Verdict on one candidate key."""
|
|
32
|
+
|
|
33
|
+
key: tuple[str, ...]
|
|
34
|
+
n_entities: int
|
|
35
|
+
n_rows_covered: int
|
|
36
|
+
coverage: float
|
|
37
|
+
duplicate_rate: float
|
|
38
|
+
invariant_cols: list[str] = field(default_factory=list)
|
|
39
|
+
monotone_cols: list[str] = field(default_factory=list)
|
|
40
|
+
invariance_violation: float = np.nan
|
|
41
|
+
monotonicity_violation: float = np.nan
|
|
42
|
+
null_invariance_violation: float = np.nan
|
|
43
|
+
null_monotonicity_violation: float = np.nan
|
|
44
|
+
n_usable_cols: int = 0
|
|
45
|
+
evidence: float = 0.0
|
|
46
|
+
evidence_frac: float = 0.0
|
|
47
|
+
verdict: str = "unknown"
|
|
48
|
+
|
|
49
|
+
def __str__(self) -> str: # pragma: no cover
|
|
50
|
+
return "\n".join([
|
|
51
|
+
f"key: {' + '.join(self.key)}",
|
|
52
|
+
f" entities {self.n_entities:,} "
|
|
53
|
+
f"(covering {self.coverage:.1%} of rows)",
|
|
54
|
+
f" duplicate rows {self.duplicate_rate:.2%} of (entity, period) cells",
|
|
55
|
+
f" invariant columns {len(self.invariant_cols)}"
|
|
56
|
+
+ (f" {self.invariant_cols[:4]}" if self.invariant_cols else ""),
|
|
57
|
+
f" monotone columns {len(self.monotone_cols)}"
|
|
58
|
+
+ (f" {self.monotone_cols[:4]}" if self.monotone_cols else ""),
|
|
59
|
+
f" invariance breach {self.invariance_violation:.3f}"
|
|
60
|
+
f" (shuffled: {self.null_invariance_violation:.3f})",
|
|
61
|
+
f" monotonicity breach {self.monotonicity_violation:.3f}"
|
|
62
|
+
f" (shuffled: {self.null_monotonicity_violation:.3f})",
|
|
63
|
+
f" columns explained {self.evidence:.0f} of {self.n_usable_cols}"
|
|
64
|
+
f" ({self.evidence_frac:.0%})",
|
|
65
|
+
f" VERDICT {self.verdict}",
|
|
66
|
+
])
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def entity_key(df: pd.DataFrame, key: Sequence[str]) -> pd.Series:
|
|
70
|
+
"""Collapse key columns into one entity label."""
|
|
71
|
+
# Vectorised concat, not .agg(join, axis=1): the search calls this once per
|
|
72
|
+
# candidate, where the row-wise form is ~19x slower and dominates runtime.
|
|
73
|
+
parts = [df[c].astype(str) for c in key]
|
|
74
|
+
out = parts[0]
|
|
75
|
+
for part in parts[1:]:
|
|
76
|
+
out = out + _SEP + part
|
|
77
|
+
return out
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _usable_columns(df: pd.DataFrame, key: Sequence[str], time_col: str) -> list[str]:
|
|
81
|
+
skip = set(key) | {time_col}
|
|
82
|
+
# Globally constant columns are invariant under any key, so they say nothing
|
|
83
|
+
# about whether this one is right.
|
|
84
|
+
return [
|
|
85
|
+
c for c in df.columns
|
|
86
|
+
if c not in skip and df[c].nunique(dropna=False) > 1
|
|
87
|
+
]
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _invariance_rates(
|
|
91
|
+
df: pd.DataFrame, entity: pd.Series, cols: Iterable[str]
|
|
92
|
+
) -> dict[str, float]:
|
|
93
|
+
"""Fraction of entities showing more than one value, per column."""
|
|
94
|
+
grouped = df.groupby(entity, sort=False)
|
|
95
|
+
return {c: float((grouped[c].nunique(dropna=False) > 1).mean()) for c in cols}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _monotonicity_rates(
|
|
99
|
+
df: pd.DataFrame, entity: pd.Series, time: pd.Series, cols: Iterable[str]
|
|
100
|
+
) -> dict[str, float]:
|
|
101
|
+
"""Fraction of within-entity steps that decrease, per counter-like column."""
|
|
102
|
+
order = np.lexsort((time.values, entity.values))
|
|
103
|
+
ent = entity.values[order]
|
|
104
|
+
same_entity = ent[1:] == ent[:-1]
|
|
105
|
+
if not same_entity.any():
|
|
106
|
+
return {}
|
|
107
|
+
|
|
108
|
+
rates = {}
|
|
109
|
+
for c in cols:
|
|
110
|
+
if not pd.api.types.is_numeric_dtype(df[c]):
|
|
111
|
+
continue
|
|
112
|
+
v = df[c].values[order].astype("float64")
|
|
113
|
+
if np.nanmin(v) < 0:
|
|
114
|
+
continue
|
|
115
|
+
step = np.diff(v)
|
|
116
|
+
valid = same_entity & np.isfinite(step)
|
|
117
|
+
if valid.sum() < _MIN_ENTITIES:
|
|
118
|
+
continue
|
|
119
|
+
# Skip columns that barely move. A constant column has steps of zero, so
|
|
120
|
+
# it would pass "never decreases" and be scored as a counter when it is
|
|
121
|
+
# really just invariant.
|
|
122
|
+
if (step[valid] != 0).mean() < 0.5:
|
|
123
|
+
continue
|
|
124
|
+
rates[c] = float((step[valid] < 0).mean())
|
|
125
|
+
return rates
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _shuffled_entity(
|
|
129
|
+
entity: pd.Series, time: pd.Series, rng: np.random.Generator
|
|
130
|
+
) -> pd.Series:
|
|
131
|
+
"""Entity labels permuted within each period.
|
|
132
|
+
|
|
133
|
+
Keeps the panel's shape but destroys any true row-to-row correspondence.
|
|
134
|
+
"""
|
|
135
|
+
out = entity.copy()
|
|
136
|
+
for _, idx in time.groupby(time, sort=False).groups.items():
|
|
137
|
+
vals = entity.loc[idx].values.copy()
|
|
138
|
+
rng.shuffle(vals)
|
|
139
|
+
out.loc[idx] = vals
|
|
140
|
+
return out
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _mean_rate(dicts: list[dict[str, float]], col: str) -> float:
|
|
144
|
+
vals = [d[col] for d in dicts if col in d]
|
|
145
|
+
return float(np.mean(vals)) if vals else np.nan
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def validate_key(
|
|
149
|
+
df: pd.DataFrame,
|
|
150
|
+
key: str | Sequence[str],
|
|
151
|
+
time_col: str,
|
|
152
|
+
*,
|
|
153
|
+
n_shuffles: int = 3,
|
|
154
|
+
random_state: int = 0,
|
|
155
|
+
) -> KeyReport:
|
|
156
|
+
"""Test whether `key` identifies entities tracked across `time_col`.
|
|
157
|
+
|
|
158
|
+
Scores how many columns resolve into invariants (constant within an entity)
|
|
159
|
+
or counters (never decreasing), against a null where entity labels are
|
|
160
|
+
shuffled within each period.
|
|
161
|
+
|
|
162
|
+
``evidence_frac`` is the share of columns explained: >= 0.40 supported,
|
|
163
|
+
0.15 to 0.40 weak, below that not supported. Share beats count, since row
|
|
164
|
+
ordering explains only the columns driving the order.
|
|
165
|
+
"""
|
|
166
|
+
key = (key,) if isinstance(key, str) else tuple(key)
|
|
167
|
+
missing = [c for c in (*key, time_col) if c not in df.columns]
|
|
168
|
+
if missing:
|
|
169
|
+
raise KeyError(f"columns not in frame: {missing}")
|
|
170
|
+
|
|
171
|
+
work = df.dropna(subset=list(key)).copy()
|
|
172
|
+
entity = entity_key(work, key)
|
|
173
|
+
time = work[time_col]
|
|
174
|
+
|
|
175
|
+
per_period = work.groupby([entity, time], sort=False).size()
|
|
176
|
+
duplicate_rate = float((per_period > 1).mean()) if len(per_period) else 1.0
|
|
177
|
+
|
|
178
|
+
counts = entity.value_counts()
|
|
179
|
+
mask = entity.isin(counts[counts >= _MIN_PERIODS_PER_ENTITY].index)
|
|
180
|
+
work, entity, time = work[mask], entity[mask], time[mask]
|
|
181
|
+
|
|
182
|
+
report = KeyReport(
|
|
183
|
+
key=key,
|
|
184
|
+
n_entities=int(entity.nunique()),
|
|
185
|
+
n_rows_covered=len(work),
|
|
186
|
+
coverage=float(len(work) / max(len(df), 1)),
|
|
187
|
+
duplicate_rate=duplicate_rate,
|
|
188
|
+
)
|
|
189
|
+
if report.n_entities < _MIN_ENTITIES:
|
|
190
|
+
report.verdict = "too few entities to judge"
|
|
191
|
+
return report
|
|
192
|
+
|
|
193
|
+
cols = _usable_columns(work, key, time_col)
|
|
194
|
+
inv = _invariance_rates(work, entity, cols)
|
|
195
|
+
mono = _monotonicity_rates(work, entity, time, cols)
|
|
196
|
+
|
|
197
|
+
rng = np.random.default_rng(random_state)
|
|
198
|
+
null_inv: list[dict[str, float]] = []
|
|
199
|
+
null_mono: list[dict[str, float]] = []
|
|
200
|
+
for _ in range(n_shuffles):
|
|
201
|
+
shuffled = _shuffled_entity(entity, time, rng)
|
|
202
|
+
null_inv.append(_invariance_rates(work, shuffled, cols))
|
|
203
|
+
null_mono.append(_monotonicity_rates(work, shuffled, time, cols))
|
|
204
|
+
|
|
205
|
+
# A column counts only if the key explains it and the null does not.
|
|
206
|
+
report.invariant_cols = [
|
|
207
|
+
c for c, rate in inv.items()
|
|
208
|
+
if rate <= _INVARIANT_TOL and _mean_rate(null_inv, c) > _INVARIANT_TOL * 2
|
|
209
|
+
]
|
|
210
|
+
report.monotone_cols = [
|
|
211
|
+
c for c, rate in mono.items()
|
|
212
|
+
if rate <= _MONOTONE_TOL and _mean_rate(null_mono, c) > _MONOTONE_TOL * 2
|
|
213
|
+
]
|
|
214
|
+
|
|
215
|
+
report.invariance_violation = float(np.mean(list(inv.values()))) if inv else np.nan
|
|
216
|
+
report.monotonicity_violation = float(np.mean(list(mono.values()))) if mono else np.nan
|
|
217
|
+
report.null_invariance_violation = (
|
|
218
|
+
float(np.mean([v for d in null_inv for v in d.values()])) if null_inv else np.nan
|
|
219
|
+
)
|
|
220
|
+
report.null_monotonicity_violation = (
|
|
221
|
+
float(np.mean([v for d in null_mono for v in d.values()])) if null_mono else np.nan
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
report.n_usable_cols = len(cols)
|
|
225
|
+
report.evidence = float(len(report.invariant_cols) + len(report.monotone_cols))
|
|
226
|
+
report.evidence_frac = report.evidence / max(len(cols), 1)
|
|
227
|
+
|
|
228
|
+
# Real entities have something that persists. A key holding nothing still,
|
|
229
|
+
# with an invariance rate matching the null, is not naming entities at all.
|
|
230
|
+
# Counters cannot rescue it: ranking rows by a column that grows over time
|
|
231
|
+
# inherits that column's monotonicity from the sort order.
|
|
232
|
+
gap = report.null_invariance_violation - report.invariance_violation
|
|
233
|
+
holds_nothing_still = not report.invariant_cols and (
|
|
234
|
+
not np.isfinite(gap) or gap < _NULL_GAP_TOL
|
|
235
|
+
)
|
|
236
|
+
|
|
237
|
+
if duplicate_rate > _DUPLICATE_TOL:
|
|
238
|
+
report.verdict = f"invalid - key repeats within a period ({duplicate_rate:.1%})"
|
|
239
|
+
elif holds_nothing_still:
|
|
240
|
+
report.verdict = (
|
|
241
|
+
"NOT SUPPORTED - nothing stays constant within an entity "
|
|
242
|
+
"(invariance matches shuffled labels)"
|
|
243
|
+
)
|
|
244
|
+
elif report.evidence_frac >= _SUPPORTED:
|
|
245
|
+
report.verdict = "supported by the data"
|
|
246
|
+
elif report.evidence_frac >= _WEAK:
|
|
247
|
+
report.verdict = "weak - inspect manually"
|
|
248
|
+
else:
|
|
249
|
+
report.verdict = "NOT SUPPORTED - within-entity quantities are unsafe"
|
|
250
|
+
return report
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def discover_keys(
|
|
254
|
+
df: pd.DataFrame,
|
|
255
|
+
time_col: str,
|
|
256
|
+
*,
|
|
257
|
+
max_columns: int = 2,
|
|
258
|
+
top_k: int = 5,
|
|
259
|
+
candidate_columns: Sequence[str] | None = None,
|
|
260
|
+
n_shuffles: int = 2,
|
|
261
|
+
random_state: int = 0,
|
|
262
|
+
) -> list[KeyReport]:
|
|
263
|
+
"""Search column combinations for one that behaves like an entity key.
|
|
264
|
+
|
|
265
|
+
Ranks by explanatory power discounted by coverage, so a key that fragments
|
|
266
|
+
the panel into slivers cannot win on cleanliness alone.
|
|
267
|
+
"""
|
|
268
|
+
n_periods = df[time_col].nunique()
|
|
269
|
+
if n_periods < 2:
|
|
270
|
+
raise ValueError(f"{time_col!r} has {n_periods} period(s); need at least 2")
|
|
271
|
+
|
|
272
|
+
pool = list(candidate_columns) if candidate_columns else [
|
|
273
|
+
c for c in df.columns if c != time_col
|
|
274
|
+
]
|
|
275
|
+
# No cardinality filter on individual columns: real keys often pair a coarse
|
|
276
|
+
# column with a fine one, and dropping the coarse half loses the key. Only
|
|
277
|
+
# per-row-unique columns go, since they make every row its own entity.
|
|
278
|
+
pool = [c for c in pool if df[c].nunique(dropna=False) < len(df)]
|
|
279
|
+
|
|
280
|
+
def shape_ok(combo: tuple[str, ...]) -> bool:
|
|
281
|
+
sub = df.dropna(subset=list(combo))
|
|
282
|
+
if len(sub) < _MIN_ENTITIES * _MIN_PERIODS_PER_ENTITY:
|
|
283
|
+
return False
|
|
284
|
+
ent = entity_key(sub, combo)
|
|
285
|
+
per_period = sub.groupby([ent, sub[time_col]], sort=False).size()
|
|
286
|
+
if not len(per_period) or float((per_period > 1).mean()) > _DUPLICATE_TOL:
|
|
287
|
+
return False
|
|
288
|
+
counts = ent.value_counts()
|
|
289
|
+
return int((counts >= _MIN_PERIODS_PER_ENTITY).sum()) >= _MIN_ENTITIES
|
|
290
|
+
|
|
291
|
+
reports: list[KeyReport] = []
|
|
292
|
+
for size in range(1, max_columns + 1):
|
|
293
|
+
for combo in combinations(pool, size):
|
|
294
|
+
if any(set(r.key) < set(combo) and r.evidence_frac >= _SUPPORTED
|
|
295
|
+
for r in reports):
|
|
296
|
+
continue
|
|
297
|
+
# Screening is much cheaper than scoring, so check shape first.
|
|
298
|
+
if not shape_ok(combo):
|
|
299
|
+
continue
|
|
300
|
+
try:
|
|
301
|
+
rep = validate_key(df, combo, time_col, n_shuffles=n_shuffles,
|
|
302
|
+
random_state=random_state)
|
|
303
|
+
except Exception:
|
|
304
|
+
continue
|
|
305
|
+
reports.append(rep)
|
|
306
|
+
|
|
307
|
+
# Tie-break toward the finer partition: two keys can score alike while one
|
|
308
|
+
# quietly merges entities that share a value, and merging shrinks the count.
|
|
309
|
+
reports.sort(key=lambda r: (
|
|
310
|
+
-round(r.evidence_frac * np.sqrt(r.coverage), 6),
|
|
311
|
+
len(r.key),
|
|
312
|
+
-r.n_entities,
|
|
313
|
+
))
|
|
314
|
+
return reports[:top_k]
|
paneldx/py.typed
ADDED
|
File without changes
|