missr 2.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.
missr/__init__.py ADDED
@@ -0,0 +1,26 @@
1
+ """missr: find how your data went missing (MCAR, MAR or MNAR), in plain English.
2
+
3
+ >>> from missr import missr, load_dataset
4
+ >>> missr(load_dataset("healthcheck")) # doctest: +ELLIPSIS
5
+ Not MCAR, consistent with MAR: ...
6
+ """
7
+
8
+ from ._core import MissrResult, missr
9
+ from ._datasets import list_datasets, load_benchmarks, load_dataset
10
+ from ._mar import MarResult, mar, mnar
11
+ from ._mcar import McarResult, mcar
12
+
13
+ __version__ = "2.1.0"
14
+
15
+ __all__ = [
16
+ "MarResult",
17
+ "McarResult",
18
+ "MissrResult",
19
+ "list_datasets",
20
+ "load_benchmarks",
21
+ "load_dataset",
22
+ "mar",
23
+ "mcar",
24
+ "missr",
25
+ "mnar",
26
+ ]
missr/_checks.py ADDED
@@ -0,0 +1,163 @@
1
+ """Input checks and data preparation shared by mcar(), mar(), mnar() and missr()."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import numbers
7
+ from collections.abc import Mapping
8
+ from dataclasses import dataclass, field
9
+
10
+ import numpy as np
11
+ import pandas as pd
12
+
13
+
14
+ def as_dataframe(data) -> pd.DataFrame:
15
+ """Return `data` as a pandas DataFrame, or raise TypeError."""
16
+ if isinstance(data, pd.DataFrame):
17
+ df = data
18
+ else:
19
+ # polars, pyarrow and friends.
20
+ to_pandas = getattr(data, "to_pandas", None)
21
+ df = to_pandas() if callable(to_pandas) else None
22
+ if not isinstance(df, pd.DataFrame):
23
+ raise TypeError("Expected a data frame (a pandas DataFrame).")
24
+ if df.columns.has_duplicates:
25
+ raise ValueError("Column names must be unique.")
26
+ return df
27
+
28
+
29
+ def check_input(data) -> pd.DataFrame:
30
+ df = as_dataframe(data)
31
+ if not df.isna().to_numpy().any():
32
+ raise ValueError("There is no missing data in this dataset.")
33
+ return df
34
+
35
+
36
+ def check_alpha(alpha) -> None:
37
+ ok = (
38
+ isinstance(alpha, numbers.Real)
39
+ and not isinstance(alpha, (bool, np.bool_))
40
+ and math.isfinite(alpha)
41
+ and 0 < alpha < 1
42
+ )
43
+ if not ok:
44
+ raise ValueError("`alpha` must be a single number between 0 and 1.")
45
+
46
+
47
+ def check_verbose(verbose) -> None:
48
+ if not isinstance(verbose, (bool, np.bool_)):
49
+ raise ValueError("`verbose` must be True or False.")
50
+
51
+
52
+ # Column types ---------------------------------------------------------------
53
+
54
+
55
+ def is_logical(s: pd.Series) -> bool:
56
+ if pd.api.types.is_bool_dtype(s):
57
+ return True
58
+ if pd.api.types.is_object_dtype(s):
59
+ values = s.dropna()
60
+ return len(values) > 0 and all(isinstance(v, (bool, np.bool_)) for v in values)
61
+ return False
62
+
63
+
64
+ def column_kind(s: pd.Series) -> str:
65
+ """'numeric', 'categorical' or 'other' (R: numeric, factor, anything else).
66
+
67
+ Logical and text columns are treated as categories, as R's factor().
68
+ """
69
+ if is_logical(s):
70
+ return "categorical"
71
+ if pd.api.types.is_numeric_dtype(s) and not pd.api.types.is_complex_dtype(s):
72
+ return "numeric"
73
+ if (
74
+ isinstance(s.dtype, pd.CategoricalDtype)
75
+ or pd.api.types.is_object_dtype(s)
76
+ or pd.api.types.is_string_dtype(s)
77
+ ):
78
+ return "categorical"
79
+ return "other"
80
+
81
+
82
+ def numeric_values(s: pd.Series) -> np.ndarray:
83
+ return s.to_numpy(dtype=float, na_value=np.nan)
84
+
85
+
86
+ def categorical_values(s: pd.Series) -> pd.Categorical:
87
+ if is_logical(s):
88
+ # R: factor(<logical>) has levels FALSE, TRUE.
89
+ return pd.Categorical(s.map(lambda v: v if pd.isna(v) else bool(v)), categories=[False, True])
90
+ if isinstance(s.dtype, pd.CategoricalDtype):
91
+ return pd.Categorical(s)
92
+ return pd.Categorical(s.astype(object).where(s.notna(), None))
93
+
94
+
95
+ @dataclass
96
+ class Prepared:
97
+ """Data split into columns with gaps ("gappy") and fully recorded ones."""
98
+
99
+ columns: list
100
+ kinds: dict
101
+ values: dict # numeric -> float ndarray; categorical -> pd.Categorical
102
+ gappy: list = field(default_factory=list)
103
+ complete: list = field(default_factory=list)
104
+
105
+ @property
106
+ def n(self) -> int:
107
+ return len(next(iter(self.values.values()))) if self.values else 0
108
+
109
+
110
+ def prepare_data(df: pd.DataFrame) -> Prepared:
111
+ columns = list(df.columns)
112
+ kinds, values = {}, {}
113
+ for col in columns:
114
+ s = df[col]
115
+ kind = column_kind(s)
116
+ kinds[col] = kind
117
+ if kind == "numeric":
118
+ values[col] = numeric_values(s)
119
+ elif kind == "categorical":
120
+ values[col] = categorical_values(s)
121
+ else:
122
+ values[col] = s.to_numpy()
123
+ has_na = df.isna().any(axis=0)
124
+ gappy = [c for c in columns if has_na[c]]
125
+ complete = [c for c in columns if not has_na[c]]
126
+ return Prepared(columns, kinds, values, gappy, complete)
127
+
128
+
129
+ def _bt(cols) -> str:
130
+ return ", ".join(f"`{c}`" for c in cols)
131
+
132
+
133
+ def check_instrument(instrument, prep: Prepared) -> dict:
134
+ if instrument is None:
135
+ return {}
136
+ if isinstance(instrument, pd.Series):
137
+ instrument = instrument.to_dict()
138
+ if not isinstance(instrument, Mapping) or any(
139
+ v is None or (isinstance(v, float) and math.isnan(v)) for v in instrument.values()
140
+ ):
141
+ raise TypeError(
142
+ "`instrument` must be a dict, e.g. "
143
+ '`instrument={"employees": "employees_last_year"}`.'
144
+ )
145
+ instrument = dict(instrument)
146
+ bad_keys = [k for k in instrument if k not in prep.gappy]
147
+ if bad_keys:
148
+ raise ValueError(
149
+ "`instrument` keys must be columns with missing values. "
150
+ f"Not a column with missing values: {_bt(bad_keys)}."
151
+ )
152
+ bad_values = [v for v in instrument.values() if v not in prep.complete]
153
+ if bad_values:
154
+ raise ValueError(
155
+ "An instrument must be a fully recorded column (no missing values). "
156
+ f"Not fully recorded or not found: {_bt(bad_values)}."
157
+ )
158
+ not_numeric = [v for v in instrument.values() if prep.kinds[v] != "numeric"]
159
+ if not_numeric:
160
+ raise ValueError(
161
+ f"An instrument must be a numeric column. Not numeric: {_bt(not_numeric)}."
162
+ )
163
+ return instrument
missr/_core.py ADDED
@@ -0,0 +1,208 @@
1
+ """missr(): the one-call entry point."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import re
7
+ from dataclasses import dataclass, field
8
+
9
+ import numpy as np
10
+
11
+ from . import _format as fmt
12
+ from ._checks import check_alpha, check_input, check_verbose
13
+ from ._mar import MarResult, mar
14
+ from ._mcar import McarResult, mcar
15
+
16
+
17
+ @dataclass(repr=False)
18
+ class MissrResult:
19
+ """The result of :func:`missr`.
20
+
21
+ Attributes
22
+ ----------
23
+ verdict : str
24
+ The plain-English verdict.
25
+ mechanism : str or None
26
+ ``"MCAR"``, ``"MAR"`` or ``"MNAR"``: the mechanism the data are most
27
+ consistent with. None if the data could not be tested.
28
+ mcar : McarResult
29
+ The full :func:`mcar` result.
30
+ mar : MarResult
31
+ The full :func:`mar` result.
32
+ alpha, instrument, verbose
33
+ The arguments used.
34
+ """
35
+
36
+ verdict: str
37
+ mechanism: str | None
38
+ mcar: McarResult
39
+ mar: MarResult
40
+ alpha: float
41
+ instrument: dict = field(default_factory=dict)
42
+ verbose: bool = False
43
+
44
+ def summary(self, verbose: bool | None = None) -> str:
45
+ """The printed report. `verbose` defaults to the value used in the call."""
46
+ verbose = self.verbose if verbose is None else verbose
47
+ labels = ["MCAR (Little's test):", f"MNAR ({_mnar_test_label(self.mar)}):"]
48
+ width = max(len(s) for s in labels)
49
+ lines = [
50
+ *fmt.wrap(self.verdict),
51
+ "",
52
+ f" {labels[0].ljust(width)} {_step_summary_mcar(self.mcar)}",
53
+ f" {labels[1].ljust(width)} {_step_summary_mar(self.mar)}",
54
+ *fmt.instrument_advice(self.mar, "missr"),
55
+ ]
56
+ if verbose:
57
+ lines += ["", "-- MCAR: Little's test " + "-" * 52]
58
+ lines += fmt.mcar_details(self.mcar)
59
+ lines += ["", "-- MAR vs MNAR " + "-" * 60]
60
+ lines += fmt.mar_details(self.mar)
61
+ else:
62
+ lines += ["", fmt.VERBOSE_HINT]
63
+ return "\n".join(lines)
64
+
65
+ def __str__(self) -> str:
66
+ return self.summary()
67
+
68
+ __repr__ = __str__
69
+
70
+
71
+ def _mnar_test_label(mar_res: MarResult) -> str:
72
+ return "score + instrument tests" if (mar_res.tests["test"] == "instrument").any() else "score test"
73
+
74
+
75
+ def _step_summary_mcar(res: McarResult) -> str:
76
+ if math.isnan(res.p_value):
77
+ return "could not test"
78
+ word = "not MCAR" if res.p_value < res.alpha else "no evidence against"
79
+ return f"{word} ({fmt.fmt_p_eq(res.p_value)})"
80
+
81
+
82
+ def _step_summary_mar(res: MarResult) -> str:
83
+ p = res.tests["p_adjusted"].to_numpy(dtype=float)
84
+ p = float(np.nanmin(p)) if np.any(~np.isnan(p)) else math.inf
85
+ if res.result == "evidence_of_mnar":
86
+ return f"evidence of MNAR (smallest adjusted {fmt.fmt_p_eq(p)})"
87
+ if res.result == "no_evidence_of_mnar":
88
+ return f"no evidence of MNAR (smallest adjusted {fmt.fmt_p_eq(p)})"
89
+ return "could not test"
90
+
91
+
92
+ def combine_results(mcar_res: McarResult, mar_res: MarResult, alpha: float):
93
+ """Combine an mcar() and a mar() result into (mechanism, verdict)."""
94
+ mar_result = mar_res.result
95
+ mcar_p = mcar_res.p_value
96
+
97
+ if mar_result == "evidence_of_mnar":
98
+ return "MNAR", mar_res.verdict
99
+
100
+ if mar_result == "not_testable":
101
+ mar_note = " Could not test MAR against MNAR: " + re.sub(
102
+ r"^Could not test: ", "", mar_res.verdict
103
+ )
104
+ else:
105
+ untested = fmt.untested_variables(mar_res.tests)
106
+ mar_note = f" Could not test {fmt.backtick(untested)} for MNAR." if untested else ""
107
+
108
+ if math.isnan(mcar_p):
109
+ if mar_result == "not_testable":
110
+ return None, "Could not test: Little's test statistic could not be computed." + mar_note
111
+ return None, (
112
+ "Could not test for MCAR: Little's test statistic could not be "
113
+ "computed. No evidence of MNAR (this does not prove MAR)." + mar_note
114
+ )
115
+
116
+ if mcar_p >= alpha:
117
+ both = " and no evidence of MNAR" if mar_result == "no_evidence_of_mnar" else ""
118
+ return "MCAR", (
119
+ f"Consistent with MCAR: no evidence against MCAR{both} "
120
+ "(this does not prove MCAR)." + mar_note
121
+ )
122
+
123
+ if mar_result == "not_testable":
124
+ return None, "Not MCAR." + mar_note
125
+
126
+ return "MAR", (
127
+ "Not MCAR, consistent with MAR: the recorded values differ between "
128
+ "rows with and without missing values, but there is no evidence of "
129
+ "MNAR (this does not prove MAR)." + mar_note
130
+ )
131
+
132
+
133
+ def missr(data, instrument: dict | None = None, alpha: float = 0.05, verbose: bool = False) -> MissrResult:
134
+ """Find how data went missing: MCAR, MAR or MNAR.
135
+
136
+ Runs :func:`mcar` and :func:`mar` on the same data and combines them into
137
+ a single plain-English verdict:
138
+
139
+ * "Consistent with MCAR": no evidence against MCAR and no evidence of MNAR.
140
+ * "Not MCAR, consistent with MAR": the data are not MCAR, but there is no
141
+ evidence of MNAR.
142
+ * "Evidence of MNAR in `x`": whether a value of `x` is missing appears to
143
+ depend on the missing value itself.
144
+ * "Could not test": with the reason.
145
+
146
+ None of these is proof. A test can only find evidence *against* a
147
+ mechanism, so "consistent with" means the tests found no problem, not
148
+ that the mechanism is confirmed.
149
+
150
+ ========================== =================== =========
151
+ mcar() mar() missr()
152
+ ========================== =================== =========
153
+ no evidence against MCAR no evidence of MNAR MCAR
154
+ evidence data are not MCAR no evidence of MNAR MAR
155
+ either evidence of MNAR MNAR
156
+ ========================== =================== =========
157
+
158
+ Evidence of MNAR always wins, because Little's test can miss departures
159
+ from MCAR that do not shift the averages of the recorded values. Each test
160
+ is run at level `alpha`, so when the data are MCAR the chance that
161
+ missr() reports something else is somewhat above `alpha` (up to about
162
+ twice it).
163
+
164
+ Naming an `instrument` makes the MNAR check much more reliable: a fully
165
+ recorded column that is linked to the column with gaps but doesn't affect
166
+ whether it goes missing, such as the same measurement from last year. See
167
+ :func:`mar` for how the tests work.
168
+
169
+ Parameters
170
+ ----------
171
+ data : pandas.DataFrame
172
+ The data.
173
+ instrument : dict, optional
174
+ e.g. ``{"employees": "employees_last_year"}``. See :func:`mar`.
175
+ alpha : float
176
+ Significance level, default 0.05.
177
+ verbose : bool
178
+ If True, also print the statistics, hypotheses and assumptions of both
179
+ tests. Only affects printing.
180
+
181
+ Returns
182
+ -------
183
+ MissrResult
184
+
185
+ Examples
186
+ --------
187
+ >>> from missr import missr, load_dataset
188
+ >>> res = missr(load_dataset("companydata"),
189
+ ... instrument={"employees": "employees_last_year"})
190
+ >>> res.mechanism
191
+ 'MNAR'
192
+ """
193
+ check_input(data)
194
+ check_alpha(alpha)
195
+ check_verbose(verbose)
196
+
197
+ mar_res = mar(data, instrument=instrument, alpha=alpha)
198
+ mcar_res = mcar(data, alpha=alpha)
199
+ mechanism, verdict = combine_results(mcar_res, mar_res, alpha)
200
+ return MissrResult(
201
+ verdict=verdict,
202
+ mechanism=mechanism,
203
+ mcar=mcar_res,
204
+ mar=mar_res,
205
+ alpha=alpha,
206
+ instrument=mar_res.instrument,
207
+ verbose=bool(verbose),
208
+ )
missr/_datasets.py ADDED
@@ -0,0 +1,101 @@
1
+ """Example and benchmark datasets shipped with missr."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import gzip
6
+ import json
7
+ from importlib import resources
8
+
9
+ import pandas as pd
10
+
11
+ DATASETS = {
12
+ "animalhealth": "Heart rates of various animals; `heart_rate` is MCAR (200 x 2).",
13
+ "companydata": (
14
+ "Company metrics (1000 x 6). `employees` is MNAR: firms with fewer employees "
15
+ "leave it blank more often. `product_rating` is MCAR. `employees_last_year` "
16
+ "is fully recorded and a valid instrument for `employees`."
17
+ ),
18
+ "healthcheck": "Health check-up metrics; MAR (200 x 5).",
19
+ "pollutionlevels": "Pollution levels of settlements; MCAR (200 x 4).",
20
+ "testscores": "Students' test scores, with no missing values (200 x 2).",
21
+ }
22
+
23
+
24
+ def _data_file(name: str):
25
+ return resources.files("missr").joinpath("data", name)
26
+
27
+
28
+ def list_datasets() -> dict:
29
+ """Names and one-line descriptions of the example datasets."""
30
+ return dict(DATASETS)
31
+
32
+
33
+ def load_dataset(name: str) -> pd.DataFrame:
34
+ """Load an example dataset by name.
35
+
36
+ Available: ``animalhealth`` (MCAR), ``companydata`` (MNAR, with an
37
+ instrument), ``healthcheck`` (MAR), ``pollutionlevels`` (MCAR) and
38
+ ``testscores`` (no missing values). See :func:`list_datasets`.
39
+
40
+ >>> from missr import load_dataset
41
+ >>> load_dataset("healthcheck").shape
42
+ (200, 5)
43
+ """
44
+ if name not in DATASETS:
45
+ raise ValueError(f"Unknown dataset {name!r}. Available: {', '.join(DATASETS)}.")
46
+ with _data_file(f"{name}.csv").open("rb") as f:
47
+ return pd.read_csv(f)
48
+
49
+
50
+ def load_benchmarks() -> pd.DataFrame:
51
+ """Sixty benchmark datasets with a known missing data mechanism.
52
+
53
+ Twenty each of MCAR, MAR and MNAR. Each is a real, complete dataset
54
+ (``quakes`` from R's datasets package, ``Boston`` and ``nlschools`` from
55
+ R's MASS package) with values removed by a known rule, so the true
56
+ mechanism is certain. Under MCAR every row is equally likely to lose its
57
+ value; under MAR the chance follows a logistic curve in a fully recorded
58
+ column; under MNAR it follows a logistic curve in the value itself (slope
59
+ 2 per standard deviation, so the MNAR datasets are clear-cut).
60
+
61
+ Each dataset also names a valid instrument for its column(s) with gaps.
62
+ With it, :func:`mar` catches every MNAR dataset; without it, about half.
63
+
64
+ Returns
65
+ -------
66
+ pandas.DataFrame
67
+ One row per dataset with columns ``id``, ``mechanism`` (the true
68
+ mechanism), ``source``, ``gappy`` (the column(s) given missing values),
69
+ ``rule``, ``seed``, ``instrument`` (a dict, ready to pass to
70
+ :func:`mar`) and ``data`` (the dataset itself, a DataFrame).
71
+
72
+ >>> from missr import load_benchmarks, mar
73
+ >>> b = load_benchmarks()
74
+ >>> row = b[b["id"] == "mnar_quakes_01"].iloc[0]
75
+ >>> mar(row["data"], instrument=row["instrument"]).result
76
+ 'evidence_of_mnar'
77
+ """
78
+ with _data_file("benchmarks.json").open("rb") as f:
79
+ meta = json.load(f)
80
+ by_source = {}
81
+ for source in sorted({m["source"] for m in meta}):
82
+ with _data_file(f"benchmarks_{source}.csv.gz").open("rb") as raw:
83
+ with gzip.open(raw) as f:
84
+ by_source[source] = pd.read_csv(f)
85
+ rows = []
86
+ for m in meta:
87
+ frame = by_source[m["source"]]
88
+ data = frame.loc[frame["id"] == m["id"], m["columns"]].reset_index(drop=True)
89
+ rows.append(
90
+ {
91
+ "id": m["id"],
92
+ "mechanism": m["mechanism"],
93
+ "source": m["source"],
94
+ "gappy": m["gappy"],
95
+ "rule": m["rule"],
96
+ "seed": m["seed"],
97
+ "instrument": dict(m["instrument"]),
98
+ "data": data,
99
+ }
100
+ )
101
+ return pd.DataFrame(rows)