missr 2.1.0__tar.gz
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-2.1.0/.gitignore +5 -0
- missr-2.1.0/LICENSE +21 -0
- missr-2.1.0/PKG-INFO +97 -0
- missr-2.1.0/README.md +73 -0
- missr-2.1.0/pyproject.toml +43 -0
- missr-2.1.0/src/missr/__init__.py +26 -0
- missr-2.1.0/src/missr/_checks.py +163 -0
- missr-2.1.0/src/missr/_core.py +208 -0
- missr-2.1.0/src/missr/_datasets.py +101 -0
- missr-2.1.0/src/missr/_format.py +255 -0
- missr-2.1.0/src/missr/_mar.py +460 -0
- missr-2.1.0/src/missr/_mcar.py +166 -0
- missr-2.1.0/src/missr/_stats.py +320 -0
- missr-2.1.0/src/missr/data/animalhealth.csv +201 -0
- missr-2.1.0/src/missr/data/benchmarks.json +728 -0
- missr-2.1.0/src/missr/data/benchmarks_Boston.csv.gz +0 -0
- missr-2.1.0/src/missr/data/benchmarks_nlschools.csv.gz +0 -0
- missr-2.1.0/src/missr/data/benchmarks_quakes.csv.gz +0 -0
- missr-2.1.0/src/missr/data/companydata.csv +1001 -0
- missr-2.1.0/src/missr/data/healthcheck.csv +201 -0
- missr-2.1.0/src/missr/data/pollutionlevels.csv +201 -0
- missr-2.1.0/src/missr/data/testscores.csv +201 -0
- missr-2.1.0/src/missr/py.typed +0 -0
- missr-2.1.0/tests/conftest.py +13 -0
- missr-2.1.0/tests/r_reference.json +1 -0
- missr-2.1.0/tests/test_against_r.py +79 -0
- missr-2.1.0/tests/test_benchmarks.py +87 -0
- missr-2.1.0/tests/test_mar.py +220 -0
- missr-2.1.0/tests/test_mcar.py +71 -0
- missr-2.1.0/tests/test_missr.py +146 -0
- missr-2.1.0/tests/test_score_test.py +59 -0
- missr-2.1.0/tests/test_stats.py +37 -0
missr-2.1.0/.gitignore
ADDED
missr-2.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 missr authors
|
|
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.
|
missr-2.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: missr
|
|
3
|
+
Version: 2.1.0
|
|
4
|
+
Summary: Test missing data mechanisms (MCAR, MAR, MNAR) with plain-English verdicts.
|
|
5
|
+
Project-URL: Homepage, https://github.com/NoahHellen/missr
|
|
6
|
+
Project-URL: Documentation, https://noahhellen.github.io/missr/
|
|
7
|
+
Project-URL: Issues, https://github.com/NoahHellen/missr/issues
|
|
8
|
+
Project-URL: R package, https://cran.r-project.org/package=missr
|
|
9
|
+
Author-email: Noah William Trelawny Hellen <noahhellen@gmail.com>
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: Little's test,MAR,MCAR,MNAR,missing data,statistics
|
|
13
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
14
|
+
Classifier: Intended Audience :: Science/Research
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
18
|
+
Classifier: Typing :: Typed
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Requires-Dist: numpy>=1.24
|
|
21
|
+
Requires-Dist: pandas>=1.5
|
|
22
|
+
Requires-Dist: scipy>=1.10
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
# missr
|
|
26
|
+
|
|
27
|
+
[](https://pypi.org/project/missr/)
|
|
28
|
+
[](https://cran.r-project.org/package=missr)
|
|
29
|
+
|
|
30
|
+
missr tells you how your data went missing, in plain English: missing
|
|
31
|
+
completely at random (MCAR), missing at random (MAR), or missing not at
|
|
32
|
+
random (MNAR).
|
|
33
|
+
|
|
34
|
+
This is the Python version of the [missr R package](https://cran.r-project.org/package=missr).
|
|
35
|
+
It runs the same tests and gives the same answers.
|
|
36
|
+
|
|
37
|
+
## Install
|
|
38
|
+
|
|
39
|
+
```sh
|
|
40
|
+
uv add missr
|
|
41
|
+
# or
|
|
42
|
+
pip install missr
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Use
|
|
46
|
+
|
|
47
|
+
Give `missr()` a pandas DataFrame with missing values:
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
from missr import missr, load_dataset
|
|
51
|
+
|
|
52
|
+
missr(load_dataset("healthcheck"))
|
|
53
|
+
#> Not MCAR, consistent with MAR: the recorded values differ between rows with
|
|
54
|
+
#> and without missing values, but there is no evidence of MNAR (this does not
|
|
55
|
+
#> prove MAR).
|
|
56
|
+
#> ...
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
It answers with one of:
|
|
60
|
+
|
|
61
|
+
| Verdict | What it means |
|
|
62
|
+
|---|---|
|
|
63
|
+
| Consistent with MCAR | Nothing links the gaps to the data. |
|
|
64
|
+
| Not MCAR, consistent with MAR | The gaps are linked to values you recorded, but not to the missing values themselves. |
|
|
65
|
+
| Evidence of MNAR | Whether a value is missing seems to depend on the missing value itself. |
|
|
66
|
+
|
|
67
|
+
To make the MNAR check much more reliable, name an *instrument*: a fully
|
|
68
|
+
recorded column that's linked to the column with gaps but doesn't affect
|
|
69
|
+
whether it goes missing, such as the same measurement from last year.
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
res = missr(load_dataset("companydata"),
|
|
73
|
+
instrument={"employees": "employees_last_year"})
|
|
74
|
+
res.mechanism # 'MNAR'
|
|
75
|
+
res.verdict # the plain-English verdict
|
|
76
|
+
res.mar.tests # a DataFrame of every test
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Add `verbose=True` (or call `res.summary(verbose=True)`) to see the
|
|
80
|
+
statistics behind the verdict. You can also run the individual tests:
|
|
81
|
+
|
|
82
|
+
- `mcar(df)`: Little's (1988) test of MCAR.
|
|
83
|
+
- `mar(df)` / `mnar(df)`: the score test of Wang, Lu & Liu (2023), plus an
|
|
84
|
+
instrument test after Breunig (2019) when you name an instrument.
|
|
85
|
+
|
|
86
|
+
## Datasets
|
|
87
|
+
|
|
88
|
+
- `load_dataset(name)`: the example datasets `animalhealth`, `companydata`,
|
|
89
|
+
`healthcheck`, `pollutionlevels` and `testscores` (see `list_datasets()`).
|
|
90
|
+
- `load_benchmarks()`: 60 real datasets with values removed by a known
|
|
91
|
+
rule (20 each MCAR, MAR and MNAR), each with a valid instrument.
|
|
92
|
+
|
|
93
|
+
## Learn more
|
|
94
|
+
|
|
95
|
+
- [Full documentation](https://noahhellen.github.io/missr/) (written for the
|
|
96
|
+
R package; the methods and verdicts are the same)
|
|
97
|
+
- [Source code](https://github.com/NoahHellen/missr)
|
missr-2.1.0/README.md
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
# missr
|
|
2
|
+
|
|
3
|
+
[](https://pypi.org/project/missr/)
|
|
4
|
+
[](https://cran.r-project.org/package=missr)
|
|
5
|
+
|
|
6
|
+
missr tells you how your data went missing, in plain English: missing
|
|
7
|
+
completely at random (MCAR), missing at random (MAR), or missing not at
|
|
8
|
+
random (MNAR).
|
|
9
|
+
|
|
10
|
+
This is the Python version of the [missr R package](https://cran.r-project.org/package=missr).
|
|
11
|
+
It runs the same tests and gives the same answers.
|
|
12
|
+
|
|
13
|
+
## Install
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
uv add missr
|
|
17
|
+
# or
|
|
18
|
+
pip install missr
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Use
|
|
22
|
+
|
|
23
|
+
Give `missr()` a pandas DataFrame with missing values:
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
from missr import missr, load_dataset
|
|
27
|
+
|
|
28
|
+
missr(load_dataset("healthcheck"))
|
|
29
|
+
#> Not MCAR, consistent with MAR: the recorded values differ between rows with
|
|
30
|
+
#> and without missing values, but there is no evidence of MNAR (this does not
|
|
31
|
+
#> prove MAR).
|
|
32
|
+
#> ...
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
It answers with one of:
|
|
36
|
+
|
|
37
|
+
| Verdict | What it means |
|
|
38
|
+
|---|---|
|
|
39
|
+
| Consistent with MCAR | Nothing links the gaps to the data. |
|
|
40
|
+
| Not MCAR, consistent with MAR | The gaps are linked to values you recorded, but not to the missing values themselves. |
|
|
41
|
+
| Evidence of MNAR | Whether a value is missing seems to depend on the missing value itself. |
|
|
42
|
+
|
|
43
|
+
To make the MNAR check much more reliable, name an *instrument*: a fully
|
|
44
|
+
recorded column that's linked to the column with gaps but doesn't affect
|
|
45
|
+
whether it goes missing, such as the same measurement from last year.
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
res = missr(load_dataset("companydata"),
|
|
49
|
+
instrument={"employees": "employees_last_year"})
|
|
50
|
+
res.mechanism # 'MNAR'
|
|
51
|
+
res.verdict # the plain-English verdict
|
|
52
|
+
res.mar.tests # a DataFrame of every test
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Add `verbose=True` (or call `res.summary(verbose=True)`) to see the
|
|
56
|
+
statistics behind the verdict. You can also run the individual tests:
|
|
57
|
+
|
|
58
|
+
- `mcar(df)`: Little's (1988) test of MCAR.
|
|
59
|
+
- `mar(df)` / `mnar(df)`: the score test of Wang, Lu & Liu (2023), plus an
|
|
60
|
+
instrument test after Breunig (2019) when you name an instrument.
|
|
61
|
+
|
|
62
|
+
## Datasets
|
|
63
|
+
|
|
64
|
+
- `load_dataset(name)`: the example datasets `animalhealth`, `companydata`,
|
|
65
|
+
`healthcheck`, `pollutionlevels` and `testscores` (see `list_datasets()`).
|
|
66
|
+
- `load_benchmarks()`: 60 real datasets with values removed by a known
|
|
67
|
+
rule (20 each MCAR, MAR and MNAR), each with a valid instrument.
|
|
68
|
+
|
|
69
|
+
## Learn more
|
|
70
|
+
|
|
71
|
+
- [Full documentation](https://noahhellen.github.io/missr/) (written for the
|
|
72
|
+
R package; the methods and verdicts are the same)
|
|
73
|
+
- [Source code](https://github.com/NoahHellen/missr)
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.27"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "missr"
|
|
7
|
+
version = "2.1.0"
|
|
8
|
+
description = "Test missing data mechanisms (MCAR, MAR, MNAR) with plain-English verdicts."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.10"
|
|
13
|
+
authors = [{ name = "Noah William Trelawny Hellen", email = "noahhellen@gmail.com" }]
|
|
14
|
+
keywords = ["missing data", "MCAR", "MAR", "MNAR", "Little's test", "statistics"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 5 - Production/Stable",
|
|
17
|
+
"Intended Audience :: Science/Research",
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Topic :: Scientific/Engineering :: Mathematics",
|
|
21
|
+
"Typing :: Typed",
|
|
22
|
+
]
|
|
23
|
+
dependencies = [
|
|
24
|
+
"numpy>=1.24",
|
|
25
|
+
"pandas>=1.5",
|
|
26
|
+
"scipy>=1.10",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
[project.urls]
|
|
30
|
+
Homepage = "https://github.com/NoahHellen/missr"
|
|
31
|
+
Documentation = "https://noahhellen.github.io/missr/"
|
|
32
|
+
Issues = "https://github.com/NoahHellen/missr/issues"
|
|
33
|
+
"R package" = "https://cran.r-project.org/package=missr"
|
|
34
|
+
|
|
35
|
+
[dependency-groups]
|
|
36
|
+
dev = ["pytest>=8"]
|
|
37
|
+
|
|
38
|
+
[tool.hatch.build.targets.sdist]
|
|
39
|
+
include = ["src", "tests", "README.md", "LICENSE"]
|
|
40
|
+
|
|
41
|
+
[tool.pytest.ini_options]
|
|
42
|
+
testpaths = ["tests", "src"]
|
|
43
|
+
addopts = "--doctest-modules"
|
|
@@ -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
|
+
]
|
|
@@ -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
|
|
@@ -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
|
+
)
|