missinglab-workbench 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.
@@ -0,0 +1,138 @@
1
+
2
+ """Shared imputation and benchmarking operations for the desktop app."""
3
+
4
+ from pathlib import Path
5
+
6
+ from missinglab.config import DEFAULT_RANDOM_STATE
7
+ import numpy as np
8
+ import pandas as pd
9
+
10
+ from missinglab.core.imputation import knn_imputation, iterative_imputation
11
+ from missinglab.core.benchmark import benchmark_imputation
12
+
13
+
14
+ METHODS = ("Mean", "Median", "Mode", "KNN", "Iterative")
15
+
16
+
17
+ def impute_dataset(df, method, n_neighbors=5, max_iter=10):
18
+ """Impute numerical or categorical values while preserving observed cells."""
19
+
20
+ if not isinstance(df, pd.DataFrame) or df.empty or not df.columns.is_unique:
21
+ raise ValueError("Provide a nonempty DataFrame with unique columns.")
22
+
23
+ if method not in METHODS:
24
+ raise ValueError("Unknown imputation method.")
25
+
26
+ numeric_columns = [
27
+ column for column in df.columns
28
+ if pd.api.types.is_numeric_dtype(df[column])
29
+ and not pd.api.types.is_bool_dtype(df[column])
30
+ ]
31
+
32
+ categorical_columns = [
33
+ column for column in df.columns
34
+ if (
35
+ pd.api.types.is_object_dtype(df[column])
36
+ or isinstance(df[column].dtype, pd.CategoricalDtype)
37
+ or pd.api.types.is_string_dtype(df[column])
38
+ or pd.api.types.is_bool_dtype(df[column])
39
+ )
40
+ ]
41
+
42
+ # Check numerical columns for unsupported values.
43
+ for column in numeric_columns:
44
+ if pd.api.types.is_complex_dtype(df[column]):
45
+ raise ValueError("Complex numbers are not supported.")
46
+
47
+ if np.isinf(df[column].to_numpy(dtype=float, na_value=np.nan)).any():
48
+ raise ValueError("Numerical columns must not contain infinite values.")
49
+
50
+ if method == "KNN":
51
+ result = knn_imputation(df, n_neighbors=n_neighbors)
52
+
53
+ elif method == "Iterative":
54
+ result = iterative_imputation(
55
+ df,
56
+ max_iter=max_iter,
57
+ random_state=DEFAULT_RANDOM_STATE
58
+ )
59
+
60
+ else:
61
+ result = df.copy(deep=True)
62
+
63
+ if method == "Mode":
64
+ # Fill missing categorical values with the most frequent value.
65
+ for column in categorical_columns:
66
+ values = df[column]
67
+
68
+ if values.isna().any() and values.notna().any():
69
+ most_frequent = values.mode(dropna=True).iloc[0]
70
+ result[column] = values.fillna(most_frequent)
71
+
72
+ else:
73
+ # Mean and Median fill numerical columns only.
74
+ for column in numeric_columns:
75
+ values = df[column]
76
+
77
+ if values.isna().any() and values.notna().any():
78
+ if method == "Mean":
79
+ fill_value = values.mean()
80
+ else:
81
+ fill_value = values.median()
82
+
83
+ result[column] = values.astype(float).fillna(fill_value)
84
+
85
+ # Ensure that the imputer did not change the dataset structure.
86
+ if not result.index.equals(df.index) or not result.columns.equals(df.columns):
87
+ raise ValueError("Imputation changed the dataset structure.")
88
+
89
+ # Ensure that originally observed values remain unchanged.
90
+ for column in df.columns:
91
+ observed = df[column].notna().to_numpy()
92
+
93
+ try:
94
+ pd.testing.assert_series_equal(
95
+ result[column].iloc[observed],
96
+ df[column].iloc[observed],
97
+ check_dtype=False,
98
+ check_exact=True,
99
+ check_categorical=False
100
+ )
101
+ except AssertionError as exc:
102
+ raise ValueError(
103
+ f"Imputation changed observed values in {column}."
104
+ ) from exc
105
+
106
+ return result
107
+
108
+
109
+ def compare_imputation_methods(reference, simulated, n_neighbors=5, max_iter=10):
110
+ """Benchmark five methods on the same masked observations."""
111
+
112
+ results = {
113
+ method: impute_dataset(simulated, method, n_neighbors, max_iter)
114
+ for method in METHODS
115
+ }
116
+
117
+ return benchmark_imputation(reference, simulated, results)
118
+
119
+
120
+ def export_cleaned_csv(df, destination, source):
121
+ """Write an imputed copy, refusing to overwrite the imported source."""
122
+
123
+ destination = Path(destination)
124
+ source = Path(source)
125
+
126
+ if destination.suffix.lower() != ".csv":
127
+ raise ValueError("Choose a CSV destination.")
128
+
129
+ if destination.resolve() == source.resolve() or (
130
+ destination.exists()
131
+ and source.exists()
132
+ and destination.samefile(source)
133
+ ):
134
+ raise ValueError(
135
+ "Choose a different filename; the source CSV must not be overwritten."
136
+ )
137
+
138
+ df.to_csv(destination, index=False, encoding="utf-8-sig")
@@ -0,0 +1,72 @@
1
+
2
+ import pandas as pd
3
+ from pyampute.exploration.mcar_statistical_tests import MCARTest
4
+
5
+ #the purpose of this function is to help users understand whether the missing values
6
+ # in their dataset are consistent with being completely random
7
+ # so we will check the dataset
8
+ #check for missing values
9
+ #check data types
10
+ #run the test
11
+ #interpret the results
12
+
13
+ import pandas as pd
14
+ from pyampute.exploration.mcar_statistical_tests import MCARTest
15
+
16
+
17
+ def run_mcar_test(df: pd.DataFrame) -> dict:
18
+ """Run Little's MCAR test using numerical columns."""
19
+
20
+ if not isinstance(df, pd.DataFrame):
21
+ raise TypeError("Expected a pandas DataFrame")
22
+
23
+ if df.empty:
24
+ raise ValueError("Dataset cannot be empty")
25
+
26
+ if not df.isna().any().any():
27
+ raise ValueError("Dataset has no missing values")
28
+
29
+ # Select numerical columns only.
30
+ numeric_df = df.select_dtypes(include="number")
31
+
32
+ # Remove columns that contain only missing values.
33
+ numeric_df = numeric_df.dropna(axis=1, how="all")
34
+
35
+ if numeric_df.empty:
36
+ raise ValueError("No usable numerical columns found")
37
+
38
+ if not numeric_df.isna().any().any():
39
+ raise ValueError("No missing values found in numerical columns")
40
+
41
+ # Record which columns are included and excluded.
42
+ included_columns = numeric_df.columns.tolist()
43
+ excluded_columns = [
44
+ column for column in df.columns
45
+ if column not in included_columns
46
+ ]
47
+
48
+ test = MCARTest(method="little")
49
+ p_value = test.little_mcar_test(numeric_df)
50
+
51
+ if pd.isna(p_value):
52
+ raise ValueError("MCAR test could not calculate a valid p-value")
53
+
54
+ if not 0 <= p_value <= 1:
55
+ raise ValueError("MCAR test returned an invalid p-value")
56
+
57
+ if p_value <= 0.05:
58
+ interpretation = (
59
+ "Reject MCAR: evidence suggests data is not MCAR."
60
+ )
61
+ else:
62
+ interpretation = (
63
+ "Do not reject MCAR: insufficient evidence against MCAR."
64
+ )
65
+
66
+ return {
67
+ "p_value": float(p_value),
68
+ "significance_level": 0.05,
69
+ "interpretation": interpretation,
70
+ "included_columns": included_columns,
71
+ "excluded_columns": excluded_columns
72
+ }