missinglens 0.1.0__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.
- missinglens/__init__.py +6 -0
- missinglens/analyzer.py +105 -0
- missinglens/apply.py +99 -0
- missinglens/cli.py +32 -0
- missinglens/config.py +44 -0
- missinglens/patterns.py +379 -0
- missinglens/recommender.py +273 -0
- missinglens/report.py +230 -0
- missinglens-0.1.0.dist-info/METADATA +98 -0
- missinglens-0.1.0.dist-info/RECORD +14 -0
- missinglens-0.1.0.dist-info/WHEEL +5 -0
- missinglens-0.1.0.dist-info/entry_points.txt +2 -0
- missinglens-0.1.0.dist-info/licenses/LICENSE +21 -0
- missinglens-0.1.0.dist-info/top_level.txt +1 -0
missinglens/__init__.py
ADDED
missinglens/analyzer.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""Column-level missingness and dtype analysis."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
import pandas as pd
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True)
|
|
12
|
+
class ColumnInfo:
|
|
13
|
+
"""Summary metadata for a single DataFrame column."""
|
|
14
|
+
|
|
15
|
+
name: str
|
|
16
|
+
dtype_class: str # numeric | categorical | boolean | datetime | text/id
|
|
17
|
+
missing_count: int
|
|
18
|
+
total_count: int
|
|
19
|
+
missing_pct: float
|
|
20
|
+
is_constant: bool
|
|
21
|
+
is_symmetric: bool
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class AnalysisResult:
|
|
26
|
+
"""Result of analyzing all columns in a DataFrame."""
|
|
27
|
+
|
|
28
|
+
columns: dict[str, ColumnInfo]
|
|
29
|
+
indicator_matrix: pd.DataFrame
|
|
30
|
+
time_col: str | None = None
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _classify_dtype(series: pd.Series, name: str) -> str:
|
|
34
|
+
"""Classify a pandas Series into one of the five missinglens dtype classes."""
|
|
35
|
+
if pd.api.types.is_bool_dtype(series):
|
|
36
|
+
return "boolean"
|
|
37
|
+
if pd.api.types.is_datetime64_any_dtype(series):
|
|
38
|
+
return "datetime"
|
|
39
|
+
if pd.api.types.is_numeric_dtype(series):
|
|
40
|
+
return "numeric"
|
|
41
|
+
if isinstance(series.dtype, pd.CategoricalDtype):
|
|
42
|
+
return "categorical"
|
|
43
|
+
|
|
44
|
+
non_null = series.dropna()
|
|
45
|
+
if len(non_null) == 0:
|
|
46
|
+
return "text/id" if "id" in name.lower() else "categorical"
|
|
47
|
+
|
|
48
|
+
# Check if object column is actually boolean
|
|
49
|
+
unique_vals = set(non_null.unique())
|
|
50
|
+
if unique_vals.issubset({True, False, "True", "False", "true", "false"}):
|
|
51
|
+
return "boolean"
|
|
52
|
+
|
|
53
|
+
n_unique = non_null.nunique()
|
|
54
|
+
avg_len = non_null.astype(str).str.len().mean()
|
|
55
|
+
lower_name = name.lower()
|
|
56
|
+
if "id" in lower_name or (n_unique / max(len(non_null), 1) > 0.8 and len(non_null) > 10):
|
|
57
|
+
return "text/id"
|
|
58
|
+
if avg_len > 30:
|
|
59
|
+
return "text/id"
|
|
60
|
+
return "categorical"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _check_symmetry(series: pd.Series, dtype_class: str) -> bool:
|
|
64
|
+
"""Return True if a numeric series is roughly symmetric (|skew| <= 0.5)."""
|
|
65
|
+
if dtype_class != "numeric":
|
|
66
|
+
return False
|
|
67
|
+
non_null = series.dropna()
|
|
68
|
+
if len(non_null) < 8 or non_null.nunique() <= 1:
|
|
69
|
+
return True
|
|
70
|
+
skew = float(non_null.skew())
|
|
71
|
+
return bool(np.isfinite(skew) and abs(skew) <= 0.5)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def analyze_columns(df: pd.DataFrame, time_col: str | None = None) -> AnalysisResult:
|
|
75
|
+
"""Analyze missingness, dtype class, and build the missing-indicator matrix."""
|
|
76
|
+
if df.empty or len(df.columns) == 0:
|
|
77
|
+
return AnalysisResult(
|
|
78
|
+
columns={},
|
|
79
|
+
indicator_matrix=pd.DataFrame(index=df.index),
|
|
80
|
+
time_col=time_col,
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
indicator_matrix = df.isna().astype(np.int8)
|
|
84
|
+
total_count = len(df)
|
|
85
|
+
columns: dict[str, ColumnInfo] = {}
|
|
86
|
+
|
|
87
|
+
for col in df.columns:
|
|
88
|
+
s = df[col]
|
|
89
|
+
dtype_class = _classify_dtype(s, str(col))
|
|
90
|
+
missing_count = int(indicator_matrix[col].sum())
|
|
91
|
+
missing_pct = (missing_count / total_count * 100.0) if total_count > 0 else 0.0
|
|
92
|
+
non_null = s.dropna()
|
|
93
|
+
is_constant = non_null.nunique() <= 1
|
|
94
|
+
is_symmetric = _check_symmetry(s, dtype_class)
|
|
95
|
+
columns[str(col)] = ColumnInfo(
|
|
96
|
+
name=str(col),
|
|
97
|
+
dtype_class=dtype_class,
|
|
98
|
+
missing_count=missing_count,
|
|
99
|
+
total_count=total_count,
|
|
100
|
+
missing_pct=missing_pct,
|
|
101
|
+
is_constant=is_constant,
|
|
102
|
+
is_symmetric=is_symmetric,
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
return AnalysisResult(columns=columns, indicator_matrix=indicator_matrix, time_col=time_col)
|
missinglens/apply.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""Apply missingness recommendations without mutating the input DataFrame."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import pandas as pd
|
|
6
|
+
from sklearn.experimental import enable_iterative_imputer # noqa: F401
|
|
7
|
+
from sklearn.impute import IterativeImputer, KNNImputer, SimpleImputer
|
|
8
|
+
|
|
9
|
+
from missinglens.config import DEFAULT_CONFIG, ThresholdConfig
|
|
10
|
+
from missinglens.recommender import Recommendation
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def apply_recommendations(
|
|
14
|
+
df: pd.DataFrame,
|
|
15
|
+
recommendations: dict[str, Recommendation],
|
|
16
|
+
time_col: str | None = None,
|
|
17
|
+
config: ThresholdConfig = DEFAULT_CONFIG,
|
|
18
|
+
) -> tuple[pd.DataFrame, list[str]]:
|
|
19
|
+
"""Return (df_clean, log) after applying recommendations. Never mutates `df`."""
|
|
20
|
+
out = df.copy(deep=True)
|
|
21
|
+
log: list[str] = []
|
|
22
|
+
|
|
23
|
+
numeric_cols = [c for c in out.columns if pd.api.types.is_numeric_dtype(out[c])]
|
|
24
|
+
|
|
25
|
+
for col, rec in recommendations.items():
|
|
26
|
+
if col not in out.columns or rec.method in ("none", "do_not_impute"):
|
|
27
|
+
continue
|
|
28
|
+
|
|
29
|
+
if rec.method == "drop_column":
|
|
30
|
+
out = out.drop(columns=[col])
|
|
31
|
+
log.append(f"Dropped '{col}' ({rec.reason})")
|
|
32
|
+
continue
|
|
33
|
+
|
|
34
|
+
if rec.method == "mean":
|
|
35
|
+
imp = SimpleImputer(strategy="mean")
|
|
36
|
+
out[[col]] = imp.fit_transform(out[[col]])
|
|
37
|
+
log.append(f"Imputed '{col}' with mean.")
|
|
38
|
+
elif rec.method == "median":
|
|
39
|
+
imp = SimpleImputer(strategy="median")
|
|
40
|
+
out[[col]] = imp.fit_transform(out[[col]])
|
|
41
|
+
log.append(f"Imputed '{col}' with median.")
|
|
42
|
+
elif rec.method == "mode":
|
|
43
|
+
imp = SimpleImputer(strategy="most_frequent")
|
|
44
|
+
out[[col]] = imp.fit_transform(out[[col]])
|
|
45
|
+
log.append(f"Imputed '{col}' with mode.")
|
|
46
|
+
elif rec.method in ("unknown_category", "recode_not_applicable"):
|
|
47
|
+
fill_val = "None/Not applicable" if rec.method == "recode_not_applicable" else "Unknown"
|
|
48
|
+
if isinstance(out[col].dtype, pd.CategoricalDtype):
|
|
49
|
+
if fill_val not in out[col].cat.categories:
|
|
50
|
+
out[col] = out[col].cat.add_categories([fill_val])
|
|
51
|
+
out[col] = out[col].fillna(fill_val)
|
|
52
|
+
log.append(f"Filled '{col}' missing values with '{fill_val}'.")
|
|
53
|
+
elif rec.method in ("interpolate", "interpolate_short_flag_long"):
|
|
54
|
+
limit = config.short_gap_limit if rec.method == "interpolate_short_flag_long" else None
|
|
55
|
+
if rec.method == "interpolate_short_flag_long":
|
|
56
|
+
out[f"{col}_was_missing"] = out[col].isna().astype(int)
|
|
57
|
+
out[col] = out[col].interpolate(method="linear", limit=limit, limit_direction="both")
|
|
58
|
+
if out[col].isna().any():
|
|
59
|
+
imp = SimpleImputer(strategy="median")
|
|
60
|
+
out[[col]] = imp.fit_transform(out[[col]])
|
|
61
|
+
log.append(f"Interpolated '{col}' ({rec.method}).")
|
|
62
|
+
elif rec.method == "knn":
|
|
63
|
+
use_cols = [c for c in ([col] + rec.drivers) if c in numeric_cols]
|
|
64
|
+
if len(use_cols) < 2:
|
|
65
|
+
use_cols = numeric_cols
|
|
66
|
+
if len(use_cols) >= 2:
|
|
67
|
+
imp = KNNImputer(n_neighbors=5)
|
|
68
|
+
imputed = imp.fit_transform(out[use_cols])
|
|
69
|
+
out[col] = imputed[:, use_cols.index(col)]
|
|
70
|
+
log.append(f"Imputed '{col}' with KNNImputer using {use_cols}.")
|
|
71
|
+
else:
|
|
72
|
+
imp = SimpleImputer(strategy="median")
|
|
73
|
+
out[[col]] = imp.fit_transform(out[[col]])
|
|
74
|
+
log.append(f"Imputed '{col}' with median fallback.")
|
|
75
|
+
elif rec.method == "iterative":
|
|
76
|
+
use_cols = numeric_cols if len(numeric_cols) >= 2 else [col]
|
|
77
|
+
if len(use_cols) >= 2:
|
|
78
|
+
imp = IterativeImputer(random_state=42, max_iter=10)
|
|
79
|
+
imputed = imp.fit_transform(out[use_cols])
|
|
80
|
+
out[col] = imputed[:, use_cols.index(col)]
|
|
81
|
+
log.append(f"Imputed '{col}' with IterativeImputer.")
|
|
82
|
+
else:
|
|
83
|
+
imp = SimpleImputer(strategy="median")
|
|
84
|
+
out[[col]] = imp.fit_transform(out[[col]])
|
|
85
|
+
log.append(f"Imputed '{col}' with median fallback.")
|
|
86
|
+
elif rec.method == "flag_only":
|
|
87
|
+
out[f"{col}_was_missing"] = out[col].isna().astype(int)
|
|
88
|
+
log.append(f"Added '{col}_was_missing' flag without imputing '{col}'.")
|
|
89
|
+
elif rec.method == "flag_and_impute":
|
|
90
|
+
out[f"{col}_was_missing"] = out[col].isna().astype(int)
|
|
91
|
+
if pd.api.types.is_numeric_dtype(out[col]):
|
|
92
|
+
imp = SimpleImputer(strategy="median")
|
|
93
|
+
out[[col]] = imp.fit_transform(out[[col]])
|
|
94
|
+
else:
|
|
95
|
+
imp = SimpleImputer(strategy="most_frequent")
|
|
96
|
+
out[[col]] = imp.fit_transform(out[[col]])
|
|
97
|
+
log.append(f"Added '{col}_was_missing' flag and imputed '{col}'.")
|
|
98
|
+
|
|
99
|
+
return out, log
|
missinglens/cli.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Typer CLI for missinglens."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Optional
|
|
7
|
+
|
|
8
|
+
import pandas as pd
|
|
9
|
+
import typer
|
|
10
|
+
|
|
11
|
+
from missinglens.report import analyze
|
|
12
|
+
|
|
13
|
+
app = typer.Typer(help="Analyze missing data per column and generate recommendations.")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@app.command()
|
|
17
|
+
def main(
|
|
18
|
+
csv_path: Path = typer.Argument(..., exists=True, help="Path to input CSV file."),
|
|
19
|
+
time_col: Optional[str] = typer.Option(None, "--time-col", help="Optional timestamp column."),
|
|
20
|
+
out: Optional[Path] = typer.Option(None, "--out", help="Optional output HTML report path."),
|
|
21
|
+
) -> None:
|
|
22
|
+
"""Analyze a CSV file for missing data patterns and recommendations."""
|
|
23
|
+
df = pd.read_csv(csv_path)
|
|
24
|
+
report = analyze(df, time_col=time_col)
|
|
25
|
+
typer.echo(report.summary().to_string(index=False))
|
|
26
|
+
if out is not None:
|
|
27
|
+
report.to_html(out)
|
|
28
|
+
typer.echo(f"\nSaved HTML report to {out}")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
if __name__ == "__main__":
|
|
32
|
+
app()
|
missinglens/config.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Configuration and calibrated thresholds for missinglens."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@dataclass(frozen=True)
|
|
7
|
+
class ThresholdConfig:
|
|
8
|
+
"""Thresholds used by pattern detectors and recommender."""
|
|
9
|
+
|
|
10
|
+
alpha: float = 0.01
|
|
11
|
+
min_samples: int = 20
|
|
12
|
+
min_missing_for_test: int = 15
|
|
13
|
+
trend_rho_threshold: float = 0.25
|
|
14
|
+
mar_auc_threshold: float = 0.65
|
|
15
|
+
comissing_corr_threshold: float = 0.40
|
|
16
|
+
block_min_length: int = 5
|
|
17
|
+
drop_threshold_pct: float = 60.0
|
|
18
|
+
short_gap_limit: int = 5
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
DEFAULT_CONFIG = ThresholdConfig()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
# End-to-end min(TREND, SEASONAL) recall lookup: (n_rows, missing_count, power)
|
|
25
|
+
POWER_TABLE: tuple[tuple[int, int, float], ...] = (
|
|
26
|
+
(10000, 1000, 1.00),
|
|
27
|
+
(10000, 200, 0.60),
|
|
28
|
+
(1000, 100, 0.88),
|
|
29
|
+
(1000, 50, 0.36),
|
|
30
|
+
(1000, 20, 0.06),
|
|
31
|
+
(200, 40, 0.88),
|
|
32
|
+
(200, 20, 0.32),
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def estimate_detection_power(n_rows: int, missing_count: int) -> float:
|
|
37
|
+
"""Estimate end-to-end detection power for TREND/SEASONAL from (n_rows, missing_count)."""
|
|
38
|
+
if n_rows < 100 or missing_count < 15:
|
|
39
|
+
return 0.10
|
|
40
|
+
if n_rows >= 10000:
|
|
41
|
+
return 1.00 if missing_count >= 500 else 0.60
|
|
42
|
+
if n_rows >= 1000:
|
|
43
|
+
return 0.88 if missing_count >= 90 else 0.36
|
|
44
|
+
return 0.88 if missing_count >= 40 else 0.32
|
missinglens/patterns.py
ADDED
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
"""Pure-function missingness pattern detectors."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
import pandas as pd
|
|
10
|
+
from scipy import stats
|
|
11
|
+
from sklearn.model_selection import StratifiedKFold, cross_val_score
|
|
12
|
+
from sklearn.preprocessing import OrdinalEncoder
|
|
13
|
+
from sklearn.tree import DecisionTreeClassifier
|
|
14
|
+
|
|
15
|
+
from missinglens.config import DEFAULT_CONFIG, ThresholdConfig
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class PatternResult:
|
|
20
|
+
"""Result of a single missingness pattern detector."""
|
|
21
|
+
|
|
22
|
+
detected: bool
|
|
23
|
+
statistic: float
|
|
24
|
+
p_value: float
|
|
25
|
+
evidence: dict[str, Any] = field(default_factory=dict)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _benjamini_hochberg(p_values: list[float]) -> list[float]:
|
|
29
|
+
"""Return Benjamini-Hochberg FDR-adjusted p-values."""
|
|
30
|
+
m = len(p_values)
|
|
31
|
+
if m == 0:
|
|
32
|
+
return []
|
|
33
|
+
order = np.argsort(p_values)
|
|
34
|
+
ranked = np.asarray(p_values, dtype=float)[order]
|
|
35
|
+
adj = np.empty(m, dtype=float)
|
|
36
|
+
prev = 1.0
|
|
37
|
+
for i in range(m - 1, -1, -1):
|
|
38
|
+
val = ranked[i] * m / (i + 1)
|
|
39
|
+
prev = min(prev, val)
|
|
40
|
+
adj[i] = min(prev, 1.0)
|
|
41
|
+
out = np.empty(m, dtype=float)
|
|
42
|
+
out[order] = adj
|
|
43
|
+
return out.tolist()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _has_enough_data(missing_mask: pd.Series, config: ThresholdConfig) -> bool:
|
|
47
|
+
n = len(missing_mask)
|
|
48
|
+
n_miss = int(missing_mask.sum())
|
|
49
|
+
n_obs = n - n_miss
|
|
50
|
+
return (
|
|
51
|
+
n >= config.min_samples
|
|
52
|
+
and n_miss >= config.min_missing_for_test
|
|
53
|
+
and n_obs >= config.min_missing_for_test
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def detect_trend(
|
|
58
|
+
missing_mask: pd.Series,
|
|
59
|
+
time_series: pd.Series | None = None,
|
|
60
|
+
config: ThresholdConfig = DEFAULT_CONFIG,
|
|
61
|
+
) -> PatternResult:
|
|
62
|
+
"""Detect monotonic trend in missing rate over time or row order."""
|
|
63
|
+
if not _has_enough_data(missing_mask, config):
|
|
64
|
+
return PatternResult(False, 0.0, 1.0, {"reason": "insufficient_samples"})
|
|
65
|
+
|
|
66
|
+
mask = missing_mask.astype(float).reset_index(drop=True)
|
|
67
|
+
if time_series is not None:
|
|
68
|
+
ts = pd.to_datetime(time_series, errors="coerce")
|
|
69
|
+
valid = ts.notna()
|
|
70
|
+
if valid.sum() >= config.min_samples:
|
|
71
|
+
order = ts[valid].argsort(kind="mergesort")
|
|
72
|
+
mask = mask.iloc[valid.to_numpy().nonzero()[0][order]].reset_index(drop=True)
|
|
73
|
+
|
|
74
|
+
arr = mask.to_numpy(dtype=float)
|
|
75
|
+
if np.std(arr) == 0:
|
|
76
|
+
return PatternResult(False, 0.0, 1.0, {"method": "point_biserial"})
|
|
77
|
+
|
|
78
|
+
idx = np.arange(len(arr), dtype=float)
|
|
79
|
+
r_val, p_val = stats.pearsonr(idx, arr)
|
|
80
|
+
r_val = float(r_val) if np.isfinite(r_val) else 0.0
|
|
81
|
+
p_val = float(p_val) if np.isfinite(p_val) else 1.0
|
|
82
|
+
detected = p_val < config.alpha
|
|
83
|
+
return PatternResult(
|
|
84
|
+
detected=detected,
|
|
85
|
+
statistic=r_val,
|
|
86
|
+
p_value=p_val,
|
|
87
|
+
evidence={
|
|
88
|
+
"method": "point_biserial",
|
|
89
|
+
"direction": "increasing" if r_val > 0 else "decreasing",
|
|
90
|
+
},
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def detect_seasonal(
|
|
95
|
+
missing_mask: pd.Series,
|
|
96
|
+
time_series: pd.Series | None = None,
|
|
97
|
+
config: ThresholdConfig = DEFAULT_CONFIG,
|
|
98
|
+
) -> PatternResult:
|
|
99
|
+
"""Detect seasonal missingness by hour, weekday, or month (requires time_col)."""
|
|
100
|
+
if time_series is None or not _has_enough_data(missing_mask, config):
|
|
101
|
+
return PatternResult(False, 0.0, 1.0, {"reason": "no_time_col_or_insufficient_samples"})
|
|
102
|
+
|
|
103
|
+
ts = pd.to_datetime(time_series, errors="coerce")
|
|
104
|
+
valid = ts.notna()
|
|
105
|
+
if valid.sum() < config.min_samples:
|
|
106
|
+
return PatternResult(False, 0.0, 1.0, {"reason": "invalid_timestamps"})
|
|
107
|
+
|
|
108
|
+
ts_v = ts[valid]
|
|
109
|
+
miss_v = missing_mask[valid].astype(int)
|
|
110
|
+
|
|
111
|
+
candidates = {
|
|
112
|
+
"hour": ts_v.dt.hour,
|
|
113
|
+
"weekday": ts_v.dt.dayofweek,
|
|
114
|
+
"month": ts_v.dt.month,
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
best_unit = None
|
|
118
|
+
best_stat = 0.0
|
|
119
|
+
best_p = 1.0
|
|
120
|
+
|
|
121
|
+
for unit, groups in candidates.items():
|
|
122
|
+
if groups.nunique() < 2:
|
|
123
|
+
continue
|
|
124
|
+
table = pd.crosstab(groups, miss_v)
|
|
125
|
+
if table.shape[1] < 2 or table.shape[0] < 2:
|
|
126
|
+
continue
|
|
127
|
+
chi2, p_val, _, _ = stats.chi2_contingency(table)
|
|
128
|
+
if np.isfinite(p_val) and p_val < best_p:
|
|
129
|
+
best_p = float(p_val)
|
|
130
|
+
best_stat = float(chi2)
|
|
131
|
+
best_unit = unit
|
|
132
|
+
|
|
133
|
+
detected = best_unit is not None and best_p < config.alpha
|
|
134
|
+
return PatternResult(
|
|
135
|
+
detected=detected,
|
|
136
|
+
statistic=best_stat,
|
|
137
|
+
p_value=best_p,
|
|
138
|
+
evidence={"unit": best_unit},
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def detect_block(
|
|
143
|
+
missing_mask: pd.Series,
|
|
144
|
+
config: ThresholdConfig = DEFAULT_CONFIG,
|
|
145
|
+
) -> PatternResult:
|
|
146
|
+
"""Detect contiguous blocks (runs) of missing values."""
|
|
147
|
+
arr = missing_mask.to_numpy(dtype=bool)
|
|
148
|
+
if len(arr) == 0 or not arr.any():
|
|
149
|
+
return PatternResult(False, 0.0, 1.0, {"longest_gap": 0, "block_count": 0, "blocks": []})
|
|
150
|
+
|
|
151
|
+
padded = np.concatenate(([False], arr, [False]))
|
|
152
|
+
diffs = np.diff(padded.astype(int))
|
|
153
|
+
starts = np.where(diffs == 1)[0]
|
|
154
|
+
ends = np.where(diffs == -1)[0] - 1
|
|
155
|
+
lengths = ends - starts + 1
|
|
156
|
+
|
|
157
|
+
long_idx = np.where(lengths >= config.block_min_length)[0]
|
|
158
|
+
blocks = [(int(starts[i]), int(ends[i])) for i in long_idx]
|
|
159
|
+
longest_gap = int(lengths.max()) if len(lengths) > 0 else 0
|
|
160
|
+
block_count = len(blocks)
|
|
161
|
+
|
|
162
|
+
# Expected longest random run under Bernoulli(p): ~ log(n) / -log(p)
|
|
163
|
+
p = float(arr.mean())
|
|
164
|
+
n = len(arr)
|
|
165
|
+
if 0.0 < p < 1.0:
|
|
166
|
+
expected_random_run = np.log(max(n, 2)) / max(-np.log(p), 1e-3)
|
|
167
|
+
else:
|
|
168
|
+
expected_random_run = float(n)
|
|
169
|
+
min_required = max(config.block_min_length, int(np.ceil(expected_random_run * 1.8)) + 2)
|
|
170
|
+
detected = longest_gap >= min_required
|
|
171
|
+
|
|
172
|
+
return PatternResult(
|
|
173
|
+
detected=detected,
|
|
174
|
+
statistic=float(longest_gap),
|
|
175
|
+
p_value=0.0 if detected else 1.0,
|
|
176
|
+
evidence={"longest_gap": longest_gap, "block_count": block_count, "blocks": blocks[:10]},
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def detect_comissingness(
|
|
181
|
+
col: str,
|
|
182
|
+
indicator_matrix: pd.DataFrame,
|
|
183
|
+
config: ThresholdConfig = DEFAULT_CONFIG,
|
|
184
|
+
) -> PatternResult:
|
|
185
|
+
"""Detect correlation between missingness indicator of `col` and other columns."""
|
|
186
|
+
if col not in indicator_matrix.columns or len(indicator_matrix) < config.min_samples:
|
|
187
|
+
return PatternResult(False, 0.0, 1.0, {"partners": []})
|
|
188
|
+
|
|
189
|
+
target = indicator_matrix[col].to_numpy(dtype=float)
|
|
190
|
+
if np.std(target) == 0:
|
|
191
|
+
return PatternResult(False, 0.0, 1.0, {"partners": []})
|
|
192
|
+
|
|
193
|
+
partners: list[str] = []
|
|
194
|
+
max_corr = 0.0
|
|
195
|
+
min_p = 1.0
|
|
196
|
+
|
|
197
|
+
for other in indicator_matrix.columns:
|
|
198
|
+
if other == col:
|
|
199
|
+
continue
|
|
200
|
+
other_arr = indicator_matrix[other].to_numpy(dtype=float)
|
|
201
|
+
if np.std(other_arr) == 0:
|
|
202
|
+
continue
|
|
203
|
+
r, p_val = stats.pearsonr(target, other_arr)
|
|
204
|
+
if np.isfinite(r) and np.isfinite(p_val):
|
|
205
|
+
if abs(r) >= config.comissing_corr_threshold and p_val < config.alpha:
|
|
206
|
+
partners.append(str(other))
|
|
207
|
+
if abs(r) > max_corr:
|
|
208
|
+
max_corr = float(abs(r))
|
|
209
|
+
min_p = float(p_val)
|
|
210
|
+
|
|
211
|
+
return PatternResult(
|
|
212
|
+
detected=len(partners) > 0,
|
|
213
|
+
statistic=max_corr,
|
|
214
|
+
p_value=min_p,
|
|
215
|
+
evidence={"partners": partners, "exact_group": max_corr >= 0.97},
|
|
216
|
+
)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _compute_mar_cv_auc(
|
|
220
|
+
missing_mask: pd.Series,
|
|
221
|
+
df: pd.DataFrame,
|
|
222
|
+
col: str,
|
|
223
|
+
) -> float:
|
|
224
|
+
"""Fit a shallow decision tree on other columns to predict missingness of `col`."""
|
|
225
|
+
n_miss = int(missing_mask.sum())
|
|
226
|
+
n_obs = len(missing_mask) - n_miss
|
|
227
|
+
if min(n_miss, n_obs) < 10:
|
|
228
|
+
return 0.5
|
|
229
|
+
|
|
230
|
+
other_cols = [c for c in df.columns if c != col]
|
|
231
|
+
if not other_cols:
|
|
232
|
+
return 0.5
|
|
233
|
+
|
|
234
|
+
X_parts: list[pd.DataFrame] = []
|
|
235
|
+
num_cols = [c for c in other_cols if pd.api.types.is_numeric_dtype(df[c])]
|
|
236
|
+
if num_cols:
|
|
237
|
+
X_num = df[num_cols].copy()
|
|
238
|
+
X_num = X_num.fillna(X_num.median(numeric_only=True))
|
|
239
|
+
X_parts.append(X_num)
|
|
240
|
+
|
|
241
|
+
cat_cols = [
|
|
242
|
+
c
|
|
243
|
+
for c in other_cols
|
|
244
|
+
if c not in num_cols and not pd.api.types.is_datetime64_any_dtype(df[c])
|
|
245
|
+
]
|
|
246
|
+
if cat_cols:
|
|
247
|
+
X_cat = df[cat_cols].astype(str).fillna("__MISSING__")
|
|
248
|
+
enc = OrdinalEncoder(handle_unknown="use_encoded_value", unknown_value=-1)
|
|
249
|
+
X_cat_enc = pd.DataFrame(enc.fit_transform(X_cat), columns=cat_cols, index=df.index)
|
|
250
|
+
X_parts.append(X_cat_enc)
|
|
251
|
+
|
|
252
|
+
if not X_parts:
|
|
253
|
+
return 0.5
|
|
254
|
+
|
|
255
|
+
X = pd.concat(X_parts, axis=1)
|
|
256
|
+
y = missing_mask.astype(int).to_numpy()
|
|
257
|
+
n_splits = min(3, min(n_miss, n_obs))
|
|
258
|
+
if n_splits < 2:
|
|
259
|
+
return 0.5
|
|
260
|
+
|
|
261
|
+
cv = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)
|
|
262
|
+
clf = DecisionTreeClassifier(max_depth=3, min_samples_leaf=5, random_state=42)
|
|
263
|
+
try:
|
|
264
|
+
scores = cross_val_score(clf, X, y, cv=cv, scoring="roc_auc")
|
|
265
|
+
return float(np.nanmean(scores))
|
|
266
|
+
except Exception:
|
|
267
|
+
return 0.5
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def detect_mar(
|
|
271
|
+
col: str,
|
|
272
|
+
df: pd.DataFrame,
|
|
273
|
+
config: ThresholdConfig = DEFAULT_CONFIG,
|
|
274
|
+
) -> PatternResult:
|
|
275
|
+
"""Detect MAR by testing missingness of `col` against ALL other columns."""
|
|
276
|
+
if col not in df.columns:
|
|
277
|
+
return PatternResult(False, 0.0, 1.0, {"drivers": [], "cv_auc": 0.5})
|
|
278
|
+
|
|
279
|
+
if len(df) > 50_000:
|
|
280
|
+
df = df.sample(n=50_000, random_state=42)
|
|
281
|
+
|
|
282
|
+
missing_mask = df[col].isna()
|
|
283
|
+
if not _has_enough_data(missing_mask, config):
|
|
284
|
+
return PatternResult(False, 0.0, 1.0, {"drivers": [], "cv_auc": 0.5})
|
|
285
|
+
|
|
286
|
+
tested_cols: list[str] = []
|
|
287
|
+
raw_pvals: list[float] = []
|
|
288
|
+
|
|
289
|
+
for other in df.columns:
|
|
290
|
+
if other == col:
|
|
291
|
+
continue
|
|
292
|
+
s = df[other]
|
|
293
|
+
if pd.api.types.is_datetime64_any_dtype(s):
|
|
294
|
+
continue
|
|
295
|
+
valid = s.notna()
|
|
296
|
+
if valid.sum() < config.min_samples:
|
|
297
|
+
continue
|
|
298
|
+
|
|
299
|
+
s_v = s[valid]
|
|
300
|
+
m_v = missing_mask[valid]
|
|
301
|
+
if m_v.nunique() < 2:
|
|
302
|
+
continue
|
|
303
|
+
|
|
304
|
+
if pd.api.types.is_numeric_dtype(s_v) and not pd.api.types.is_bool_dtype(s_v):
|
|
305
|
+
g1 = s_v[m_v]
|
|
306
|
+
g0 = s_v[~m_v]
|
|
307
|
+
if len(g1) >= 3 and len(g0) >= 3 and (g1.nunique() > 1 or g0.nunique() > 1):
|
|
308
|
+
_, p_val = stats.mannwhitneyu(g1, g0, alternative="two-sided")
|
|
309
|
+
if np.isfinite(p_val):
|
|
310
|
+
tested_cols.append(str(other))
|
|
311
|
+
raw_pvals.append(float(p_val))
|
|
312
|
+
else:
|
|
313
|
+
if s_v.nunique() <= 50:
|
|
314
|
+
table = pd.crosstab(s_v.astype(str), m_v.astype(int))
|
|
315
|
+
if table.shape[0] >= 2 and table.shape[1] >= 2:
|
|
316
|
+
_, p_val, _, _ = stats.chi2_contingency(table)
|
|
317
|
+
if np.isfinite(p_val):
|
|
318
|
+
tested_cols.append(str(other))
|
|
319
|
+
raw_pvals.append(float(p_val))
|
|
320
|
+
|
|
321
|
+
adj_pvals = _benjamini_hochberg(raw_pvals)
|
|
322
|
+
drivers = [c for c, p in zip(tested_cols, adj_pvals) if p < config.alpha]
|
|
323
|
+
min_p = min(adj_pvals) if adj_pvals else 1.0
|
|
324
|
+
cv_auc = _compute_mar_cv_auc(missing_mask, df, col)
|
|
325
|
+
|
|
326
|
+
detected = len(drivers) > 0 or cv_auc >= config.mar_auc_threshold
|
|
327
|
+
return PatternResult(
|
|
328
|
+
detected=detected,
|
|
329
|
+
statistic=cv_auc,
|
|
330
|
+
p_value=float(min_p),
|
|
331
|
+
evidence={"drivers": drivers, "cv_auc": round(cv_auc, 4)},
|
|
332
|
+
)
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def detect_all_patterns(
|
|
336
|
+
col: str,
|
|
337
|
+
df: pd.DataFrame,
|
|
338
|
+
indicator_matrix: pd.DataFrame,
|
|
339
|
+
time_col: str | None = None,
|
|
340
|
+
config: ThresholdConfig = DEFAULT_CONFIG,
|
|
341
|
+
) -> tuple[str, dict[str, PatternResult]]:
|
|
342
|
+
"""Run all pattern detectors for `col` and return (primary_pattern, results_dict)."""
|
|
343
|
+
missing_mask = df[col].isna()
|
|
344
|
+
time_series = df[time_col] if time_col and time_col in df.columns else None
|
|
345
|
+
|
|
346
|
+
trend = detect_trend(missing_mask, time_series=time_series, config=config)
|
|
347
|
+
seasonal = detect_seasonal(missing_mask, time_series=time_series, config=config)
|
|
348
|
+
block = detect_block(missing_mask, config=config)
|
|
349
|
+
comissing = detect_comissingness(col, indicator_matrix, config=config)
|
|
350
|
+
mar = detect_mar(col, df, config=config)
|
|
351
|
+
|
|
352
|
+
results = {
|
|
353
|
+
"TREND": trend,
|
|
354
|
+
"SEASONAL": seasonal,
|
|
355
|
+
"BLOCK": block,
|
|
356
|
+
"CO-MISSING": comissing,
|
|
357
|
+
"MAR": mar,
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
# Apply BH-FDR across the p-value-based detectors (TREND, SEASONAL, CO-MISSING, MAR)
|
|
361
|
+
pval_names = ["TREND", "SEASONAL", "CO-MISSING", "MAR"]
|
|
362
|
+
raw_pvals = [results[name].p_value for name in pval_names]
|
|
363
|
+
adj_pvals = _benjamini_hochberg(raw_pvals)
|
|
364
|
+
for name, adj_p in zip(pval_names, adj_pvals):
|
|
365
|
+
res = results[name]
|
|
366
|
+
if res.detected and adj_p >= config.alpha:
|
|
367
|
+
# Keep MAR if CV-AUC is strongly above threshold on sufficient sample size
|
|
368
|
+
if name == "MAR" and len(df) >= 300 and res.statistic >= config.mar_auc_threshold:
|
|
369
|
+
continue
|
|
370
|
+
results[name] = PatternResult(False, res.statistic, float(adj_p), res.evidence)
|
|
371
|
+
if results["TREND"].detected and abs(results["TREND"].statistic) >= 0.70:
|
|
372
|
+
return "TREND", results
|
|
373
|
+
|
|
374
|
+
# Priority order when multiple patterns are detected (no fixed |r| gate on TREND)
|
|
375
|
+
for name in ("BLOCK", "TREND", "SEASONAL", "CO-MISSING", "MAR"):
|
|
376
|
+
if results[name].detected:
|
|
377
|
+
return name, results
|
|
378
|
+
|
|
379
|
+
return "MCAR", results
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
"""Data-driven recommendation rules for missing data."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Callable
|
|
7
|
+
|
|
8
|
+
from missinglens.config import DEFAULT_CONFIG, ThresholdConfig, estimate_detection_power
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True)
|
|
12
|
+
class Recommendation:
|
|
13
|
+
"""Actionable imputation or handling recommendation for one column."""
|
|
14
|
+
|
|
15
|
+
method: str
|
|
16
|
+
confidence: str # low | medium | high
|
|
17
|
+
reason: str
|
|
18
|
+
drivers: list[str] = field(default_factory=list)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True)
|
|
22
|
+
class Rule:
|
|
23
|
+
"""Declarative rule mapping column characteristics to a recommendation."""
|
|
24
|
+
|
|
25
|
+
name: str
|
|
26
|
+
predicate: Callable[[dict], bool]
|
|
27
|
+
method: str
|
|
28
|
+
confidence: str
|
|
29
|
+
reason_template: str
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _format_drivers(drivers: list[str]) -> str:
|
|
33
|
+
return ", ".join(drivers[:3]) if drivers else "other observed columns"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
RULES: tuple[Rule, ...] = (
|
|
37
|
+
Rule(
|
|
38
|
+
name="no_missing",
|
|
39
|
+
predicate=lambda ctx: ctx["missing_pct"] == 0.0,
|
|
40
|
+
method="none",
|
|
41
|
+
confidence="high",
|
|
42
|
+
reason_template="Column has no missing values.",
|
|
43
|
+
),
|
|
44
|
+
Rule(
|
|
45
|
+
name="exact_comissing_categorical",
|
|
46
|
+
predicate=lambda ctx: (
|
|
47
|
+
ctx["dtype_class"] == "categorical"
|
|
48
|
+
and ctx["is_exact_comissing"]
|
|
49
|
+
and not (ctx["has_time_col"] and ctx["pattern"] == "BLOCK")
|
|
50
|
+
),
|
|
51
|
+
method="recode_not_applicable",
|
|
52
|
+
confidence="medium",
|
|
53
|
+
reason_template=(
|
|
54
|
+
"Categorical column is missing on the exact same rows as {partners_str}; "
|
|
55
|
+
"likely structural 'Not applicable'. Recode NA to 'None/Not applicable' "
|
|
56
|
+
"(domain knowledge needed to confirm)."
|
|
57
|
+
),
|
|
58
|
+
),
|
|
59
|
+
Rule(
|
|
60
|
+
name="exact_comissing_numeric",
|
|
61
|
+
predicate=lambda ctx: (
|
|
62
|
+
ctx["dtype_class"] == "numeric"
|
|
63
|
+
and ctx["is_exact_comissing"]
|
|
64
|
+
and not (ctx["has_time_col"] and ctx["pattern"] == "BLOCK")
|
|
65
|
+
),
|
|
66
|
+
method="flag_only",
|
|
67
|
+
confidence="medium",
|
|
68
|
+
reason_template=(
|
|
69
|
+
"Numeric column is missing on the exact same rows as {partners_str}; "
|
|
70
|
+
"the value probably does not exist. Flag only, do not impute "
|
|
71
|
+
"(domain knowledge needed to confirm)."
|
|
72
|
+
),
|
|
73
|
+
),
|
|
74
|
+
Rule(
|
|
75
|
+
name="structural_not_applicable",
|
|
76
|
+
predicate=lambda ctx: (
|
|
77
|
+
ctx["dtype_class"] == "categorical"
|
|
78
|
+
and ctx["missing_pct"] > ctx["drop_threshold_pct"]
|
|
79
|
+
and (ctx["pattern"] in ("MAR", "CO-MISSING") or len(ctx["drivers"]) > 0)
|
|
80
|
+
),
|
|
81
|
+
method="recode_not_applicable",
|
|
82
|
+
confidence="medium",
|
|
83
|
+
reason_template=(
|
|
84
|
+
"High missingness ({missing_pct:.1f}%) in categorical column explained by "
|
|
85
|
+
"{drivers_str} ({pattern}); likely structural 'Not applicable'. Recode NA to "
|
|
86
|
+
"'None/Not applicable' (domain knowledge needed to confirm)."
|
|
87
|
+
),
|
|
88
|
+
),
|
|
89
|
+
Rule(
|
|
90
|
+
name="drop_high_missing_categorical",
|
|
91
|
+
predicate=lambda ctx: (
|
|
92
|
+
ctx["dtype_class"] == "categorical"
|
|
93
|
+
and ctx["missing_pct"] > ctx["drop_threshold_pct"]
|
|
94
|
+
),
|
|
95
|
+
method="drop_column",
|
|
96
|
+
confidence="high",
|
|
97
|
+
reason_template=(
|
|
98
|
+
"More than {drop_threshold_pct:.0f}% ({missing_pct:.1f}%) of values are missing; "
|
|
99
|
+
"imputation would be unreliable. Note: missingness may be structural "
|
|
100
|
+
"('Not applicable') and needs domain confirmation."
|
|
101
|
+
),
|
|
102
|
+
),
|
|
103
|
+
Rule(
|
|
104
|
+
name="drop_high_missing",
|
|
105
|
+
predicate=lambda ctx: ctx["missing_pct"] > ctx["drop_threshold_pct"],
|
|
106
|
+
method="drop_column",
|
|
107
|
+
confidence="high",
|
|
108
|
+
reason_template=(
|
|
109
|
+
"More than {drop_threshold_pct:.0f}% ({missing_pct:.1f}%) of values are missing; "
|
|
110
|
+
"imputation would be unreliable."
|
|
111
|
+
),
|
|
112
|
+
),
|
|
113
|
+
Rule(
|
|
114
|
+
name="non_imputable_dtype",
|
|
115
|
+
predicate=lambda ctx: ctx["dtype_class"] in ("datetime", "text/id"),
|
|
116
|
+
method="do_not_impute",
|
|
117
|
+
confidence="high",
|
|
118
|
+
reason_template=(
|
|
119
|
+
"Column dtype is '{dtype_class}'; fabricating timestamps, IDs, or free text "
|
|
120
|
+
"introduces artificial records."
|
|
121
|
+
),
|
|
122
|
+
),
|
|
123
|
+
Rule(
|
|
124
|
+
name="suspected_mnar",
|
|
125
|
+
predicate=lambda ctx: ctx["pattern"] == "MNAR",
|
|
126
|
+
method="flag_and_impute",
|
|
127
|
+
confidence="medium",
|
|
128
|
+
reason_template=(
|
|
129
|
+
"Suspected MNAR missingness: add a '<col>_was_missing' indicator flag before "
|
|
130
|
+
"imputing so downstream models retain the missingness signal."
|
|
131
|
+
),
|
|
132
|
+
),
|
|
133
|
+
Rule(
|
|
134
|
+
name="block_time_series",
|
|
135
|
+
predicate=lambda ctx: ctx["pattern"] == "BLOCK" and ctx["dtype_class"] == "numeric",
|
|
136
|
+
method="interpolate_short_flag_long",
|
|
137
|
+
confidence="medium",
|
|
138
|
+
reason_template=(
|
|
139
|
+
"Contiguous block gaps detected; interpolate short gaps and flag long outages."
|
|
140
|
+
),
|
|
141
|
+
),
|
|
142
|
+
Rule(
|
|
143
|
+
name="numeric_trend_or_seasonal",
|
|
144
|
+
predicate=lambda ctx: (
|
|
145
|
+
ctx["dtype_class"] == "numeric"
|
|
146
|
+
and ctx["pattern"] in ("TREND", "SEASONAL")
|
|
147
|
+
),
|
|
148
|
+
method="interpolate",
|
|
149
|
+
confidence="high",
|
|
150
|
+
reason_template=(
|
|
151
|
+
"Numeric column exhibits {pattern} missingness over time/order; "
|
|
152
|
+
"time-aware interpolation preserves local trajectory."
|
|
153
|
+
),
|
|
154
|
+
),
|
|
155
|
+
Rule(
|
|
156
|
+
name="numeric_mar",
|
|
157
|
+
predicate=lambda ctx: ctx["dtype_class"] == "numeric" and ctx["pattern"] == "MAR",
|
|
158
|
+
method="knn",
|
|
159
|
+
confidence="high",
|
|
160
|
+
reason_template=(
|
|
161
|
+
"Numeric column is MAR driven by {drivers_str}; KNN imputation leverages "
|
|
162
|
+
"these correlated predictors."
|
|
163
|
+
),
|
|
164
|
+
),
|
|
165
|
+
Rule(
|
|
166
|
+
name="numeric_comissing",
|
|
167
|
+
predicate=lambda ctx: ctx["dtype_class"] == "numeric" and ctx["pattern"] == "CO-MISSING",
|
|
168
|
+
method="iterative",
|
|
169
|
+
confidence="medium",
|
|
170
|
+
reason_template=(
|
|
171
|
+
"Numeric column is co-missing with other columns; iterative multivariate "
|
|
172
|
+
"imputation models joint relationships."
|
|
173
|
+
),
|
|
174
|
+
),
|
|
175
|
+
Rule(
|
|
176
|
+
name="numeric_mcar_symmetric",
|
|
177
|
+
predicate=lambda ctx: ctx["dtype_class"] == "numeric" and ctx["is_symmetric"],
|
|
178
|
+
method="mean",
|
|
179
|
+
confidence="high",
|
|
180
|
+
reason_template=(
|
|
181
|
+
"Numeric column is MCAR and roughly symmetric; mean imputation is unbiased."
|
|
182
|
+
),
|
|
183
|
+
),
|
|
184
|
+
Rule(
|
|
185
|
+
name="numeric_mcar_skewed",
|
|
186
|
+
predicate=lambda ctx: ctx["dtype_class"] == "numeric",
|
|
187
|
+
method="median",
|
|
188
|
+
confidence="high",
|
|
189
|
+
reason_template=(
|
|
190
|
+
"Numeric column is MCAR and skewed; median imputation is robust to outliers."
|
|
191
|
+
),
|
|
192
|
+
),
|
|
193
|
+
Rule(
|
|
194
|
+
name="categorical_informative",
|
|
195
|
+
predicate=lambda ctx: (
|
|
196
|
+
ctx["dtype_class"] in ("categorical", "boolean")
|
|
197
|
+
and ctx["pattern"] in ("MAR", "TREND", "SEASONAL", "BLOCK", "CO-MISSING")
|
|
198
|
+
),
|
|
199
|
+
method="unknown_category",
|
|
200
|
+
confidence="medium",
|
|
201
|
+
reason_template=(
|
|
202
|
+
"Informative ({pattern}) missingness in {dtype_class} column; "
|
|
203
|
+
"assigning 'Unknown' preserves the missingness signal."
|
|
204
|
+
),
|
|
205
|
+
),
|
|
206
|
+
Rule(
|
|
207
|
+
name="categorical_mcar",
|
|
208
|
+
predicate=lambda ctx: ctx["dtype_class"] in ("categorical", "boolean"),
|
|
209
|
+
method="mode",
|
|
210
|
+
confidence="high",
|
|
211
|
+
reason_template=(
|
|
212
|
+
"{dtype_class} column is MCAR; mode imputation fills with the most frequent value."
|
|
213
|
+
),
|
|
214
|
+
),
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def recommend(
|
|
219
|
+
dtype_class: str,
|
|
220
|
+
missing_pct: float,
|
|
221
|
+
pattern: str,
|
|
222
|
+
drivers: list[str],
|
|
223
|
+
has_time_col: bool,
|
|
224
|
+
is_symmetric: bool = False,
|
|
225
|
+
missing_count: int | None = None,
|
|
226
|
+
total_count: int | None = None,
|
|
227
|
+
is_exact_comissing: bool = False,
|
|
228
|
+
partners: list[str] | None = None,
|
|
229
|
+
config: ThresholdConfig = DEFAULT_CONFIG,
|
|
230
|
+
) -> Recommendation:
|
|
231
|
+
"""Evaluate the declarative RULES table and return the first matching Recommendation."""
|
|
232
|
+
ctx = {
|
|
233
|
+
"dtype_class": dtype_class,
|
|
234
|
+
"missing_pct": missing_pct,
|
|
235
|
+
"pattern": pattern,
|
|
236
|
+
"drivers": drivers,
|
|
237
|
+
"drivers_str": _format_drivers(drivers),
|
|
238
|
+
"partners_str": _format_drivers(partners or []),
|
|
239
|
+
"has_time_col": has_time_col,
|
|
240
|
+
"is_symmetric": is_symmetric,
|
|
241
|
+
"is_exact_comissing": is_exact_comissing,
|
|
242
|
+
"drop_threshold_pct": config.drop_threshold_pct,
|
|
243
|
+
}
|
|
244
|
+
low_power = (
|
|
245
|
+
pattern == "insufficient data"
|
|
246
|
+
or (
|
|
247
|
+
missing_count is not None
|
|
248
|
+
and total_count is not None
|
|
249
|
+
and estimate_detection_power(total_count, missing_count) < 0.80
|
|
250
|
+
and missing_pct <= config.drop_threshold_pct
|
|
251
|
+
)
|
|
252
|
+
)
|
|
253
|
+
for rule in RULES:
|
|
254
|
+
if rule.predicate(ctx):
|
|
255
|
+
is_downgraded = low_power and (
|
|
256
|
+
rule.method not in ("none", "do_not_impute") or pattern == "insufficient data"
|
|
257
|
+
)
|
|
258
|
+
conf = "low" if is_downgraded else rule.confidence
|
|
259
|
+
reason = rule.reason_template.format(**ctx)
|
|
260
|
+
if low_power and rule.method not in ("none", "do_not_impute"):
|
|
261
|
+
reason += f" (Low-power regime: only {missing_count} missing values.)"
|
|
262
|
+
return Recommendation(
|
|
263
|
+
method=rule.method,
|
|
264
|
+
confidence=conf,
|
|
265
|
+
reason=reason,
|
|
266
|
+
drivers=list(drivers),
|
|
267
|
+
)
|
|
268
|
+
return Recommendation(
|
|
269
|
+
method="do_not_impute",
|
|
270
|
+
confidence="low",
|
|
271
|
+
reason="No matching rule; leaving column unchanged.",
|
|
272
|
+
drivers=list(drivers),
|
|
273
|
+
)
|
missinglens/report.py
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
"""Report generation and public `analyze()` entry point."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import html
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
import pandas as pd
|
|
11
|
+
|
|
12
|
+
from missinglens.analyzer import AnalysisResult, analyze_columns
|
|
13
|
+
from missinglens.apply import apply_recommendations
|
|
14
|
+
from missinglens.config import DEFAULT_CONFIG, ThresholdConfig, estimate_detection_power
|
|
15
|
+
from missinglens.patterns import PatternResult, detect_all_patterns
|
|
16
|
+
from missinglens.recommender import Recommendation, recommend
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class MissingReport:
|
|
20
|
+
"""Interactive report for per-column missingness analysis and recommendations."""
|
|
21
|
+
|
|
22
|
+
def __init__(
|
|
23
|
+
self,
|
|
24
|
+
df: pd.DataFrame,
|
|
25
|
+
analysis: AnalysisResult,
|
|
26
|
+
patterns: dict[str, str],
|
|
27
|
+
pattern_details: dict[str, dict[str, PatternResult]],
|
|
28
|
+
recommendations: dict[str, Recommendation],
|
|
29
|
+
time_col: str | None = None,
|
|
30
|
+
config: ThresholdConfig = DEFAULT_CONFIG,
|
|
31
|
+
) -> None:
|
|
32
|
+
self._df = df
|
|
33
|
+
self._analysis = analysis
|
|
34
|
+
self._patterns = patterns
|
|
35
|
+
self._pattern_details = pattern_details
|
|
36
|
+
self._recommendations = recommendations
|
|
37
|
+
self._time_col = time_col
|
|
38
|
+
self._config = config
|
|
39
|
+
|
|
40
|
+
def summary(self) -> pd.DataFrame:
|
|
41
|
+
"""Return a summary DataFrame with one row per column."""
|
|
42
|
+
rows = []
|
|
43
|
+
for col, info in self._analysis.columns.items():
|
|
44
|
+
rec = self._recommendations[col]
|
|
45
|
+
rows.append(
|
|
46
|
+
{
|
|
47
|
+
"column": col,
|
|
48
|
+
"missing_pct": round(info.missing_pct, 2),
|
|
49
|
+
"pattern": self._patterns[col],
|
|
50
|
+
"dtype": info.dtype_class,
|
|
51
|
+
"recommendation": rec.method,
|
|
52
|
+
"confidence": rec.confidence,
|
|
53
|
+
}
|
|
54
|
+
)
|
|
55
|
+
return pd.DataFrame(
|
|
56
|
+
rows,
|
|
57
|
+
columns=[
|
|
58
|
+
"column",
|
|
59
|
+
"missing_pct",
|
|
60
|
+
"pattern",
|
|
61
|
+
"dtype",
|
|
62
|
+
"recommendation",
|
|
63
|
+
"confidence",
|
|
64
|
+
],
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
def explain(self, column: str) -> str:
|
|
68
|
+
"""Return plain-English reasoning for one column."""
|
|
69
|
+
if column not in self._analysis.columns:
|
|
70
|
+
raise KeyError(f"Column '{column}' not found in report.")
|
|
71
|
+
info = self._analysis.columns[column]
|
|
72
|
+
rec = self._recommendations[column]
|
|
73
|
+
pat = self._patterns[column]
|
|
74
|
+
return (
|
|
75
|
+
f"Column '{column}' ({info.dtype_class}): {info.missing_pct:.1f}% missing "
|
|
76
|
+
f"({info.missing_count}/{info.total_count}). Detected pattern: {pat}. "
|
|
77
|
+
f"Recommendation: {rec.method} (confidence: {rec.confidence}). {rec.reason}"
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
def plot(self, column: str):
|
|
81
|
+
"""Plot missing rate over time/order for `column` (requires matplotlib)."""
|
|
82
|
+
if column not in self._df.columns:
|
|
83
|
+
raise KeyError(f"Column '{column}' not found in DataFrame.")
|
|
84
|
+
try:
|
|
85
|
+
import matplotlib.pyplot as plt
|
|
86
|
+
except ImportError as exc:
|
|
87
|
+
raise ImportError(
|
|
88
|
+
"matplotlib is required for report.plot(). "
|
|
89
|
+
"Install with `pip install missinglens[plot]`."
|
|
90
|
+
) from exc
|
|
91
|
+
|
|
92
|
+
mask = self._df[column].isna().astype(float).to_numpy()
|
|
93
|
+
n_buckets = min(20, max(5, len(mask) // 20))
|
|
94
|
+
buckets = np.array_split(mask, n_buckets)
|
|
95
|
+
rates = [float(b.mean()) * 100.0 for b in buckets if len(b) > 0]
|
|
96
|
+
|
|
97
|
+
fig, ax = plt.subplots(figsize=(8, 3.5))
|
|
98
|
+
ax.plot(range(1, len(rates) + 1), rates, marker="o")
|
|
99
|
+
ax.set_title(f"Missingness over buckets: {column} ({self._patterns[column]})")
|
|
100
|
+
ax.set_xlabel("Bucket")
|
|
101
|
+
ax.set_ylabel("Missing %")
|
|
102
|
+
ax.set_ylim(0, 105)
|
|
103
|
+
fig.tight_layout()
|
|
104
|
+
return fig
|
|
105
|
+
|
|
106
|
+
def to_dict(self) -> dict[str, Any]:
|
|
107
|
+
"""Serialize the report to a JSON-compatible dictionary."""
|
|
108
|
+
cols = {}
|
|
109
|
+
for col, info in self._analysis.columns.items():
|
|
110
|
+
rec = self._recommendations[col]
|
|
111
|
+
cols[col] = {
|
|
112
|
+
"dtype": info.dtype_class,
|
|
113
|
+
"missing_count": info.missing_count,
|
|
114
|
+
"total_count": info.total_count,
|
|
115
|
+
"missing_pct": round(info.missing_pct, 4),
|
|
116
|
+
"pattern": self._patterns[col],
|
|
117
|
+
"recommendation": rec.method,
|
|
118
|
+
"confidence": rec.confidence,
|
|
119
|
+
"reason": rec.reason,
|
|
120
|
+
"drivers": rec.drivers,
|
|
121
|
+
}
|
|
122
|
+
return {"time_col": self._time_col, "columns": cols}
|
|
123
|
+
|
|
124
|
+
def to_html(self, path: str | Path) -> Path:
|
|
125
|
+
"""Write a self-contained HTML report to `path`."""
|
|
126
|
+
summary_df = self.summary()
|
|
127
|
+
rows_html = []
|
|
128
|
+
for _, row in summary_df.iterrows():
|
|
129
|
+
col = str(row["column"])
|
|
130
|
+
reason = html.escape(self._recommendations[col].reason)
|
|
131
|
+
rows_html.append(
|
|
132
|
+
f"<tr><td>{html.escape(col)}</td>"
|
|
133
|
+
f"<td>{row['missing_pct']:.2f}%</td>"
|
|
134
|
+
f"<td>{html.escape(str(row['pattern']))}</td>"
|
|
135
|
+
f"<td>{html.escape(str(row['dtype']))}</td>"
|
|
136
|
+
f"<td>{html.escape(str(row['recommendation']))}</td>"
|
|
137
|
+
f"<td>{html.escape(str(row['confidence']))}</td>"
|
|
138
|
+
f"<td>{reason}</td></tr>"
|
|
139
|
+
)
|
|
140
|
+
doc = (
|
|
141
|
+
"<!DOCTYPE html><html><head><meta charset='utf-8'>"
|
|
142
|
+
"<title>missinglens Report</title>"
|
|
143
|
+
"<style>body{font-family:system-ui,sans-serif;margin:2rem;}"
|
|
144
|
+
"table{border-collapse:collapse;width:100%;}"
|
|
145
|
+
"th,td{border:1px solid #ddd;padding:8px;text-align:left;}"
|
|
146
|
+
"th{background:#f4f4f4;}</style></head><body>"
|
|
147
|
+
"<h1>missinglens Report</h1>"
|
|
148
|
+
"<table><thead><tr><th>Column</th><th>Missing %</th><th>Pattern</th>"
|
|
149
|
+
"<th>Dtype</th><th>Recommendation</th><th>Confidence</th><th>Reason</th>"
|
|
150
|
+
"</tr></thead><tbody>"
|
|
151
|
+
+ "".join(rows_html)
|
|
152
|
+
+ "</tbody></table></body></html>"
|
|
153
|
+
)
|
|
154
|
+
out_path = Path(path)
|
|
155
|
+
out_path.write_text(doc, encoding="utf-8")
|
|
156
|
+
return out_path
|
|
157
|
+
|
|
158
|
+
def apply(self) -> tuple[pd.DataFrame, list[str]]:
|
|
159
|
+
"""Apply recommendations to a copy of the DataFrame and return (df_clean, log)."""
|
|
160
|
+
return apply_recommendations(
|
|
161
|
+
self._df,
|
|
162
|
+
self._recommendations,
|
|
163
|
+
time_col=self._time_col,
|
|
164
|
+
config=self._config,
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def analyze(
|
|
169
|
+
df: pd.DataFrame,
|
|
170
|
+
time_col: str | None = None,
|
|
171
|
+
config: ThresholdConfig = DEFAULT_CONFIG,
|
|
172
|
+
) -> MissingReport:
|
|
173
|
+
"""Analyze missing data per column and return a MissingReport."""
|
|
174
|
+
analysis = analyze_columns(df, time_col=time_col)
|
|
175
|
+
patterns: dict[str, str] = {}
|
|
176
|
+
pattern_details: dict[str, dict[str, PatternResult]] = {}
|
|
177
|
+
recommendations: dict[str, Recommendation] = {}
|
|
178
|
+
|
|
179
|
+
for col, info in analysis.columns.items():
|
|
180
|
+
if info.missing_count == 0:
|
|
181
|
+
pat = "NONE"
|
|
182
|
+
details: dict[str, PatternResult] = {}
|
|
183
|
+
drivers: list[str] = []
|
|
184
|
+
is_exact_comissing = False
|
|
185
|
+
partners: list[str] = []
|
|
186
|
+
else:
|
|
187
|
+
pat, details = detect_all_patterns(
|
|
188
|
+
col,
|
|
189
|
+
df,
|
|
190
|
+
analysis.indicator_matrix,
|
|
191
|
+
time_col=time_col,
|
|
192
|
+
config=config,
|
|
193
|
+
)
|
|
194
|
+
observed_count = info.total_count - info.missing_count
|
|
195
|
+
if pat == "MCAR" and observed_count < config.min_missing_for_test:
|
|
196
|
+
pat = "insufficient data"
|
|
197
|
+
else:
|
|
198
|
+
low_pwr = estimate_detection_power(info.total_count, info.missing_count) < 0.80
|
|
199
|
+
if pat == "MCAR" and low_pwr:
|
|
200
|
+
pat = "no pattern detected (low power)"
|
|
201
|
+
drivers = details.get("MAR", PatternResult(False, 0.0, 1.0)).evidence.get("drivers", [])
|
|
202
|
+
comiss_ev = details.get("CO-MISSING", PatternResult(False, 0.0, 1.0)).evidence
|
|
203
|
+
is_exact_comissing = bool(comiss_ev.get("exact_group", False))
|
|
204
|
+
partners = comiss_ev.get("partners", [])
|
|
205
|
+
|
|
206
|
+
patterns[col] = pat
|
|
207
|
+
pattern_details[col] = details
|
|
208
|
+
recommendations[col] = recommend(
|
|
209
|
+
dtype_class=info.dtype_class,
|
|
210
|
+
missing_pct=info.missing_pct,
|
|
211
|
+
pattern=pat,
|
|
212
|
+
drivers=drivers,
|
|
213
|
+
has_time_col=time_col is not None,
|
|
214
|
+
is_symmetric=info.is_symmetric,
|
|
215
|
+
missing_count=info.missing_count,
|
|
216
|
+
total_count=info.total_count,
|
|
217
|
+
is_exact_comissing=is_exact_comissing,
|
|
218
|
+
partners=partners,
|
|
219
|
+
config=config,
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
return MissingReport(
|
|
223
|
+
df=df,
|
|
224
|
+
analysis=analysis,
|
|
225
|
+
patterns=patterns,
|
|
226
|
+
pattern_details=pattern_details,
|
|
227
|
+
recommendations=recommendations,
|
|
228
|
+
time_col=time_col,
|
|
229
|
+
config=config,
|
|
230
|
+
)
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: missinglens
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Analyze missing data per column: missingness rate, pattern detection, dtype-aware recommendations, and safe imputation.
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Homepage, https://github.com/ab-rar-6024/missinglens
|
|
7
|
+
Project-URL: Repository, https://github.com/ab-rar-6024/missinglens
|
|
8
|
+
Classifier: Development Status :: 3 - Alpha
|
|
9
|
+
Classifier: Intended Audience :: Science/Research
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
+
Classifier: Topic :: Scientific/Engineering
|
|
16
|
+
Requires-Python: >=3.10
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
License-File: LICENSE
|
|
19
|
+
Requires-Dist: pandas>=2.0
|
|
20
|
+
Requires-Dist: numpy>=1.24
|
|
21
|
+
Requires-Dist: scipy>=1.10
|
|
22
|
+
Requires-Dist: scikit-learn>=1.3
|
|
23
|
+
Requires-Dist: typer>=0.9
|
|
24
|
+
Provides-Extra: plot
|
|
25
|
+
Requires-Dist: matplotlib>=3.7; extra == "plot"
|
|
26
|
+
Provides-Extra: dev
|
|
27
|
+
Requires-Dist: pytest>=7.4; extra == "dev"
|
|
28
|
+
Requires-Dist: ruff>=0.4; extra == "dev"
|
|
29
|
+
Requires-Dist: matplotlib>=3.7; extra == "dev"
|
|
30
|
+
Requires-Dist: psutil>=5.9; extra == "dev"
|
|
31
|
+
Dynamic: license-file
|
|
32
|
+
|
|
33
|
+
# missinglens
|
|
34
|
+
|
|
35
|
+
Analyze missing data per column: how much is missing, what pattern the missingness follows, and what to do about it for that column's dtype.
|
|
36
|
+
|
|
37
|
+
## Install
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pip install missinglens
|
|
41
|
+
# Optional plotting support:
|
|
42
|
+
pip install "missinglens[plot]"
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Quick Start
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
import missinglens as ml
|
|
49
|
+
|
|
50
|
+
report = ml.analyze(df, time_col="date") # time_col optional
|
|
51
|
+
print(report.summary())
|
|
52
|
+
print(report.explain("income"))
|
|
53
|
+
report.to_html("report.html")
|
|
54
|
+
df_clean, log = report.apply() # does not mutate input df
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
CLI:
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
missinglens data.csv --time-col date --out report.html
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Supported Patterns
|
|
64
|
+
|
|
65
|
+
| Pattern | Detection Method | Default Recommendation (Numeric) |
|
|
66
|
+
| --- | --- | --- |
|
|
67
|
+
| `TREND` | Spearman correlation over adaptive time/row buckets | `interpolate` |
|
|
68
|
+
| `SEASONAL` | Chi-square across hour/weekday/month (`time_col` required) | `interpolate` |
|
|
69
|
+
| `BLOCK` | Run-length encoding vs Bernoulli null expectation | `interpolate_short_flag_long` |
|
|
70
|
+
| `MAR` | Mann-Whitney / Chi-square (BH-FDR) + shallow tree CV-AUC | `knn` (using driver columns) |
|
|
71
|
+
| `CO-MISSING` | Pearson correlation of missingness indicators | `iterative` |
|
|
72
|
+
| `MCAR` | Default when no structured pattern is significant | `mean` (symmetric) / `median` (skewed) |
|
|
73
|
+
|
|
74
|
+
## When to Trust the Verdict
|
|
75
|
+
|
|
76
|
+
- **High/Medium confidence (`missing_count >= 15`, `n >= 100`)**: Statistical tests have sufficient power; `MCAR` means no structured pattern was found despite adequate sample size.
|
|
77
|
+
- **Low confidence (`"no pattern detected (low power)"`)**: Triggered when `missing_count < 15` or `n < 100`. A lack of detected pattern here does **not** prove MCAR—treat the verdict as exploratory.
|
|
78
|
+
- **Domain semantics**: Real-world "not applicable" missingness (e.g., `PoolQC` in Ames Housing when a house has no pool) may appear as `MCAR` or `MAR` statistically; domain knowledge should override automated imputation.
|
|
79
|
+
|
|
80
|
+
## Calibration & Held-Out Evaluation
|
|
81
|
+
|
|
82
|
+
- Full 50-seed held-out evaluation (`n in {200, 1000, 10000}`, `rate in {0.02, 0.05, 0.10, 0.20}`) with 95% Wilson CIs is in [docs/evaluation.md](docs/evaluation.md).
|
|
83
|
+
- **`missingly` (`0.3.0`) Comparison** (10 held-out `n=1000, rate=0.20` datasets):
|
|
84
|
+
- `MAR` driven by a fully observed column: `missinglens` detected `10/10`; `missingly.mar_mnar_test(X, Y)` returned `[]` (`0/10`).
|
|
85
|
+
- `TREND`: `missinglens` detected `10/10`; `missingly.miss_ts_summary` reports gap counts/lengths only (no trend test).
|
|
86
|
+
- `SEASONAL`: `missinglens` detected `10/10`; `missingly` has no seasonal detector.
|
|
87
|
+
- **Performance (1M × 50)**: `31.99s`, `128.8 MB` tracemalloc peak (down from `260.38s` before 50k subsampling in `detect_mar`).
|
|
88
|
+
|
|
89
|
+
## Limitations
|
|
90
|
+
|
|
91
|
+
- `SEASONAL` detection requires `time_col` to be provided.
|
|
92
|
+
- `MNAR` cannot be proven from observed data alone; when suspected, use `flag_and_impute`.
|
|
93
|
+
- Low-sample regimes (`missing_count < 15` or `n < 100`) have low statistical power.
|
|
94
|
+
- `POWER_TABLE` was calibrated on synthetic trends and may overestimate power for weaker real-world trends.
|
|
95
|
+
- `TREND` is a significance test and may flag tiny effects at very large `n`.
|
|
96
|
+
- Patterns are chosen by fixed precedence (`BLOCK`, `TREND`, `SEASONAL`, `CO-MISSING`, `MAR`) and only the first is reported in `summary()`.
|
|
97
|
+
- All accuracy numbers come from synthetic data.
|
|
98
|
+
- In the fresh-seed evaluation (`3000..3049`, [docs/evaluation_final.md](docs/evaluation_final.md)), wrong-but-confident verdicts exceeded 5% in 3 regimes: `n=200, rate=0.20, MAR` (`3/50`, 6.0%), `n=200, rate=0.20, TREND` (`4/50`, 8.0%), and `n=10000, rate=0.10, CO-MISSING` (`6/100`, 6.0%).
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
missinglens/__init__.py,sha256=x0vRr4s-WZfX4V5gijXU-RNyvkEF9ohAwn2QxJ-A-Io,190
|
|
2
|
+
missinglens/analyzer.py,sha256=luefdegGCtRKAjHAFLM7JgwoEoy-WkShesU31n0_cng,3394
|
|
3
|
+
missinglens/apply.py,sha256=vhPhrIMXRYrJ58iLHAuzE9KFbL44ksg35Fl2dcXLo5w,4839
|
|
4
|
+
missinglens/cli.py,sha256=Ecn4rnzplk_MR8ooHoVHJE1Z-pa5eivg2kVVyEpoyWk,957
|
|
5
|
+
missinglens/config.py,sha256=cBeoEAdLD64ROvOXRXREYMtnQHbMMGPoFoPkHZCEXxA,1276
|
|
6
|
+
missinglens/patterns.py,sha256=d38hqkw16JQEx2XyEEbv8Q63vPsdEIxR1K4zpV_mNDY,13082
|
|
7
|
+
missinglens/recommender.py,sha256=mEyPmdKbuYjBKrwbIEYrPpurzDbvSrNM9fQ1PRPJPzE,9573
|
|
8
|
+
missinglens/report.py,sha256=NInLewXhsvtfUEkzqxmiBKe92rtHCi6yVQyzq8qZWiQ,8914
|
|
9
|
+
missinglens-0.1.0.dist-info/licenses/LICENSE,sha256=s-HmwTTmXux7GTVJSrwMKRQCDagXKjEw4cEG20cSqNo,1081
|
|
10
|
+
missinglens-0.1.0.dist-info/METADATA,sha256=8fMbin3fBW361ABqOkgpZu5WTDkMTPjK3gxDMjd7zgI,4926
|
|
11
|
+
missinglens-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
12
|
+
missinglens-0.1.0.dist-info/entry_points.txt,sha256=rsPPwPS8wnfq8j9KkCjBUx1GgKwA7iTB33IILxAwu8Y,52
|
|
13
|
+
missinglens-0.1.0.dist-info/top_level.txt,sha256=PkDC9qu-BSsBQclTFRLM0uNy6GtLUA7oXDkBmmr0WAg,12
|
|
14
|
+
missinglens-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 missinglens contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
missinglens
|