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.
missinglab/__init__.py ADDED
File without changes
missinglab/__main__.py ADDED
@@ -0,0 +1,22 @@
1
+ """Entry point: python -m missinglab."""
2
+ # this is the entry point that python finds once we run
3
+ #python -m missinglab
4
+
5
+ def main() -> None:
6
+
7
+ from missinglab.gui.app import MissingLabApp
8
+ #the previous line connects the startup file to app.py
9
+ #where we have defined desktop interface
10
+ app = MissingLabApp() #creating the application window
11
+ app.mainloop() #keep runnning the application and starting
12
+ #Tkinter's event loop
13
+
14
+
15
+ if __name__ == "__main__":
16
+ main()
17
+ #the last one ensures that main() runs.
18
+
19
+ #so the connection becomes running a command
20
+ #start the application __main__.py
21
+ # gui/app.py creates the interface
22
+ #io/ and core/ load and analyze the data when requested
missinglab/config.py ADDED
@@ -0,0 +1 @@
1
+ DEFAULT_RANDOM_STATE = 42
File without changes
@@ -0,0 +1,70 @@
1
+ """missing-data summary functions (no GUI dependencies)."""
2
+
3
+ from dataclasses import asdict, dataclass
4
+
5
+ import pandas as pd
6
+
7
+
8
+ @dataclass(frozen=True)
9
+ class DatasetSummary:
10
+ """it stores the overall statistics of a dataset"""
11
+ """for example, it stores the nb of rows and cols"""
12
+ """total number of cells, nb and % of missing cells"""
13
+ """nb of cols containing missing values"""
14
+ rows: int
15
+ columns: int
16
+ total_cells: int
17
+ missing_cells: int
18
+ missing_percent: float
19
+ columns_with_missing: int
20
+
21
+ def to_dict(self) -> dict[str, int | float]:
22
+ return asdict(self)
23
+
24
+ """the previous function to_dict is used only
25
+ to transform the results into a python dictionary"""
26
+
27
+ def summarize_dataset(df: pd.DataFrame) -> DatasetSummary:
28
+ """Compute dataset-level missingness; supports empty DataFrames safely."""
29
+ """"it calculates the overall missing data statistics """
30
+ if not isinstance(df, pd.DataFrame):
31
+ raise TypeError("Expected a pandas DataFrame")
32
+ rows, columns = df.shape
33
+ total = rows * columns #calculating the total nb of elements
34
+ missing = int(df.isna().sum().sum()) #counts all missing values in the dataset
35
+ return DatasetSummary(
36
+ rows=rows,
37
+ columns=columns,
38
+ total_cells=total,
39
+ missing_cells=missing,
40
+ missing_percent=round(100 * missing / total, 2) if total else 0.0,
41
+ columns_with_missing=int(df.isna().any(axis=0).sum()),
42
+ )
43
+ """return all these statistics to the GUI"""
44
+
45
+ def column_missingness(df: pd.DataFrame) -> pd.DataFrame:
46
+ """Summarize missing entries per column without changing the source data."""
47
+ if not isinstance(df, pd.DataFrame):
48
+ raise TypeError("Expected a pandas DataFrame")
49
+ counts = df.isna().sum(axis=0)
50
+ percent = (counts / len(df) * 100) if len(df) else counts.astype(float)
51
+ return pd.DataFrame({
52
+ "column": [str(name) for name in df.columns],
53
+ "dtype": [str(dtype) for dtype in df.dtypes],
54
+ "missing_count": counts.to_numpy(dtype=int),
55
+ "missing_percent": percent.round(2).to_numpy(dtype=float),
56
+ })
57
+
58
+ #TILL NOW: we are calculating the overall missingness, missingness per column
59
+ #and displaying the results
60
+
61
+ #In the next function we will define, we will check every cell in the dataset
62
+ #so it returns true if the missing value is actually missing
63
+ #false if the value exists
64
+ #this step gives us information about the dataset so we can draw the heatmap
65
+
66
+
67
+ def missingness_matrix(df: pd.DataFrame) -> pd.DataFrame:
68
+ if not isinstance(df, pd.DataFrame):
69
+ raise TypeError("Expected a pandas DataFrame")
70
+ return df.isna()
@@ -0,0 +1,174 @@
1
+
2
+ """Metrics for evaluating missing-value imputation accuracy."""
3
+
4
+ import numpy as np
5
+ import pandas as pd
6
+ from sklearn.metrics import mean_absolute_error, mean_squared_error
7
+
8
+
9
+ def benchmark_imputation(reference_df, incomplete_df, imputed_datasets):
10
+ """Compare numerical and categorical imputation methods.
11
+
12
+ Numerical methods are evaluated using MAE and RMSE.
13
+ Mode is evaluated using categorical accuracy.
14
+
15
+ Only deliberately hidden cells are evaluated.
16
+ """
17
+
18
+ if not isinstance(reference_df, pd.DataFrame):
19
+ raise TypeError("reference_df must be a pandas DataFrame.")
20
+
21
+ if not isinstance(incomplete_df, pd.DataFrame):
22
+ raise TypeError("incomplete_df must be a pandas DataFrame.")
23
+
24
+ if not isinstance(imputed_datasets, dict) or not imputed_datasets:
25
+ raise ValueError("Provide at least one imputed dataset.")
26
+
27
+ if (
28
+ reference_df.empty
29
+ or not reference_df.columns.equals(incomplete_df.columns)
30
+ or not reference_df.index.equals(incomplete_df.index)
31
+ or not reference_df.columns.is_unique
32
+ ):
33
+ raise ValueError("Datasets must have matching rows and columns.")
34
+
35
+ if reference_df.isna().any().any():
36
+ raise ValueError("The reference dataset must be complete.")
37
+
38
+ if not incomplete_df.isna().any().any():
39
+ raise ValueError("The incomplete dataset must contain missing values.")
40
+
41
+ numeric_columns = [
42
+ column for column in reference_df.columns
43
+ if pd.api.types.is_numeric_dtype(reference_df[column])
44
+ and not pd.api.types.is_bool_dtype(reference_df[column])
45
+ and not pd.api.types.is_complex_dtype(reference_df[column])
46
+ ]
47
+
48
+ categorical_columns = [
49
+ column for column in reference_df.columns
50
+ if (
51
+ pd.api.types.is_object_dtype(reference_df[column])
52
+ or isinstance(reference_df[column].dtype, pd.CategoricalDtype)
53
+ or pd.api.types.is_string_dtype(reference_df[column])
54
+ or pd.api.types.is_bool_dtype(reference_df[column])
55
+ )
56
+ ]
57
+
58
+ numeric_mask = incomplete_df[numeric_columns].isna()
59
+ categorical_mask = incomplete_df[categorical_columns].isna()
60
+
61
+ # Check that the observed values have not been changed.
62
+ for column in reference_df.columns:
63
+ observed = incomplete_df[column].notna()
64
+
65
+ try:
66
+ pd.testing.assert_series_equal(
67
+ incomplete_df.loc[observed, column],
68
+ reference_df.loc[observed, column],
69
+ check_dtype=False,
70
+ check_exact=True,
71
+ check_categorical=False
72
+ )
73
+ except AssertionError as exc:
74
+ raise ValueError(
75
+ f"Observed values were changed in column: {column}"
76
+ ) from exc
77
+
78
+ if numeric_columns:
79
+ reference_numeric = reference_df[numeric_columns].astype(float)
80
+
81
+ if np.isinf(reference_numeric.to_numpy()).any():
82
+ raise ValueError("Reference values must not contain infinity.")
83
+
84
+ rows = []
85
+
86
+ for method_name, imputed_df in imputed_datasets.items():
87
+
88
+ if not isinstance(method_name, str) or not method_name.strip():
89
+ raise ValueError("Method names must be non-empty strings.")
90
+
91
+ if not isinstance(imputed_df, pd.DataFrame):
92
+ raise TypeError("Each imputed result must be a DataFrame.")
93
+
94
+ if (
95
+ not imputed_df.columns.equals(reference_df.columns)
96
+ or not imputed_df.index.equals(reference_df.index)
97
+ ):
98
+ raise ValueError("Imputed datasets must match the reference structure.")
99
+
100
+ if method_name.strip().lower() == "mode":
101
+
102
+ actual_mask = categorical_mask
103
+
104
+ if not actual_mask.any().any():
105
+ mae = np.nan
106
+ rmse = np.nan
107
+ accuracy = np.nan
108
+ categorical_count = 0
109
+
110
+ else:
111
+ predicted = imputed_df[categorical_columns]
112
+
113
+ if predicted.isna().to_numpy()[actual_mask.to_numpy()].any():
114
+ raise ValueError(
115
+ f"{method_name} did not fill every missing categorical value."
116
+ )
117
+
118
+ actual_values = reference_df[categorical_columns].to_numpy()[
119
+ actual_mask.to_numpy()
120
+ ]
121
+ predicted_values = predicted.to_numpy()[
122
+ actual_mask.to_numpy()
123
+ ]
124
+
125
+ accuracy = float(np.mean(actual_values == predicted_values))
126
+ mae = np.nan
127
+ rmse = np.nan
128
+ categorical_count = len(actual_values)
129
+
130
+ numeric_count = 0
131
+
132
+ else:
133
+ actual_mask = numeric_mask
134
+
135
+ if not actual_mask.any().any():
136
+ mae = np.nan
137
+ rmse = np.nan
138
+ numeric_count = 0
139
+
140
+ else:
141
+ predicted = imputed_df[numeric_columns].astype(float)
142
+
143
+ if predicted.isna().to_numpy()[actual_mask.to_numpy()].any():
144
+ raise ValueError(
145
+ f"{method_name} did not fill every missing numerical value."
146
+ )
147
+
148
+ if np.isinf(predicted.to_numpy()).any():
149
+ raise ValueError("Imputed values must not contain infinity.")
150
+
151
+ reference_numeric = reference_df[numeric_columns].astype(float)
152
+
153
+ actual = reference_numeric.to_numpy()[actual_mask.to_numpy()]
154
+ predicted_values = predicted.to_numpy()[actual_mask.to_numpy()]
155
+
156
+ mae = mean_absolute_error(actual, predicted_values)
157
+ rmse = np.sqrt(mean_squared_error(actual, predicted_values))
158
+ numeric_count = len(actual)
159
+
160
+ accuracy = np.nan
161
+ categorical_count = 0
162
+
163
+ rows.append({
164
+ "method": method_name,
165
+ "MAE": mae,
166
+ "RMSE": rmse,
167
+ "Accuracy": accuracy,
168
+ "evaluated_cells": numeric_count + categorical_count,
169
+ "evaluated_numeric_cells": numeric_count,
170
+ "evaluated_categorical_cells": categorical_count
171
+ })
172
+
173
+ return pd.DataFrame(rows)
174
+
@@ -0,0 +1,138 @@
1
+ """Compare analytical results before and after simulated missingness."""
2
+
3
+ import numpy as np
4
+ import pandas as pd
5
+ from scipy.stats import ks_2samp, pearsonr, spearmanr, linregress
6
+ from missinglab.core.imputation_workflow import impute_dataset
7
+ from missinglab.config import DEFAULT_RANDOM_STATE
8
+
9
+ ANALYSIS_TYPES = ("descriptive", "distribution", "correlation", "regression")
10
+ HANDLING_METHODS = ("complete_case", "mean", "median", "knn", "iterative")
11
+
12
+
13
+ def evaluate_analysis(reference_df, simulated_df, columns,
14
+ analysis="descriptive", handling="complete_case", *,
15
+ n_neighbors=5, max_iter=10):
16
+ """Return a tidy DataFrame of analytical comparisons.
17
+
18
+ Both inputs must contain the same sampled rows in the same order.
19
+ The reference must be complete; simulated observed values must match it.
20
+ Descriptive and distribution analyses use one numeric variable; correlation
21
+ and regression use two. Regression treats the first as x and second as y.
22
+ Complete-case deletion applies only to the selected analysis columns.
23
+ Mean/median imputation uses only observed simulated values, including y
24
+ if selected. Advanced methods use the numerical columns of the simulated
25
+ dataset, following the shared imputation workflow. Neither input is
26
+ modified. KS is a distance, not a p-value.
27
+ """
28
+ if not isinstance(reference_df, pd.DataFrame) or not isinstance(simulated_df, pd.DataFrame):
29
+ raise TypeError("Both datasets must be pandas DataFrames.")
30
+ if reference_df.empty or simulated_df.empty:
31
+ raise ValueError("Both datasets must be non-empty.")
32
+ if (not reference_df.columns.is_unique or not simulated_df.columns.is_unique
33
+ or not reference_df.columns.equals(simulated_df.columns)
34
+ or not reference_df.index.equals(simulated_df.index)):
35
+ raise ValueError("Datasets must have matching rows and unique columns in the same order.")
36
+ if reference_df.isna().any().any():
37
+ raise ValueError("The reference dataset must contain no missing values.")
38
+ # Compare only observed cells. Missing markers such as pd.NA and
39
+ # np.nan are equivalent for this check, regardless of column dtype.
40
+ for column in simulated_df.columns:
41
+ observed = simulated_df[column].notna().to_numpy()
42
+ try:
43
+ pd.testing.assert_series_equal(
44
+ simulated_df[column].iloc[observed],
45
+ reference_df[column].iloc[observed],
46
+ check_dtype=False, check_exact=True, check_categorical=False)
47
+ except AssertionError as exc:
48
+ raise ValueError(
49
+ f"Observed simulated values must match the reference (column: {column})."
50
+ ) from exc
51
+ if analysis not in ANALYSIS_TYPES:
52
+ raise ValueError("Unknown analysis type.")
53
+ if handling not in HANDLING_METHODS:
54
+ raise ValueError("Unknown missing-data handling method.")
55
+ if not isinstance(columns, (list, tuple)):
56
+ raise TypeError("Columns must be a list or tuple of column names.")
57
+ required = 1 if analysis in ("descriptive", "distribution") else 2
58
+ if len(columns) != required or len(set(columns)) != required:
59
+ raise ValueError(f"This analysis requires {required} distinct column(s).")
60
+ for column in columns:
61
+ if column not in reference_df.columns:
62
+ raise ValueError(f"Unknown column: {column}")
63
+ if (not pd.api.types.is_numeric_dtype(reference_df[column])
64
+ or pd.api.types.is_bool_dtype(reference_df[column])
65
+ or pd.api.types.is_complex_dtype(reference_df[column])):
66
+ raise ValueError(f"Column {column} must be real numerical data.")
67
+
68
+ reference = reference_df[list(columns)].astype(float).copy()
69
+ simulated = simulated_df[list(columns)].astype(float).copy()
70
+ if np.isinf(reference.to_numpy()).any() or np.isinf(simulated.to_numpy()).any():
71
+ raise ValueError("Selected columns must not contain infinite values.")
72
+ missing_cells = int(simulated.isna().sum().sum())
73
+ observed_rows = int(simulated.dropna().shape[0])
74
+ if handling == "complete_case":
75
+ handled = simulated.dropna()
76
+ else:
77
+ if simulated.isna().all().any():
78
+ raise ValueError("Cannot impute a selected column with no observed values.")
79
+ if handling in ("knn", "iterative"):
80
+ # Fit on the simulated data only, never on hidden reference values.
81
+ method = "KNN" if handling == "knn" else "Iterative"
82
+ completed = impute_dataset(simulated_df, method,
83
+ n_neighbors=n_neighbors, max_iter=max_iter)
84
+ handled = completed[list(columns)].astype(float)
85
+ if handled.isna().any().any():
86
+ raise ValueError("Selected variables still contain missing values after imputation.")
87
+ else:
88
+ fills = simulated.mean() if handling == "mean" else simulated.median()
89
+ handled = simulated.fillna(fills)
90
+
91
+ minimum = {"descriptive": 2, "distribution": 1,
92
+ "correlation": 3, "regression": 3}[analysis]
93
+ if len(reference) < minimum or len(handled) < minimum:
94
+ raise ValueError(f"This analysis requires at least {minimum} usable rows in both datasets.")
95
+
96
+ def calculate(data):
97
+ x = data[columns[0]]
98
+ if analysis == "descriptive":
99
+ return {"Mean": x.mean(), "Median": x.median(), "Variance": x.var(ddof=1)}
100
+ y = data[columns[1]]
101
+ if x.nunique() < 2 or y.nunique() < 2:
102
+ raise ValueError("Correlation and regression require nonconstant selected variables in both datasets.")
103
+ if analysis == "correlation":
104
+ return {"Pearson r": pearsonr(x, y)[0], "Spearman rho": spearmanr(x, y)[0]}
105
+ fit = linregress(x, y)
106
+ return {"Slope": fit.slope, "Intercept": fit.intercept, "R-squared": fit.rvalue ** 2}
107
+
108
+ if analysis == "distribution":
109
+ # The reference compared to itself has zero distance by definition.
110
+ before = {"KS distance": 0.0}
111
+ after = {"KS distance": ks_2samp(reference[columns[0]], handled[columns[0]]).statistic}
112
+ else:
113
+ before, after = calculate(reference), calculate(handled)
114
+
115
+ rows = []
116
+ for metric, value in before.items():
117
+ result = after[metric]
118
+ if not np.isfinite([value, result]).all():
119
+ raise ValueError(f"Metric {metric} is not finite for the selected data.")
120
+ rows.append({
121
+ "analysis": analysis, "variables": ", ".join(map(str, columns)),
122
+ "handling": handling, "metric": metric,
123
+ "reference": float(value), "simulated": float(result),
124
+ "signed_difference": float(result - value),
125
+ "absolute_difference": float(abs(result - value)),
126
+ "reference_rows": len(reference), "simulated_rows": len(simulated),
127
+ "observed_complete_rows": observed_rows, "rows_used": len(handled),
128
+ "missing_cells": missing_cells,
129
+ "imputed_cells": missing_cells if handling != "complete_case" else 0,
130
+ })
131
+ results = pd.DataFrame(rows)
132
+ # Preserve the original schema for the existing handling methods.
133
+ if handling == "knn":
134
+ results["n_neighbors"] = n_neighbors
135
+ elif handling == "iterative":
136
+ results["max_iter"] = max_iter
137
+ results["imputation_random_state"] = DEFAULT_RANDOM_STATE
138
+ return results
@@ -0,0 +1,176 @@
1
+
2
+ """Missing-data imputation methods for MissingLab."""
3
+ from missinglab.config import DEFAULT_RANDOM_STATE
4
+ import numpy as np
5
+ import pandas as pd
6
+ from sklearn.impute import KNNImputer
7
+ from sklearn.experimental import enable_iterative_imputer # noqa: F401
8
+ from sklearn.impute import IterativeImputer
9
+
10
+ # the following function uses KNN to estimate numerical values
11
+ #and it chooses the neighbors number
12
+ # it preserves categorical variables without changing them and
13
+ # it doesn't modify the original dataset
14
+
15
+ def knn_imputation(df, n_neighbors=5, weights="uniform"):
16
+ """Fill missing numerical values using K-nearest neighbors.
17
+
18
+ Categorical columns are preserved without modification.
19
+ Columns containing only missing values are left unchanged.
20
+ The original DataFrame is never modified.
21
+ """
22
+ if not isinstance(df, pd.DataFrame):
23
+ raise TypeError("Expected a pandas DataFrame.")
24
+
25
+ if df.empty:
26
+ raise ValueError("The dataset must not be empty.")
27
+
28
+ if not isinstance(n_neighbors, int) or isinstance(n_neighbors, bool):
29
+ raise ValueError("n_neighbors must be a positive integer.")
30
+
31
+ if n_neighbors < 1:
32
+ raise ValueError("n_neighbors must be a positive integer.")
33
+
34
+ if weights not in ("uniform", "distance"):
35
+ raise ValueError("weights must be 'uniform' or 'distance'.")
36
+
37
+ result = df.copy(deep=True)
38
+
39
+ # Select numerical columns, excluding Boolean columns.
40
+ # Select numerical columns, excluding Boolean columns.
41
+ numeric_columns = [
42
+ column for column in df.columns
43
+ if pd.api.types.is_numeric_dtype(df[column])
44
+ and not pd.api.types.is_bool_dtype(df[column])
45
+ ]
46
+
47
+ # Check all numerical columns for infinite values.
48
+ if numeric_columns:
49
+ numeric_values = df[numeric_columns].to_numpy(dtype=float)
50
+
51
+ if np.isinf(numeric_values).any():
52
+ raise ValueError(
53
+ "Numerical columns must not contain infinite values."
54
+ )
55
+ # Keep only columns that contain missing values
56
+ # and have at least one observed value.
57
+ columns_to_impute = [
58
+ column for column in numeric_columns
59
+ if df[column].isna().any() and df[column].notna().any()
60
+ ]
61
+
62
+ if not columns_to_impute:
63
+ return result
64
+
65
+ numeric_data = df[columns_to_impute].astype(float)
66
+
67
+ imputer = KNNImputer(
68
+ n_neighbors=n_neighbors,
69
+ weights=weights
70
+ )
71
+
72
+ imputed_data = imputer.fit_transform(numeric_data)
73
+
74
+ result.loc[:, columns_to_impute] = imputed_data
75
+
76
+ return result
77
+
78
+ #the new function below now will
79
+ #- impute the numerical columns only
80
+ # - put other numerical columns as predictors
81
+ #- preserve the categorical variables
82
+ # leave the entire empty column unchanges
83
+ #keep the original dataframe unchanged
84
+ #reject invalid parameters and infinite numerical values
85
+
86
+ def iterative_imputation(
87
+ df,
88
+ max_iter=10,
89
+ tol=0.001,
90
+ initial_strategy="mean",
91
+ random_state=DEFAULT_RANDOM_STATE
92
+ ):
93
+ """Fill missing numerical values using iterative imputation."""
94
+
95
+ if not isinstance(df, pd.DataFrame):
96
+ raise TypeError("Expected a pandas DataFrame.")
97
+
98
+ if df.empty:
99
+ raise ValueError("The dataset must not be empty.")
100
+
101
+ if (
102
+ not isinstance(max_iter, int)
103
+ or isinstance(max_iter, bool)
104
+ or max_iter < 1
105
+ ):
106
+ raise ValueError("max_iter must be a positive integer.")
107
+
108
+ if (
109
+ not isinstance(tol, (int, float))
110
+ or isinstance(tol, bool)
111
+ or not np.isfinite(tol)
112
+ or tol <= 0
113
+ ):
114
+ raise ValueError("tol must be a positive finite number.")
115
+
116
+ allowed_strategies = ["mean", "median", "most_frequent"]
117
+
118
+ if initial_strategy not in allowed_strategies:
119
+ raise ValueError(
120
+ "initial_strategy must be mean, median, or most_frequent."
121
+ )
122
+
123
+ result = df.copy(deep=True)
124
+
125
+ # Select numerical columns, excluding Boolean columns.
126
+ numeric_columns = [
127
+ column for column in df.columns
128
+ if pd.api.types.is_numeric_dtype(df[column])
129
+ and not pd.api.types.is_bool_dtype(df[column])
130
+ ]
131
+
132
+ # Check all numerical columns for infinite values.
133
+ if numeric_columns:
134
+ numeric_values = df[numeric_columns].to_numpy(dtype=float)
135
+
136
+ if np.isinf(numeric_values).any():
137
+ raise ValueError(
138
+ "Numerical columns must not contain infinite values."
139
+ )
140
+
141
+ # Keep columns that contain at least one observed value.
142
+ usable_columns = [
143
+ column for column in numeric_columns
144
+ if df[column].notna().any()
145
+ ]
146
+
147
+ # Identify numerical columns that need imputation.
148
+ columns_to_impute = [
149
+ column for column in usable_columns
150
+ if df[column].isna().any()
151
+ ]
152
+
153
+ if not columns_to_impute:
154
+ return result
155
+
156
+ numeric_data = df[usable_columns].astype(float)
157
+
158
+ imputer = IterativeImputer(
159
+ max_iter=max_iter,
160
+ tol=tol,
161
+ initial_strategy=initial_strategy,
162
+ random_state=random_state
163
+ )
164
+
165
+ imputed_data = imputer.fit_transform(numeric_data)
166
+
167
+ imputed_df = pd.DataFrame(
168
+ imputed_data,
169
+ columns=usable_columns,
170
+ index=df.index
171
+ )
172
+
173
+ # Update only columns that originally had missing values.
174
+ result.loc[:, columns_to_impute] = imputed_df[columns_to_impute]
175
+
176
+ return result