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/gui/app.py ADDED
@@ -0,0 +1,2595 @@
1
+ """CustomTkinter desktop user interface for MissingLab v0.1.0."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from concurrent.futures import ThreadPoolExecutor
6
+ from pathlib import Path
7
+ import tkinter as tk
8
+ from tkinter import filedialog, messagebox, ttk
9
+ from missinglab.config import DEFAULT_RANDOM_STATE
10
+ import customtkinter as ctk
11
+ import pandas as pd
12
+ from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
13
+ from matplotlib.figure import Figure
14
+
15
+ from missinglab.core.analyzer import (
16
+ column_missingness,
17
+ summarize_dataset,
18
+ missingness_matrix,
19
+ )
20
+ from missinglab.core.mcar import run_mcar_test
21
+ from missinglab.core.evaluation import evaluate_analysis
22
+ from missinglab.core.patterns import (
23
+ simulate_missingness,
24
+ simulate_missingness_by_employment,
25
+ simulate_missingness_conditional,
26
+ compare_missingness_patterns,
27
+ )
28
+ from missinglab.io.loader import load_csv
29
+ from missinglab.core.session_report import build_session_report, export_session_report
30
+ from missinglab.core.imputation_workflow import (
31
+ METHODS, impute_dataset, compare_imputation_methods, export_cleaned_csv,
32
+ )
33
+
34
+
35
+ class MissingLabApp(ctk.CTk):
36
+
37
+ def __init__(self) -> None:
38
+ super().__init__()
39
+
40
+ ctk.set_appearance_mode("light")
41
+ ctk.set_default_color_theme("dark-blue")
42
+
43
+ # Keep table selection consistent with the application accent.
44
+ ttk.Style(self).map("Treeview", background=[("selected", "#A63871")],
45
+ foreground=[("selected", "#FFFFFF")])
46
+
47
+ self.title("MissingLab — Data Quality Studio")
48
+ self.geometry("1360x900")
49
+ self.minsize(1050, 720)
50
+
51
+ self._pool = ThreadPoolExecutor(max_workers=1)
52
+ self._active_future = None
53
+ self._mcar_future = None
54
+ self._simulation_future = None
55
+ self._evaluation_future = None
56
+ self._imputation_future = None
57
+ self._closing = False
58
+
59
+ self.current_df = None
60
+ self.current_matrix = None
61
+ self.simulation_comparison = None
62
+ self.reference_df = None
63
+ self.simulated_df = None
64
+ self.last_simulation_method = None
65
+ self.evaluation_results = None
66
+ self.source_path = None
67
+ self.cleaned_df = None
68
+ self.imputation_config = None
69
+ self.benchmark_results = None
70
+ self.benchmark_config = None
71
+ self.mcar_results = None
72
+ self.simulation_config = None
73
+ self.evaluation_config = None
74
+
75
+ self.protocol("WM_DELETE_WINDOW", self._close)
76
+
77
+ self._build_ui()
78
+
79
+ # ---------------------------------------------------------
80
+ # MAIN INTERFACE
81
+ # ---------------------------------------------------------
82
+
83
+
84
+ def _build_ui(self) -> None:
85
+ """Build the interactive MissingLab analytics workspace."""
86
+
87
+ # One consistent visual system for the entire application.
88
+ self.colors = {
89
+ "bg": "#F7F1F4",
90
+ "white": "#FFFCFD",
91
+ "pink": "#C45A83",
92
+ "pink_dark": "#702847",
93
+ "pink_light": "#F8E8EF",
94
+ "pink_hover": "#EBC6D5",
95
+ "sidebar": "#241521",
96
+ "sidebar_hover": "#42283B",
97
+ "sidebar_active": "#F4DCE7",
98
+ "text": "#30232D",
99
+ "muted": "#8A7884",
100
+ "border": "#EADCE3",
101
+ "input": "#FFF9FC",
102
+ "green": "#32866B",
103
+ "orange": "#C17A3A",
104
+ "red": "#B94C5C",
105
+ "lavender": "#F0E4EB",
106
+ "ink": "#241521",
107
+ "soft_ink": "#655260",
108
+ "sidebar_text": "#F8EDF3",
109
+ "peach": "#F3B58E",
110
+ "plum": "#45253D",
111
+ }
112
+
113
+ self.configure(fg_color=self.colors["bg"])
114
+
115
+ # ---------------- HEADER ----------------
116
+
117
+ header = ctk.CTkFrame(
118
+ self,
119
+ height=72,
120
+ corner_radius=0,
121
+ fg_color="#F8D7E8"
122
+ )
123
+ header.pack(fill="x")
124
+ header.pack_propagate(False)
125
+
126
+ brand = ctk.CTkFrame(
127
+ header,
128
+ fg_color="transparent"
129
+ )
130
+ brand.pack(side="left", padx=25)
131
+
132
+ ctk.CTkLabel(
133
+ brand,
134
+ text="MissingLab",
135
+ font=ctk.CTkFont(size=26, weight="bold"),
136
+ text_color=self.colors["pink_dark"]
137
+ ).pack(anchor="w")
138
+
139
+ ctk.CTkLabel(
140
+ brand,
141
+ text="DATA QUALITY STUDIO / ANALYTICS WORKSPACE",
142
+ font=ctk.CTkFont(size=9, weight="bold"),
143
+ text_color=self.colors["muted"]
144
+ ).pack(anchor="w")
145
+
146
+ self.import_button = ctk.CTkButton(
147
+ header,
148
+ text="+ Import dataset",
149
+ width=155,
150
+ height=38,
151
+ corner_radius=10,
152
+ fg_color=self.colors["pink"],
153
+ hover_color=self.colors["pink_dark"],
154
+ font=ctk.CTkFont(size=12, weight="bold"),
155
+ command=self._choose_file
156
+ )
157
+ self.import_button.pack(side="right", padx=24, pady=16)
158
+
159
+ # ---------------- MAIN LAYOUT ----------------
160
+
161
+ main = ctk.CTkFrame(
162
+ self,
163
+ fg_color="transparent",
164
+ corner_radius=0
165
+ )
166
+ main.pack(fill="both", expand=True)
167
+
168
+ # ---------------- SIDEBAR ----------------
169
+
170
+ sidebar = ctk.CTkFrame(
171
+ main,
172
+ width=215,
173
+ corner_radius=0,
174
+ fg_color=self.colors["sidebar"]
175
+ )
176
+ sidebar.pack(side="left", fill="y")
177
+ sidebar.pack_propagate(False)
178
+
179
+ ctk.CTkLabel(
180
+ sidebar,
181
+ text="WORKSPACE",
182
+ font=ctk.CTkFont(size=10, weight="bold"),
183
+ text_color="#E6B9CE"
184
+ ).pack(anchor="w", padx=22, pady=(28, 12))
185
+
186
+ self.pages = {}
187
+ self.nav_buttons = {}
188
+
189
+ navigation = [
190
+ ("Overview", "⌂", "Dashboard"),
191
+ ("Diagnostics", "◉", "Diagnostics"),
192
+ ("Simulation", "⇄", "Simulation"),
193
+ ("Evaluation", "▤", "Evaluation"),
194
+ ("Imputation", "✦", "Imputation"),
195
+ ("Reports", "▧", "Reports"),
196
+ ]
197
+
198
+ # ---------------- CONTENT AREA ----------------
199
+
200
+ content = ctk.CTkFrame(
201
+ main,
202
+ fg_color=self.colors["bg"],
203
+ corner_radius=0
204
+ )
205
+ content.pack(side="left", fill="both", expand=True)
206
+
207
+ self.source_label = ctk.CTkLabel(
208
+ content,
209
+ text="● No dataset loaded",
210
+ anchor="w",
211
+ font=ctk.CTkFont(size=11, weight="bold"),
212
+ text_color=self.colors["muted"],
213
+ fg_color=self.colors["white"],
214
+ corner_radius=9,
215
+ height=35
216
+ )
217
+ self.source_label.pack(
218
+ fill="x",
219
+ padx=22,
220
+ pady=(16, 8)
221
+ )
222
+
223
+ # ---------------- PAGE CONTAINERS ----------------
224
+
225
+ for page_name, icon, label in navigation:
226
+
227
+ page = ctk.CTkScrollableFrame(
228
+ content,
229
+ fg_color="transparent",
230
+ corner_radius=0
231
+ )
232
+
233
+ self.pages[page_name] = page
234
+
235
+ if page_name != "Overview":
236
+ page_intro = ctk.CTkFrame(
237
+ page, fg_color=self.colors["white"], corner_radius=18,
238
+ border_width=1, border_color=self.colors["border"]
239
+ )
240
+ page_intro.pack(fill="x", padx=8, pady=(12, 12))
241
+ ctk.CTkLabel(
242
+ page_intro, text=label,
243
+ font=ctk.CTkFont(size=25, weight="bold"),
244
+ text_color=self.colors["ink"]
245
+ ).pack(anchor="w", padx=22, pady=(16, 2))
246
+ ctk.CTkLabel(
247
+ page_intro,
248
+ text={
249
+ "Diagnostics": "Inspect missing-data assumptions and understand the structure of missingness.",
250
+ "Simulation": "Create controlled missingness scenarios and compare them with your source data.",
251
+ "Evaluation": "Measure how missing-data handling changes downstream analysis.",
252
+ "Imputation": "Fill missing values, compare methods, and export a cleaned dataset.",
253
+ "Reports": "Package your completed analysis settings and results into a session report.",
254
+ }.get(page_name, "Your MissingLab workspace"),
255
+ font=ctk.CTkFont(size=12), text_color=self.colors["muted"]
256
+ ).pack(anchor="w", padx=22, pady=(0, 16))
257
+
258
+ nav_button = ctk.CTkButton(
259
+ sidebar,
260
+ text=f"{icon} {label}",
261
+ height=45,
262
+ corner_radius=9,
263
+ anchor="w",
264
+ fg_color="transparent",
265
+ hover_color=self.colors["sidebar_hover"],
266
+ text_color="#F8E8EF",
267
+ font=ctk.CTkFont(size=13),
268
+ command=lambda name=page_name: self._show_page(name)
269
+ )
270
+
271
+ nav_button.pack(
272
+ fill="x",
273
+ padx=11,
274
+ pady=3
275
+ )
276
+
277
+ self.nav_buttons[page_name] = nav_button
278
+
279
+ # Sidebar bottom information
280
+
281
+ sidebar_bottom = ctk.CTkFrame(
282
+ sidebar,
283
+ fg_color="#45253D",
284
+ corner_radius=10
285
+ )
286
+ sidebar_bottom.pack(
287
+ side="bottom",
288
+ fill="x",
289
+ padx=12,
290
+ pady=15
291
+ )
292
+
293
+ ctk.CTkLabel(
294
+ sidebar_bottom,
295
+ text="MISSINGLAB",
296
+ font=ctk.CTkFont(size=10, weight="bold"),
297
+ text_color="#F8D7E8"
298
+ ).pack(anchor="w", padx=12, pady=(10, 2))
299
+
300
+ ctk.CTkLabel(
301
+ sidebar_bottom,
302
+ text="Data analysis made clearer.",
303
+ font=ctk.CTkFont(size=10),
304
+ text_color="#E6B9CE"
305
+ ).pack(anchor="w", padx=12, pady=(0, 10))
306
+
307
+ # ---------------- OVERVIEW ----------------
308
+
309
+ overview = self.pages["Overview"]
310
+
311
+ ctk.CTkLabel(
312
+ overview,
313
+ text="Your data quality studio",
314
+ font=ctk.CTkFont(size=30, weight="bold"),
315
+ text_color=self.colors["ink"]
316
+ ).pack(anchor="w", padx=8, pady=(12, 2))
317
+
318
+ ctk.CTkLabel(
319
+ overview,
320
+ text="Understand missing values. Test scenarios. Build cleaner datasets.",
321
+ font=ctk.CTkFont(size=13),
322
+ text_color=self.colors["muted"]
323
+ ).pack(anchor="w", padx=8, pady=(0, 17))
324
+
325
+ # KPI cards
326
+
327
+ self.metrics = {}
328
+
329
+ metrics_container = ctk.CTkFrame(
330
+ overview,
331
+ fg_color="transparent"
332
+ )
333
+ metrics_container.pack(fill="x", padx=3, pady=4)
334
+
335
+ metric_data = [
336
+ ("rows", "TOTAL ROWS", "▤"),
337
+ ("columns", "VARIABLES", "▥"),
338
+ ("missing", "MISSING CELLS", "◌"),
339
+ ("percent", "MISSING RATE", "%"),
340
+ ]
341
+
342
+ for key, title, symbol in metric_data:
343
+
344
+ card = ctk.CTkFrame(
345
+ metrics_container,
346
+ fg_color=self.colors["white"],
347
+ corner_radius=13,
348
+ border_width=1,
349
+ border_color=self.colors["border"]
350
+ )
351
+
352
+ card.pack(
353
+ side="left",
354
+ fill="both",
355
+ expand=True,
356
+ padx=5
357
+ )
358
+
359
+ ctk.CTkLabel(
360
+ card,
361
+ text=symbol,
362
+ font=ctk.CTkFont(size=19, weight="bold"),
363
+ text_color=self.colors["pink"]
364
+ ).pack(anchor="w", padx=15, pady=(12, 0))
365
+
366
+ ctk.CTkLabel(
367
+ card,
368
+ text=title,
369
+ font=ctk.CTkFont(size=9, weight="bold"),
370
+ text_color=self.colors["muted"]
371
+ ).pack(anchor="w", padx=15, pady=(5, 1))
372
+
373
+ value = ctk.CTkLabel(
374
+ card,
375
+ text="—",
376
+ font=ctk.CTkFont(size=25, weight="bold"),
377
+ text_color=self.colors["text"]
378
+ )
379
+ value.pack(anchor="w", padx=15, pady=(0, 13))
380
+
381
+ self.metrics[key] = value
382
+
383
+ # Quick actions
384
+
385
+ ctk.CTkLabel(
386
+ overview,
387
+ text="Quick actions",
388
+ font=ctk.CTkFont(size=18, weight="bold"),
389
+ text_color=self.colors["text"]
390
+ ).pack(anchor="w", padx=8, pady=(22, 9))
391
+
392
+ quick_actions = ctk.CTkFrame(
393
+ overview,
394
+ fg_color="transparent"
395
+ )
396
+ quick_actions.pack(fill="x", padx=3)
397
+
398
+ action_data = [
399
+ ("Diagnostics", "Run MCAR test", "Check missingness assumptions"),
400
+ ("Simulation", "Simulate missingness", "Reproduce missing-value patterns"),
401
+ ("Evaluation", "Evaluate analysis", "Compare analytical results"),
402
+ ("Imputation", "Impute missing values", "Apply numerical imputation"),
403
+ ]
404
+
405
+ for page_name, title, description in action_data:
406
+
407
+ action_card = ctk.CTkFrame(
408
+ quick_actions,
409
+ fg_color=self.colors["white"],
410
+ corner_radius=12,
411
+ border_width=1,
412
+ border_color=self.colors["border"]
413
+ )
414
+
415
+ action_card.pack(
416
+ side="left",
417
+ expand=True,
418
+ fill="both",
419
+ padx=5,
420
+ pady=4
421
+ )
422
+
423
+ ctk.CTkLabel(
424
+ action_card,
425
+ text=title,
426
+ font=ctk.CTkFont(size=12, weight="bold"),
427
+ text_color=self.colors["text"]
428
+ ).pack(anchor="w", padx=12, pady=(13, 3))
429
+
430
+ ctk.CTkLabel(
431
+ action_card,
432
+ text=description,
433
+ font=ctk.CTkFont(size=10),
434
+ text_color=self.colors["muted"],
435
+ wraplength=145,
436
+ justify="left"
437
+ ).pack(anchor="w", padx=12, pady=(0, 9))
438
+
439
+ ctk.CTkButton(
440
+ action_card,
441
+ text="Open workspace →",
442
+ height=30,
443
+ corner_radius=7,
444
+ fg_color=self.colors["pink_light"],
445
+ hover_color="#F4DCE7",
446
+ text_color=self.colors["pink_dark"],
447
+ font=ctk.CTkFont(size=10, weight="bold"),
448
+ command=lambda name=page_name: self._show_page(name)
449
+ ).pack(fill="x", padx=10, pady=(0, 11))
450
+
451
+ # ---------------- ANALYTICS CHART ----------------
452
+
453
+ chart_card = ctk.CTkFrame(
454
+ overview,
455
+ fg_color=self.colors["white"],
456
+ corner_radius=13,
457
+ border_width=1,
458
+ border_color=self.colors["border"]
459
+ )
460
+ chart_card.pack(fill="x", padx=8, pady=(18, 10))
461
+
462
+ ctk.CTkLabel(
463
+ chart_card,
464
+ text="Missingness distribution",
465
+ font=ctk.CTkFont(size=16, weight="bold"),
466
+ text_color=self.colors["text"]
467
+ ).pack(anchor="w", padx=15, pady=(13, 3))
468
+
469
+ ctk.CTkLabel(
470
+ chart_card,
471
+ text="A column-level overview of missing values in your dataset.",
472
+ font=ctk.CTkFont(size=10),
473
+ text_color=self.colors["muted"]
474
+ ).pack(anchor="w", padx=15, pady=(0, 6))
475
+
476
+ self.plot_frame = ctk.CTkFrame(
477
+ chart_card,
478
+ height=250,
479
+ fg_color=self.colors["white"]
480
+ )
481
+ self.plot_frame.pack(fill="x", padx=10, pady=5)
482
+ self.plot_frame.pack_propagate(False)
483
+
484
+ self.placeholder = ctk.CTkLabel(
485
+ self.plot_frame,
486
+ text="Import a CSV dataset to visualize missingness.",
487
+ text_color=self.colors["muted"]
488
+ )
489
+ self.placeholder.pack(expand=True)
490
+
491
+ self.canvas = None
492
+
493
+ # ---------------- HEATMAP ----------------
494
+
495
+ self.heatmap_frame = ctk.CTkFrame(
496
+ overview,
497
+ fg_color=self.colors["white"],
498
+ corner_radius=13,
499
+ border_width=1,
500
+ border_color=self.colors["border"]
501
+ )
502
+ self.heatmap_frame.pack(fill="x", padx=8, pady=9)
503
+
504
+ self.heatmap_title = ctk.CTkLabel(
505
+ self.heatmap_frame,
506
+ text="Missingness heatmap",
507
+ font=ctk.CTkFont(size=16, weight="bold"),
508
+ text_color=self.colors["text"]
509
+ )
510
+ self.heatmap_title.pack(anchor="w", padx=15, pady=(13, 5))
511
+
512
+ self.heatmap_option = ctk.CTkSegmentedButton(
513
+ self.heatmap_frame,
514
+ values=["First 50 rows", "All rows"],
515
+ command=self._update_heatmap_view,
516
+ selected_color=self.colors["pink"],
517
+ selected_hover_color=self.colors["pink_dark"]
518
+ )
519
+ self.heatmap_option.set("First 50 rows")
520
+ self.heatmap_option.pack(anchor="w", padx=15, pady=7)
521
+
522
+ self.heatmap_canvas = None
523
+
524
+ self.heatmap_label = ctk.CTkLabel(
525
+ self.heatmap_frame,
526
+ text="Import a dataset to display the heatmap.",
527
+ text_color=self.colors["muted"]
528
+ )
529
+ self.heatmap_label.pack(pady=12)
530
+
531
+ # ---------------- COLUMN SUMMARY ----------------
532
+
533
+ table_card = ctk.CTkFrame(
534
+ overview,
535
+ fg_color=self.colors["white"],
536
+ corner_radius=16,
537
+ border_width=1,
538
+ border_color=self.colors["border"]
539
+ )
540
+ table_card.pack(fill="x", padx=8, pady=10)
541
+
542
+ summary_header = ctk.CTkFrame(
543
+ table_card,
544
+ fg_color="transparent"
545
+ )
546
+ summary_header.pack(fill="x", padx=18, pady=(16, 3))
547
+
548
+ ctk.CTkLabel(
549
+ summary_header,
550
+ text="Column summary",
551
+ font=ctk.CTkFont(size=18, weight="bold"),
552
+ text_color="#30232D"
553
+ ).pack(side="left")
554
+
555
+ self.column_count_label = ctk.CTkLabel(
556
+ summary_header,
557
+ text="Waiting for dataset",
558
+ font=ctk.CTkFont(size=11, weight="bold"),
559
+ text_color="#702847",
560
+ fg_color="#F8E8EF",
561
+ corner_radius=8
562
+ )
563
+ self.column_count_label.pack(side="right", padx=2, pady=2)
564
+
565
+ ctk.CTkLabel(
566
+ table_card,
567
+ text="A detailed overview of missing and available values in each variable.",
568
+ font=ctk.CTkFont(size=11),
569
+ text_color="#78606E"
570
+ ).pack(anchor="w", padx=18, pady=(0, 12))
571
+
572
+ self.column_summary_frame = ctk.CTkScrollableFrame(
573
+ table_card,
574
+ fg_color="transparent",
575
+ height=270,
576
+ corner_radius=10
577
+ )
578
+ self.column_summary_frame.pack(
579
+ fill="x",
580
+ padx=12,
581
+ pady=(0, 12)
582
+ )
583
+
584
+ self.column_summary_frame.grid_columnconfigure(0, weight=1)
585
+ self.column_summary_frame.grid_columnconfigure(1, weight=1)
586
+
587
+ self.column_summary_placeholder = ctk.CTkLabel(
588
+ self.column_summary_frame,
589
+ text="Import a dataset to see the column summary.",
590
+ font=ctk.CTkFont(size=12),
591
+ text_color="#78606E"
592
+ )
593
+ self.column_summary_placeholder.grid(
594
+ row=0,
595
+ column=0,
596
+ columnspan=2,
597
+ pady=35
598
+ )
599
+
600
+ # ---------------- EXISTING WORKFLOWS ----------------
601
+ # These are your original feature builders and callbacks.
602
+ # Their calculations and functionality are not rewritten.
603
+
604
+ self._build_mcar_section(self.pages["Diagnostics"])
605
+ self._build_simulation_section(self.pages["Simulation"])
606
+ self._build_evaluation_section(self.pages["Evaluation"])
607
+ self._build_imputation_section(self.pages["Imputation"])
608
+ self._build_session_section(self.pages["Reports"])
609
+
610
+ # Apply the same button, input, dropdown, and table styling everywhere.
611
+ self._apply_visual_theme(self)
612
+
613
+ # ---------------- STATUS BAR ----------------
614
+
615
+ self.status_label = ctk.CTkLabel(
616
+ content,
617
+ text="● Ready | Import a CSV dataset to begin.",
618
+ anchor="w",
619
+ height=30,
620
+ font=ctk.CTkFont(size=10),
621
+ text_color=self.colors["muted"]
622
+ )
623
+ self.status_label.pack(fill="x", padx=22, pady=(0, 5))
624
+
625
+ self._show_page("Overview")
626
+
627
+ def _apply_visual_theme(self, parent) -> None:
628
+ """Apply a consistent, semantic visual system to all nested controls."""
629
+ for widget in parent.winfo_children():
630
+ kind = type(widget).__name__
631
+ try:
632
+ if kind in ("CTkFrame", "CTkScrollableFrame"):
633
+ # Preserve transparent layout containers; style actual panels.
634
+ current = str(widget.cget("fg_color"))
635
+ if current not in ("transparent", "none"):
636
+ widget.configure(
637
+ corner_radius=18,
638
+ border_width=1,
639
+ border_color=self.colors["border"],
640
+ )
641
+
642
+ elif kind == "CTkButton":
643
+ label = str(widget.cget("text")).strip().lower()
644
+
645
+ # Navigation is styled separately by _show_page.
646
+ is_nav = widget in self.nav_buttons.values()
647
+
648
+ is_danger = any(
649
+ token in label for token in ("delete", "remove", "reset")
650
+ )
651
+ is_primary = any(
652
+ token in label for token in (
653
+ "import", "run ", "start ", "impute",
654
+ "simulate", "evaluate", "generate report"
655
+ )
656
+ )
657
+ is_export = any(
658
+ token in label for token in (
659
+ "export", "download", "save report"
660
+ )
661
+ )
662
+ is_open = "open workspace" in label
663
+
664
+ common = {
665
+ "height": 42,
666
+ "corner_radius": 14,
667
+ "border_width": 1,
668
+ "font": ctk.CTkFont(
669
+ family="Segoe UI", size=12, weight="bold"
670
+ ),
671
+ "border_spacing": 10,
672
+ }
673
+
674
+ if is_nav:
675
+ widget.configure(
676
+ height=45,
677
+ corner_radius=13,
678
+ border_width=0,
679
+ fg_color="transparent",
680
+ hover_color=self.colors["sidebar_hover"],
681
+ text_color=self.colors["sidebar_text"],
682
+ font=ctk.CTkFont(
683
+ family="Segoe UI", size=13, weight="bold"
684
+ ),
685
+ anchor="w",
686
+ )
687
+ elif is_danger:
688
+ widget.configure(
689
+ **common,
690
+ fg_color="#F9E6E8",
691
+ hover_color="#F0C9CE",
692
+ border_color="#E9B8C0",
693
+ text_color=self.colors["red"],
694
+ )
695
+ elif is_primary and not is_export:
696
+ widget.configure(
697
+ **{**common, "height": 46, "corner_radius": 15},
698
+ fg_color="#A63871",
699
+ hover_color="#842957",
700
+ border_color="#A63871",
701
+ text_color="#FFFFFF",
702
+ text_color_disabled="#E8C6D7",
703
+ )
704
+ elif is_export:
705
+ widget.configure(
706
+ **common,
707
+ fg_color="#F8E8EF",
708
+ hover_color="#EBC6D5",
709
+ border_color="#D9A7BF",
710
+ text_color="#702847",
711
+ )
712
+ elif is_open:
713
+ widget.configure(
714
+ **{**common, "height": 38, "corner_radius": 12},
715
+ fg_color=self.colors["pink_light"],
716
+ hover_color=self.colors["pink_hover"],
717
+ border_color=self.colors["pink_light"],
718
+ text_color=self.colors["pink_dark"],
719
+ )
720
+ else:
721
+ widget.configure(
722
+ **common,
723
+ fg_color="#FFFFFF",
724
+ hover_color="#F4E7ED",
725
+ border_color="#E5D2DC",
726
+ text_color=self.colors["pink_dark"],
727
+ text_color_disabled="#B7A7B0",
728
+ )
729
+
730
+ elif kind == "CTkEntry":
731
+ widget.configure(
732
+ height=42,
733
+ corner_radius=12,
734
+ fg_color=self.colors["input"],
735
+ border_color="#DCC5D1",
736
+ border_width=1,
737
+ text_color=self.colors["text"],
738
+ placeholder_text_color="#A28E9A",
739
+ )
740
+
741
+ elif kind == "CTkOptionMenu":
742
+ widget.configure(
743
+ height=42,
744
+ corner_radius=12,
745
+ fg_color="#A63871",
746
+ button_color="#A63871",
747
+ button_hover_color=self.colors["pink_dark"],
748
+ dropdown_fg_color="#FFFCFD",
749
+ dropdown_hover_color=self.colors["pink_light"],
750
+ text_color="#FFFFFF",
751
+ font=ctk.CTkFont(family="Segoe UI", size=12, weight="bold"),
752
+ )
753
+
754
+ elif kind == "CTkComboBox":
755
+ widget.configure(
756
+ height=42,
757
+ corner_radius=12,
758
+ fg_color=self.colors["input"],
759
+ border_color="#DCC5D1",
760
+ button_color=self.colors["pink"],
761
+ button_hover_color=self.colors["pink_dark"],
762
+ dropdown_fg_color="#FFFCFD",
763
+ dropdown_hover_color=self.colors["pink_light"],
764
+ text_color=self.colors["text"],
765
+ )
766
+
767
+ elif kind == "CTkCheckBox":
768
+ widget.configure(
769
+ corner_radius=5,
770
+ border_color=self.colors["pink"],
771
+ fg_color=self.colors["pink_dark"],
772
+ hover_color=self.colors["pink"],
773
+ text_color=self.colors["text"],
774
+ )
775
+
776
+ elif kind == "CTkRadioButton":
777
+ widget.configure(
778
+ fg_color=self.colors["pink_dark"],
779
+ hover_color=self.colors["pink"],
780
+ text_color=self.colors["text"],
781
+ )
782
+
783
+ elif kind == "CTkSegmentedButton":
784
+ widget.configure(
785
+ corner_radius=12,
786
+ selected_color="#E3A8C4",
787
+ selected_hover_color="#D995B6",
788
+ unselected_color="#F3E8EE",
789
+ unselected_hover_color="#EAD2DE",
790
+ text_color=self.colors["text"],
791
+ )
792
+
793
+ elif kind == "CTkProgressBar":
794
+ widget.configure(
795
+ corner_radius=8,
796
+ fg_color="#F0E1E9",
797
+ progress_color=self.colors["pink"],
798
+ )
799
+
800
+ elif kind == "CTkSlider":
801
+ widget.configure(
802
+ progress_color=self.colors["pink"],
803
+ button_color=self.colors["pink_dark"],
804
+ button_hover_color=self.colors["pink"],
805
+ )
806
+
807
+ elif kind == "CTkSwitch":
808
+ widget.configure(
809
+ progress_color=self.colors["pink"],
810
+ button_color="#FFFFFF",
811
+ button_hover_color=self.colors["pink_light"],
812
+ )
813
+
814
+ elif kind == "CTkLabel":
815
+ try:
816
+ color = str(widget.cget("text_color"))
817
+ if color in ("gray", "#2B2B2B", "#000000"):
818
+ widget.configure(text_color=self.colors["text"])
819
+ except Exception:
820
+ pass
821
+
822
+ except (tk.TclError, TypeError, ValueError):
823
+ pass
824
+
825
+ # Do not restyle internal buttons of compound controls independently.
826
+ if kind not in ("CTkButton", "CTkOptionMenu", "CTkComboBox",
827
+ "CTkSegmentedButton", "CTkCheckBox", "CTkRadioButton",
828
+ "CTkSwitch", "CTkSlider", "CTkEntry", "CTkProgressBar") and widget.winfo_children():
829
+ self._apply_visual_theme(widget)
830
+
831
+ try:
832
+ style = ttk.Style(self)
833
+ style.theme_use("clam")
834
+ style.configure(
835
+ "Treeview",
836
+ background=self.colors["white"],
837
+ fieldbackground=self.colors["white"],
838
+ foreground=self.colors["text"],
839
+ rowheight=36,
840
+ borderwidth=0,
841
+ font=("Segoe UI", 10),
842
+ )
843
+ style.configure(
844
+ "Treeview.Heading",
845
+ background="#F3E5EC",
846
+ foreground=self.colors["pink_dark"],
847
+ font=("Segoe UI", 10, "bold"),
848
+ relief="flat",
849
+ padding=(11, 9),
850
+ )
851
+ style.map(
852
+ "Treeview",
853
+ background=[("selected", self.colors["pink_dark"])],
854
+ foreground=[("selected", "#FFFFFF")],
855
+ )
856
+ except tk.TclError:
857
+ pass
858
+
859
+ def _update_column_summary(self, columns) -> None:
860
+ """Refresh the overview cards showing missingness for each column."""
861
+
862
+ for widget in self.column_summary_frame.winfo_children():
863
+ widget.destroy()
864
+
865
+ total_columns = len(columns)
866
+ self.column_count_label.configure(
867
+ text=f"{total_columns} columns"
868
+ )
869
+
870
+ if total_columns == 0:
871
+ ctk.CTkLabel(
872
+ self.column_summary_frame,
873
+ text="No columns found.",
874
+ font=ctk.CTkFont(size=12),
875
+ text_color="#78606E"
876
+ ).grid(
877
+ row=0,
878
+ column=0,
879
+ columnspan=2,
880
+ pady=30
881
+ )
882
+ return
883
+
884
+ total_rows = len(self.current_df)
885
+
886
+ for index, item in enumerate(columns.itertuples(index=False)):
887
+ grid_row = index // 2
888
+ grid_column = index % 2
889
+
890
+ missing = int(item.missing_count)
891
+ percentage = float(item.missing_percent)
892
+ available = max(0, total_rows - missing)
893
+
894
+ if percentage == 0:
895
+ status_color = "#32866B"
896
+ status_text = "Complete"
897
+ elif percentage < 30:
898
+ status_color = "#C17A3A"
899
+ status_text = "Some missing"
900
+ else:
901
+ status_color = "#702847"
902
+ status_text = "High missingness"
903
+
904
+ card = ctk.CTkFrame(
905
+ self.column_summary_frame,
906
+ fg_color="#FFF8FB",
907
+ corner_radius=12,
908
+ border_width=1,
909
+ border_color="#EADCE3"
910
+ )
911
+ card.grid(
912
+ row=grid_row,
913
+ column=grid_column,
914
+ sticky="nsew",
915
+ padx=6,
916
+ pady=6
917
+ )
918
+
919
+ card_header = ctk.CTkFrame(
920
+ card,
921
+ fg_color="transparent"
922
+ )
923
+ card_header.pack(
924
+ fill="x",
925
+ padx=13,
926
+ pady=(12, 5)
927
+ )
928
+
929
+ ctk.CTkLabel(
930
+ card_header,
931
+ text=str(item.column),
932
+ font=ctk.CTkFont(size=13, weight="bold"),
933
+ text_color="#30232D",
934
+ anchor="w"
935
+ ).pack(side="left", fill="x", expand=True)
936
+
937
+ ctk.CTkLabel(
938
+ card_header,
939
+ text=str(item.dtype),
940
+ font=ctk.CTkFont(size=10),
941
+ text_color="#78606E",
942
+ fg_color="#F8E8EF",
943
+ corner_radius=6
944
+ ).pack(side="right", padx=(6, 0), pady=2)
945
+
946
+ percentage_row = ctk.CTkFrame(
947
+ card,
948
+ fg_color="transparent"
949
+ )
950
+ percentage_row.pack(
951
+ fill="x",
952
+ padx=13,
953
+ pady=(5, 2)
954
+ )
955
+
956
+ ctk.CTkLabel(
957
+ percentage_row,
958
+ text=f"{percentage:.2f}%",
959
+ font=ctk.CTkFont(size=23, weight="bold"),
960
+ text_color=status_color
961
+ ).pack(side="left")
962
+
963
+ ctk.CTkLabel(
964
+ percentage_row,
965
+ text=status_text,
966
+ font=ctk.CTkFont(size=10, weight="bold"),
967
+ text_color=status_color
968
+ ).pack(side="right")
969
+
970
+ progress = ctk.CTkProgressBar(
971
+ card,
972
+ height=7,
973
+ corner_radius=10,
974
+ fg_color="#F4DCE7",
975
+ progress_color=status_color
976
+ )
977
+ progress.pack(
978
+ fill="x",
979
+ padx=13,
980
+ pady=(5, 10)
981
+ )
982
+ progress.set(max(0.0, min(percentage, 100.0)) / 100.0)
983
+
984
+ stats = ctk.CTkFrame(
985
+ card,
986
+ fg_color="transparent"
987
+ )
988
+ stats.pack(
989
+ fill="x",
990
+ padx=13,
991
+ pady=(0, 12)
992
+ )
993
+
994
+ ctk.CTkLabel(
995
+ stats,
996
+ text=f"Missing: {missing:,}",
997
+ font=ctk.CTkFont(size=10),
998
+ text_color="#702847"
999
+ ).pack(side="left")
1000
+
1001
+ ctk.CTkLabel(
1002
+ stats,
1003
+ text=f"Available: {available:,}",
1004
+ font=ctk.CTkFont(size=10),
1005
+ text_color="#059669"
1006
+ ).pack(side="right")
1007
+
1008
+ def _show_page(self, page_name: str) -> None:
1009
+ """Switch pages and give navigation a clear active state."""
1010
+ for name, page in self.pages.items():
1011
+ page.pack_forget()
1012
+ self.pages[page_name].pack(fill="both", expand=True, padx=18, pady=(10, 8))
1013
+
1014
+ for name, button in self.nav_buttons.items():
1015
+ active = name == page_name
1016
+ button.configure(
1017
+ fg_color="#F4DCE7" if active else "transparent",
1018
+ text_color="#702847" if active else "#EADCE5",
1019
+ hover_color="#EBC6D5" if active else "#42283B",
1020
+ border_width=0,
1021
+ corner_radius=14,
1022
+ height=49,
1023
+ anchor="w",
1024
+ font=ctk.CTkFont(
1025
+ family="Segoe UI", size=13,
1026
+ weight="bold" if active else "normal"
1027
+ )
1028
+ )
1029
+
1030
+ # ---------------------------------------------------------
1031
+ # LITTLE'S MCAR TEST SECTION
1032
+ # ---------------------------------------------------------
1033
+
1034
+ def _build_mcar_section(self, container) -> None:
1035
+
1036
+ self.mcar_frame = ctk.CTkFrame(container)
1037
+ self.mcar_frame.pack(fill="x", pady=10)
1038
+
1039
+ ctk.CTkLabel(
1040
+ self.mcar_frame,
1041
+ text="Little's MCAR Test",
1042
+ font=ctk.CTkFont(size=18, weight="bold")
1043
+ ).pack(anchor="w", padx=12, pady=(12, 5))
1044
+
1045
+ self.mcar_button = ctk.CTkButton(
1046
+ self.mcar_frame,
1047
+ fg_color="#C45A83", hover_color="#A63871", text="Run Little's MCAR Test",
1048
+ command=self._run_mcar
1049
+ )
1050
+ self.mcar_button.pack(
1051
+ anchor="w",
1052
+ padx=12,
1053
+ pady=8
1054
+ )
1055
+
1056
+ self.mcar_result_label = ctk.CTkLabel(
1057
+ self.mcar_frame,
1058
+ text="Import a dataset to run the test.",
1059
+ anchor="w",
1060
+ justify="left"
1061
+ )
1062
+ self.mcar_result_label.pack(
1063
+ fill="x",
1064
+ padx=12,
1065
+ pady=(5, 12)
1066
+ )
1067
+
1068
+ # ---------------------------------------------------------
1069
+ # MISSINGNESS SIMULATION SECTION
1070
+ # ---------------------------------------------------------
1071
+
1072
+ def _build_simulation_section(self, container) -> None:
1073
+
1074
+ self.simulation_frame = ctk.CTkFrame(container)
1075
+ self.simulation_frame.pack(
1076
+ fill="x",
1077
+ pady=10
1078
+ )
1079
+
1080
+ ctk.CTkLabel(
1081
+ self.simulation_frame,
1082
+ text="Missingness Simulation",
1083
+ font=ctk.CTkFont(size=18, weight="bold")
1084
+ ).pack(
1085
+ anchor="w",
1086
+ padx=12,
1087
+ pady=(12, 5)
1088
+ )
1089
+
1090
+ ctk.CTkLabel(
1091
+ self.simulation_frame,
1092
+ text=(
1093
+ "Generate missing values on complete rows and compare "
1094
+ "the simulated data with the original dataset."
1095
+ ),
1096
+ anchor="w",
1097
+ wraplength=900,
1098
+ justify="left"
1099
+ ).pack(
1100
+ fill="x",
1101
+ padx=12,
1102
+ pady=5
1103
+ )
1104
+
1105
+ # Simulation method
1106
+ ctk.CTkLabel(
1107
+ self.simulation_frame,
1108
+ text="Simulation method:"
1109
+ ).pack(
1110
+ anchor="w",
1111
+ padx=12,
1112
+ pady=(8, 2)
1113
+ )
1114
+
1115
+ self.simulation_method = ctk.CTkOptionMenu(
1116
+ self.simulation_frame,
1117
+ values=[
1118
+ "Baseline",
1119
+ "Employment-based",
1120
+ "Random Forest"
1121
+ ],
1122
+ command=self._update_predictor_options, fg_color="#A63871", button_color="#A63871", button_hover_color="#842957", dropdown_hover_color=("#F4DCE7", "#A63871")
1123
+ )
1124
+ self.simulation_method.pack(
1125
+ anchor="w",
1126
+ padx=12,
1127
+ pady=5
1128
+ )
1129
+ self.simulation_method.set("Baseline")
1130
+
1131
+ # Number of rows
1132
+ ctk.CTkLabel(
1133
+ self.simulation_frame,
1134
+ text="Number of rows to simulate (leave empty for default):"
1135
+ ).pack(
1136
+ anchor="w",
1137
+ padx=12,
1138
+ pady=(8, 2)
1139
+ )
1140
+
1141
+ self.simulation_rows_entry = ctk.CTkEntry(
1142
+ self.simulation_frame,
1143
+ placeholder_text="Default: number of complete rows",
1144
+ width=300
1145
+ )
1146
+ self.simulation_rows_entry.pack(
1147
+ anchor="w",
1148
+ padx=12,
1149
+ pady=5
1150
+ )
1151
+
1152
+ # Predictor selection
1153
+ self.predictor_title = ctk.CTkLabel(
1154
+ self.simulation_frame,
1155
+ text="Random Forest predictor variables:"
1156
+ )
1157
+ self.predictor_title.pack(
1158
+ anchor="w",
1159
+ padx=12,
1160
+ pady=(10, 2)
1161
+ )
1162
+
1163
+ self.predictor_frame = ctk.CTkFrame(
1164
+ self.simulation_frame,
1165
+ fg_color="transparent"
1166
+ )
1167
+ self.predictor_frame.pack(
1168
+ fill="x",
1169
+ padx=12,
1170
+ pady=5
1171
+ )
1172
+
1173
+ self.predictor_variables = {}
1174
+ self.predictor_checkboxes = {}
1175
+
1176
+ self.predictor_title.pack_forget()
1177
+ self.predictor_frame.pack_forget()
1178
+ # Run simulation
1179
+ self.simulation_button = ctk.CTkButton(
1180
+ self.simulation_frame,
1181
+ fg_color="#C45A83", hover_color="#A63871", text="Run Simulation",
1182
+ command=self._run_simulation
1183
+ )
1184
+ self.simulation_button.pack(
1185
+ anchor="w",
1186
+ padx=12,
1187
+ pady=10
1188
+ )
1189
+
1190
+ # Simulation results
1191
+ self.simulation_result_label = ctk.CTkLabel(
1192
+ self.simulation_frame,
1193
+ text="Import a dataset to begin simulation.",
1194
+ anchor="w",
1195
+ justify="left",
1196
+ wraplength=950
1197
+ )
1198
+ self.simulation_result_label.pack(
1199
+ fill="x",
1200
+ padx=12,
1201
+ pady=8
1202
+ )
1203
+
1204
+ # Column comparison table
1205
+ ctk.CTkLabel(
1206
+ self.simulation_frame,
1207
+ text="Original vs simulated missingness",
1208
+ font=ctk.CTkFont(size=15, weight="bold")
1209
+ ).pack(
1210
+ anchor="w",
1211
+ padx=12,
1212
+ pady=(8, 5)
1213
+ )
1214
+
1215
+ self.simulation_table = ttk.Treeview(
1216
+ self.simulation_frame,
1217
+ columns=(
1218
+ "column",
1219
+ "original",
1220
+ "simulated",
1221
+ "difference"
1222
+ ),
1223
+ show="headings",
1224
+ height=6
1225
+ )
1226
+
1227
+ simulation_columns = [
1228
+ ("column", "Column", 200),
1229
+ ("original", "Original missing %", 150),
1230
+ ("simulated", "Simulated missing %", 160),
1231
+ ("difference", "Difference (pp)", 140)
1232
+ ]
1233
+
1234
+ for ident, title, width in simulation_columns:
1235
+ self.simulation_table.heading(
1236
+ ident,
1237
+ text=title
1238
+ )
1239
+ self.simulation_table.column(
1240
+ ident,
1241
+ width=width,
1242
+ stretch=True
1243
+ )
1244
+
1245
+ self.simulation_table.pack(
1246
+ fill="x",
1247
+ padx=12,
1248
+ pady=5
1249
+ )
1250
+
1251
+ self.export_simulation_button = ctk.CTkButton(
1252
+ self.simulation_frame,
1253
+ fg_color="#C45A83", hover_color="#A63871", text="Export Comparison CSV",
1254
+ command=self._export_simulation_results,
1255
+ state="disabled"
1256
+ )
1257
+ self.export_simulation_button.pack(
1258
+ anchor="w",
1259
+ padx=12,
1260
+ pady=(8, 12)
1261
+ )
1262
+
1263
+ def _update_predictor_options(self, selected_method=None) -> None:
1264
+
1265
+ if not hasattr(self, "current_df") or self.current_df is None:
1266
+ return
1267
+
1268
+ method = self.simulation_method.get()
1269
+
1270
+ if method != "Random Forest":
1271
+ self.predictor_title.pack_forget()
1272
+ self.predictor_frame.pack_forget()
1273
+ return
1274
+
1275
+ self.predictor_title.pack(
1276
+ anchor="w",
1277
+ padx=12,
1278
+ pady=(10, 2),
1279
+ before=self.simulation_button
1280
+ )
1281
+
1282
+ self.predictor_frame.pack(
1283
+ fill="x",
1284
+ padx=12,
1285
+ pady=5,
1286
+ before=self.simulation_button
1287
+ )
1288
+
1289
+ # Remove old predictor checkboxes
1290
+ for widget in self.predictor_frame.winfo_children():
1291
+ widget.destroy()
1292
+
1293
+ self.predictor_variables.clear()
1294
+ self.predictor_checkboxes.clear()
1295
+
1296
+ for column in self.current_df.columns:
1297
+
1298
+ variable = tk.BooleanVar(value=False)
1299
+
1300
+ checkbox = ctk.CTkCheckBox(
1301
+ self.predictor_frame,
1302
+ text=str(column),
1303
+ variable=variable, fg_color="#C45A83", hover_color="#A63871"
1304
+ )
1305
+ checkbox.pack(
1306
+ anchor="w",
1307
+ padx=5,
1308
+ pady=3
1309
+ )
1310
+
1311
+ self.predictor_variables[column] = variable
1312
+ self.predictor_checkboxes[column] = checkbox
1313
+
1314
+ # Employment is the predictor used in our current validation.
1315
+ if "employment" in self.current_df.columns:
1316
+ self.predictor_variables["employment"].set(True)
1317
+
1318
+ def _operation_running(self) -> bool:
1319
+ """Keep operations exclusive until their GUI result is processed."""
1320
+ return any(future is not None for future in (
1321
+ self._active_future, self._mcar_future,
1322
+ self._simulation_future, self._evaluation_future, self._imputation_future
1323
+ ))
1324
+
1325
+ # ---------------------------------------------------------
1326
+ # CSV IMPORT
1327
+ # ---------------------------------------------------------
1328
+
1329
+ def _choose_file(self) -> None:
1330
+
1331
+ if self._operation_running():
1332
+ messagebox.showinfo("Please wait", "Another operation is currently running.")
1333
+ return
1334
+
1335
+ filename = filedialog.askopenfilename(
1336
+ title="Choose a CSV dataset",
1337
+ filetypes=[("CSV files", "*.csv")]
1338
+ )
1339
+
1340
+ if not filename:
1341
+ return
1342
+
1343
+ if self._operation_running():
1344
+ messagebox.showinfo(
1345
+ "Please wait",
1346
+ "Another operation is currently running."
1347
+ )
1348
+ return
1349
+
1350
+ self.import_button.configure(state="disabled")
1351
+ self.status_label.configure(
1352
+ text="Reading CSV in the background..."
1353
+ )
1354
+
1355
+ future = self._pool.submit(
1356
+ self._analyze,
1357
+ filename
1358
+ )
1359
+
1360
+ self._active_future = future
1361
+
1362
+ self.after(
1363
+ 100,
1364
+ lambda: self._poll(future, filename)
1365
+ )
1366
+
1367
+ @staticmethod
1368
+ def _analyze(filename: str):
1369
+
1370
+ df = load_csv(filename)
1371
+
1372
+ return (
1373
+ df,
1374
+ summarize_dataset(df),
1375
+ column_missingness(df),
1376
+ missingness_matrix(df)
1377
+ )
1378
+
1379
+ def _poll(self, future, filename: str) -> None:
1380
+
1381
+ if self._closing:
1382
+ return
1383
+
1384
+ if not future.done():
1385
+ self.after(
1386
+ 100,
1387
+ lambda: self._poll(future, filename)
1388
+ )
1389
+ return
1390
+ self._active_future = None
1391
+ self.import_button.configure(state="normal")
1392
+
1393
+ try:
1394
+ df, summary, columns, matrix = future.result()
1395
+
1396
+ self.current_df = df
1397
+ self.current_matrix = matrix
1398
+ self.source_path = Path(filename).resolve()
1399
+ self.mcar_results = None
1400
+ self._clear_imputation()
1401
+ self._clear_benchmark()
1402
+ self._clear_evaluation(clear_simulation=True)
1403
+ self.mcar_result_label.configure(text="Click Run Little’s MCAR Test.")
1404
+
1405
+ self.simulation_comparison = None
1406
+ self.export_simulation_button.configure(
1407
+ state="disabled"
1408
+ )
1409
+
1410
+ except Exception as exc:
1411
+ self.status_label.configure(
1412
+ text="Import failed"
1413
+ )
1414
+ messagebox.showerror(
1415
+ "Could not import CSV",
1416
+ str(exc)
1417
+ )
1418
+ return
1419
+
1420
+ self.source_label.configure(
1421
+ text=f"Loaded: {Path(filename).name}"
1422
+ )
1423
+
1424
+ metric_values = {
1425
+ "rows": f"{summary.rows:,}",
1426
+ "columns": str(summary.columns),
1427
+ "missing": f"{summary.missing_cells:,}",
1428
+ "percent": f"{summary.missing_percent:.2f}%"
1429
+ }
1430
+
1431
+ for key, value in metric_values.items():
1432
+ self.metrics[key].configure(text=value)
1433
+
1434
+ self._update_column_summary(columns)
1435
+
1436
+ self._draw_plot(columns)
1437
+ self._update_heatmap_view()
1438
+
1439
+ self.simulation_table.delete(
1440
+ *self.simulation_table.get_children()
1441
+ )
1442
+
1443
+ self.simulation_result_label.configure(
1444
+ text="Choose a simulation method and click Run Simulation."
1445
+ )
1446
+
1447
+ self._update_predictor_options()
1448
+
1449
+ self.status_label.configure(
1450
+ text="Analysis complete — source CSV was not changed."
1451
+ )
1452
+
1453
+ # ---------------------------------------------------------
1454
+ # MISSINGNESS CHART
1455
+ # ---------------------------------------------------------
1456
+
1457
+ def _draw_plot(self, columns) -> None:
1458
+
1459
+ if self.canvas is not None:
1460
+ self.canvas.get_tk_widget().destroy()
1461
+ self.canvas = None
1462
+
1463
+ if self.placeholder is not None and self.placeholder.winfo_exists():
1464
+ self.placeholder.destroy()
1465
+ self.placeholder = None
1466
+
1467
+ top = (
1468
+ columns
1469
+ .sort_values(
1470
+ "missing_percent",
1471
+ ascending=False
1472
+ )
1473
+ .head(15)
1474
+ .iloc[::-1]
1475
+ )
1476
+
1477
+ figure = Figure(
1478
+ figsize=(8, 3.5),
1479
+ dpi=100
1480
+ )
1481
+
1482
+ ax = figure.add_subplot(111)
1483
+
1484
+ ax.barh(
1485
+ top["column"],
1486
+ top["missing_percent"],
1487
+ color="#C45A83"
1488
+ )
1489
+
1490
+ ax.set_xlabel("Missing values (%)")
1491
+ ax.set_xlim(0, 100)
1492
+ ax.set_title(
1493
+ "Up to 15 columns with highest missingness"
1494
+ )
1495
+
1496
+ figure.tight_layout()
1497
+
1498
+ self.canvas = FigureCanvasTkAgg(
1499
+ figure,
1500
+ master=self.plot_frame
1501
+ )
1502
+
1503
+ self.canvas.draw()
1504
+
1505
+ self.canvas.get_tk_widget().pack(
1506
+ fill="both",
1507
+ expand=True
1508
+ )
1509
+
1510
+ # ---------------------------------------------------------
1511
+ # MISSINGNESS HEATMAP
1512
+ # ---------------------------------------------------------
1513
+
1514
+ def _update_heatmap_view(self, choice=None) -> None:
1515
+
1516
+ if self.current_matrix is None:
1517
+ return
1518
+
1519
+ if self.heatmap_canvas is not None:
1520
+ self.heatmap_canvas.get_tk_widget().destroy()
1521
+
1522
+ if self.heatmap_label is not None and self.heatmap_label.winfo_exists():
1523
+ self.heatmap_label.destroy()
1524
+ self.heatmap_label = None
1525
+
1526
+ matrix = self.current_matrix
1527
+
1528
+ if self.heatmap_option.get() == "First 50 rows":
1529
+ matrix = matrix.head(50)
1530
+
1531
+ figure = Figure(
1532
+ figsize=(9, 4),
1533
+ dpi=100
1534
+ )
1535
+
1536
+ ax = figure.add_subplot(111)
1537
+
1538
+ from matplotlib.colors import ListedColormap
1539
+
1540
+ heatmap_colors = ListedColormap([
1541
+ "#F8E8EF", # Soft rose: values present
1542
+ "#702847" # Deep plum: missing values
1543
+ ])
1544
+
1545
+ ax.imshow(
1546
+ matrix.astype(int).to_numpy(),
1547
+ aspect="auto",
1548
+ interpolation="nearest",
1549
+ cmap=heatmap_colors,
1550
+ vmin=0,
1551
+ vmax=1
1552
+ )
1553
+
1554
+ ax.set_title(
1555
+ f"Missingness Heatmap — Showing {len(matrix)} of "
1556
+ f"{len(self.current_matrix)} rows"
1557
+ )
1558
+
1559
+ ax.set_xlabel("Columns")
1560
+ ax.set_ylabel("Rows")
1561
+
1562
+ ax.set_xticks(
1563
+ range(len(matrix.columns))
1564
+ )
1565
+
1566
+ ax.set_xticklabels(
1567
+ matrix.columns,
1568
+ rotation=45,
1569
+ ha="right"
1570
+ )
1571
+
1572
+ figure.tight_layout()
1573
+
1574
+ self.heatmap_canvas = FigureCanvasTkAgg(
1575
+ figure,
1576
+ master=self.heatmap_frame
1577
+ )
1578
+
1579
+ self.heatmap_canvas.draw()
1580
+
1581
+ self.heatmap_canvas.get_tk_widget().pack(
1582
+ fill="both",
1583
+ expand=True
1584
+ )
1585
+
1586
+ # ---------------------------------------------------------
1587
+ # LITTLE'S MCAR TEST
1588
+ # ---------------------------------------------------------
1589
+
1590
+ def _run_mcar(self) -> None:
1591
+
1592
+ if self.current_df is None:
1593
+ messagebox.showwarning(
1594
+ "No dataset",
1595
+ "Please import a dataset first."
1596
+ )
1597
+ return
1598
+
1599
+ if self._operation_running():
1600
+ messagebox.showinfo(
1601
+ "Please wait",
1602
+ "Another operation is currently running."
1603
+ )
1604
+ return
1605
+
1606
+ self.mcar_results = None
1607
+ self.mcar_button.configure(
1608
+ state="disabled"
1609
+ )
1610
+
1611
+ self.mcar_result_label.configure(
1612
+ text="Running Little's MCAR test..."
1613
+ )
1614
+
1615
+ future = self._pool.submit(
1616
+ run_mcar_test,
1617
+ self.current_df
1618
+ )
1619
+
1620
+ self._mcar_future = future
1621
+
1622
+ self.after(
1623
+ 100,
1624
+ lambda: self._poll_mcar(future)
1625
+ )
1626
+
1627
+ def _poll_mcar(self, future) -> None:
1628
+
1629
+ if self._closing:
1630
+ return
1631
+
1632
+ if not future.done():
1633
+ self.after(
1634
+ 100,
1635
+ lambda: self._poll_mcar(future)
1636
+ )
1637
+ return
1638
+ self._mcar_future = None
1639
+ self.mcar_button.configure(
1640
+ state="normal"
1641
+ )
1642
+
1643
+ try:
1644
+ result = future.result()
1645
+ self.mcar_results = result
1646
+
1647
+ included = ", ".join(
1648
+ result["included_columns"]
1649
+ )
1650
+
1651
+ excluded = ", ".join(
1652
+ result["excluded_columns"]
1653
+ )
1654
+
1655
+ if not excluded:
1656
+ excluded = "None"
1657
+
1658
+ self.mcar_result_label.configure(
1659
+ text=(
1660
+ f"P-value: {result['p_value']:.4f}\n"
1661
+ f"Significance level: "
1662
+ f"{result['significance_level']}\n\n"
1663
+ f"Interpretation: "
1664
+ f"{result['interpretation']}\n\n"
1665
+ f"Included columns: {included}\n"
1666
+ f"Excluded columns: {excluded}"
1667
+ )
1668
+ )
1669
+
1670
+ self.status_label.configure(
1671
+ text="Little's MCAR test completed."
1672
+ )
1673
+
1674
+ except Exception as exc:
1675
+ self.mcar_result_label.configure(
1676
+ text=f"MCAR test failed: {exc}"
1677
+ )
1678
+
1679
+ # ---------------------------------------------------------
1680
+ # RUN MISSINGNESS SIMULATION
1681
+ # ---------------------------------------------------------
1682
+
1683
+ @staticmethod
1684
+ def _simulate(
1685
+ df,
1686
+ method,
1687
+ n_rows,
1688
+ predictor_columns
1689
+ ):
1690
+ """Run the selected simulation and compare its results."""
1691
+
1692
+ if method == "Baseline":
1693
+
1694
+ simulated_df, reference_df = simulate_missingness(
1695
+ df,
1696
+ n_rows=n_rows,
1697
+ return_reference=True
1698
+ )
1699
+
1700
+ elif method == "Employment-based":
1701
+
1702
+ simulated_df, reference_df = simulate_missingness_by_employment(
1703
+ df,
1704
+ n_rows=n_rows,
1705
+ return_reference=True
1706
+ )
1707
+
1708
+ elif method == "Random Forest":
1709
+
1710
+ simulated_df, reference_df = simulate_missingness_conditional(
1711
+ df,
1712
+ predictor_columns=predictor_columns,
1713
+ n_rows=n_rows,
1714
+ return_reference=True
1715
+ )
1716
+
1717
+ else:
1718
+ raise ValueError("Unknown simulation method.")
1719
+
1720
+ comparison = compare_missingness_patterns(
1721
+ df,
1722
+ simulated_df
1723
+ )
1724
+
1725
+ return simulated_df, reference_df, comparison
1726
+
1727
+ def _run_simulation(self) -> None:
1728
+
1729
+ if self.current_df is None:
1730
+ messagebox.showwarning(
1731
+ "No dataset",
1732
+ "Please import a dataset first."
1733
+ )
1734
+ return
1735
+
1736
+ if self._operation_running():
1737
+ messagebox.showinfo(
1738
+ "Please wait",
1739
+ "Another operation is currently running."
1740
+ )
1741
+ return
1742
+
1743
+ method = self.simulation_method.get()
1744
+
1745
+ # Read the requested number of rows
1746
+ rows_text = self.simulation_rows_entry.get().strip()
1747
+
1748
+ if rows_text:
1749
+ try:
1750
+ n_rows = int(rows_text)
1751
+
1752
+ if n_rows <= 0:
1753
+ raise ValueError
1754
+
1755
+ except ValueError:
1756
+ messagebox.showerror(
1757
+ "Invalid number of rows",
1758
+ "Enter a positive whole number."
1759
+ )
1760
+ return
1761
+ else:
1762
+ n_rows = None
1763
+
1764
+ # Check method requirements
1765
+ predictor_columns = []
1766
+
1767
+ if method == "Employment-based":
1768
+
1769
+ if "employment" not in self.current_df.columns:
1770
+ messagebox.showerror(
1771
+ "Missing employment column",
1772
+ "The employment-based method requires a column "
1773
+ "named 'employment'."
1774
+ )
1775
+ return
1776
+
1777
+ elif method == "Random Forest":
1778
+
1779
+ predictor_columns = [
1780
+ column
1781
+ for column, variable
1782
+ in self.predictor_variables.items()
1783
+ if variable.get()
1784
+ ]
1785
+
1786
+ if not predictor_columns:
1787
+ messagebox.showerror(
1788
+ "No predictors selected",
1789
+ "Select at least one predictor variable."
1790
+ )
1791
+ return
1792
+ if len(predictor_columns) > 1:
1793
+ messagebox.showinfo(
1794
+ "Experimental configuration",
1795
+ "Multiple predictors are supported. "
1796
+ "Their performance may vary depending on the dataset."
1797
+ )
1798
+
1799
+ self._clear_evaluation(clear_simulation=True)
1800
+ self._clear_benchmark()
1801
+ self.simulation_comparison = None
1802
+ self.simulation_table.delete(*self.simulation_table.get_children())
1803
+ self.simulation_button.configure(
1804
+ state="disabled"
1805
+ )
1806
+
1807
+ self.export_simulation_button.configure(
1808
+ state="disabled"
1809
+ )
1810
+
1811
+ self.simulation_result_label.configure(
1812
+ text="Running simulation. Please wait..."
1813
+ )
1814
+
1815
+ self.status_label.configure(
1816
+ text="Missingness simulation is running..."
1817
+ )
1818
+
1819
+ future = self._pool.submit(
1820
+ self._simulate,
1821
+ self.current_df.copy(),
1822
+ method,
1823
+ n_rows,
1824
+ predictor_columns
1825
+ )
1826
+
1827
+ config = {"method": method, "requested_rows": n_rows,
1828
+ "predictors": (["employment"] if method == "Employment-based" else list(predictor_columns)),
1829
+ "random_state": DEFAULT_RANDOM_STATE}
1830
+ if method == "Random Forest":
1831
+ config["n_estimators"] = 200
1832
+ self._simulation_future = future
1833
+
1834
+ self.after(
1835
+ 100,
1836
+ lambda: self._poll_simulation(future, method, config)
1837
+ )
1838
+
1839
+ def _poll_simulation(self, future, method, config) -> None:
1840
+
1841
+ if self._closing:
1842
+ return
1843
+
1844
+ if not future.done():
1845
+ self.after(
1846
+ 100,
1847
+ lambda: self._poll_simulation(future, method, config)
1848
+ )
1849
+ return
1850
+ self._simulation_future = None
1851
+ self.simulation_button.configure(
1852
+ state="normal"
1853
+ )
1854
+
1855
+ try:
1856
+ simulated_df, reference_df, comparison = future.result()
1857
+
1858
+ except Exception as exc:
1859
+ self.simulation_result_label.configure(
1860
+ text=f"Simulation failed: {exc}"
1861
+ )
1862
+
1863
+ self.status_label.configure(
1864
+ text="Simulation failed."
1865
+ )
1866
+
1867
+ messagebox.showerror(
1868
+ "Simulation error",
1869
+ str(exc)
1870
+ )
1871
+ return
1872
+
1873
+ self.simulated_df = simulated_df
1874
+ self.reference_df = reference_df
1875
+ self.last_simulation_method = method
1876
+ self.simulation_config = {**config, "actual_rows": len(simulated_df)}
1877
+ self._prepare_evaluation()
1878
+ self.simulation_comparison = comparison
1879
+ self.benchmark_button.configure(state="normal")
1880
+
1881
+ # Display overall comparison
1882
+ overall = comparison["overall"]
1883
+
1884
+ original_percent = overall[
1885
+ "original_missing_percent"
1886
+ ]
1887
+
1888
+ simulated_percent = overall[
1889
+ "simulated_missing_percent"
1890
+ ]
1891
+
1892
+ overall_difference = overall["difference"]
1893
+
1894
+ # Average difference between missingness patterns
1895
+ pattern_difference = (
1896
+ comparison["patterns"]["difference"].mean()
1897
+ )
1898
+
1899
+ co_missingness = comparison["co_missingness"]
1900
+
1901
+ if co_missingness.empty:
1902
+ average_co_difference = 0.0
1903
+ else:
1904
+ average_co_difference = (
1905
+ co_missingness["jaccard_difference"].mean()
1906
+ )
1907
+
1908
+ self.simulation_result_label.configure(
1909
+ text=(
1910
+ f"Method: {method}\n"
1911
+ f"Original missingness: {original_percent:.2f}%\n"
1912
+ f"Simulated missingness: {simulated_percent:.2f}%\n"
1913
+ f"Overall difference: {overall_difference:.2f} "
1914
+ f"percentage points\n"
1915
+ f"Average pattern difference: "
1916
+ f"{pattern_difference:.4f}\n"
1917
+ f"Average co-missingness difference: "
1918
+ f"{average_co_difference:.4f}\n\n"
1919
+ f"Simulation completed. The original dataset "
1920
+ f"was not modified."
1921
+ )
1922
+ )
1923
+
1924
+ # Update column comparison table
1925
+ self.simulation_table.delete(
1926
+ *self.simulation_table.get_children()
1927
+ )
1928
+
1929
+ for column, row in comparison["by_column"].iterrows():
1930
+
1931
+ self.simulation_table.insert(
1932
+ "",
1933
+ "end",
1934
+ values=(
1935
+ column,
1936
+ f"{row['original_missing_percent']:.2f}%",
1937
+ f"{row['simulated_missing_percent']:.2f}%",
1938
+ f"{row['difference']:.2f}"
1939
+ )
1940
+ )
1941
+
1942
+ self.export_simulation_button.configure(
1943
+ state="normal"
1944
+ )
1945
+
1946
+ self.status_label.configure(
1947
+ text="Missingness simulation completed."
1948
+ )
1949
+
1950
+ # ---------------------------------------------------------
1951
+ # EXPORT SIMULATION COMPARISON
1952
+ # ---------------------------------------------------------
1953
+
1954
+ def _export_simulation_results(self) -> None:
1955
+
1956
+ if self.simulation_comparison is None:
1957
+ messagebox.showwarning(
1958
+ "No results",
1959
+ "Run a simulation before exporting results."
1960
+ )
1961
+ return
1962
+
1963
+ filename = filedialog.asksaveasfilename(
1964
+ title="Export simulation comparison",
1965
+ defaultextension=".csv",
1966
+ filetypes=[("CSV files", "*.csv")],
1967
+ initialfile="missinglab_simulation_comparison.csv"
1968
+ )
1969
+
1970
+ if not filename:
1971
+ return
1972
+
1973
+ try:
1974
+ comparison = self.simulation_comparison
1975
+
1976
+ export_df = (
1977
+ comparison["by_column"]
1978
+ .reset_index()
1979
+ .rename(columns={"index": "column"})
1980
+ )
1981
+
1982
+ overall = comparison["overall"]
1983
+
1984
+ export_df["overall_original_missing_percent"] = (
1985
+ overall["original_missing_percent"]
1986
+ )
1987
+
1988
+ export_df["overall_simulated_missing_percent"] = (
1989
+ overall["simulated_missing_percent"]
1990
+ )
1991
+
1992
+ export_df["overall_difference"] = (
1993
+ overall["difference"]
1994
+ )
1995
+
1996
+ export_df.to_csv(
1997
+ filename,
1998
+ index=False
1999
+ )
2000
+
2001
+ messagebox.showinfo(
2002
+ "Export successful",
2003
+ f"Comparison results saved to:\n{filename}"
2004
+ )
2005
+
2006
+ except Exception as exc:
2007
+ messagebox.showerror(
2008
+ "Export failed",
2009
+ str(exc)
2010
+ )
2011
+
2012
+ # ---------------------------------------------------------
2013
+ # ANALYSIS-AWARE EVALUATION
2014
+ # ---------------------------------------------------------
2015
+
2016
+ def _build_evaluation_section(self, container) -> None:
2017
+ frame = ctk.CTkFrame(container)
2018
+ frame.pack(fill="x", pady=10)
2019
+ ctk.CTkLabel(frame, text="Analysis-Aware Evaluation",
2020
+ font=ctk.CTkFont(size=18, weight="bold")).pack(
2021
+ anchor="w", padx=12, pady=(12, 5))
2022
+ ctk.CTkLabel(frame, text=(
2023
+ "Compare the complete sampled reference rows with the same rows "
2024
+ "after simulated missingness and missing-data handling."),
2025
+ wraplength=850, justify="left", anchor="w").pack(fill="x", padx=12, pady=5)
2026
+
2027
+ self.analysis_options = {
2028
+ "Descriptive statistics": "descriptive",
2029
+ "Distribution (KS distance)": "distribution",
2030
+ "Correlation": "correlation",
2031
+ "Linear regression": "regression",
2032
+ }
2033
+ self.handling_options = {
2034
+ "Complete-case analysis": "complete_case",
2035
+ "Mean imputation": "mean",
2036
+ "Median imputation": "median",
2037
+ "KNN imputation": "knn",
2038
+ "Iterative imputation": "iterative",
2039
+ }
2040
+ self.evaluation_columns = []
2041
+
2042
+ def menu(label, values, command):
2043
+ label_widget = ctk.CTkLabel(frame, text=label)
2044
+ label_widget.pack(anchor="w", padx=12, pady=(8, 2))
2045
+ if label == "Missing-data handling:":
2046
+ self.handling_label = label_widget
2047
+ widget = ctk.CTkOptionMenu(frame, values=values, command=command, width=260, fg_color="#A63871", button_color="#A63871", button_hover_color="#842957", dropdown_hover_color=("#F4DCE7", "#A63871"))
2048
+ widget.pack(anchor="w", padx=12, pady=3)
2049
+ return widget
2050
+
2051
+ self.analysis_menu = menu("Analysis type:", list(self.analysis_options),
2052
+ self._evaluation_options_changed)
2053
+ self.eval_first = menu("First variable (predictor for regression):", ["—"],
2054
+ self._evaluation_options_changed)
2055
+ self.eval_second_label = ctk.CTkLabel(frame, text="Second variable (outcome for regression):")
2056
+ self.eval_second = ctk.CTkOptionMenu(frame, values=["—"], width=260,
2057
+ command=self._evaluation_options_changed, fg_color="#A63871", button_color="#A63871", button_hover_color="#842957", dropdown_hover_color=("#F4DCE7", "#A63871"))
2058
+ self.handling_menu = menu("Missing-data handling:", list(self.handling_options),
2059
+ self._evaluation_options_changed)
2060
+ self.eval_knn_label = ctk.CTkLabel(frame, text="KNN neighbors:")
2061
+ self.eval_knn_entry = ctk.CTkEntry(frame)
2062
+ self.eval_knn_entry.insert(0, "5")
2063
+ self.eval_iter_label = ctk.CTkLabel(frame, text="Iterative maximum iterations:")
2064
+ self.eval_iter_entry = ctk.CTkEntry(frame)
2065
+ self.eval_iter_entry.insert(0, "10")
2066
+ self.evaluation_button = ctk.CTkButton(frame, fg_color="#C45A83", hover_color="#A63871", text="Run Evaluation",
2067
+ command=self._run_evaluation, state="disabled")
2068
+ self.evaluation_button.pack(anchor="w", padx=12, pady=10)
2069
+ self.evaluation_label = ctk.CTkLabel(frame, text="Run a simulation first.",
2070
+ anchor="w", justify="left", wraplength=850)
2071
+ self.evaluation_label.pack(fill="x", padx=12, pady=5)
2072
+ self.evaluation_table = ttk.Treeview(frame, columns=("metric", "reference", "simulated", "difference"),
2073
+ show="headings", height=4)
2074
+ for key, title in [("metric", "Metric"), ("reference", "Reference"),
2075
+ ("simulated", "After handling"), ("difference", "Absolute difference")]:
2076
+ self.evaluation_table.heading(key, text=title)
2077
+ self.evaluation_table.column(key, width=150, stretch=True)
2078
+ self.evaluation_table.pack(fill="x", padx=12, pady=5)
2079
+ self.export_evaluation_button = ctk.CTkButton(frame, fg_color="#C45A83", hover_color="#A63871", text="Export Evaluation CSV",
2080
+ command=self._export_evaluation_results, state="disabled")
2081
+ self.export_evaluation_button.pack(anchor="w", padx=12, pady=(8, 12))
2082
+ self._clear_evaluation(clear_simulation=True)
2083
+
2084
+ def _clear_evaluation(self, clear_simulation=False) -> None:
2085
+ self.evaluation_results = None
2086
+ self.evaluation_config = None
2087
+ self.evaluation_table.delete(*self.evaluation_table.get_children())
2088
+ self.export_evaluation_button.configure(state="disabled")
2089
+ if clear_simulation:
2090
+ self.reference_df = None
2091
+ self.simulated_df = None
2092
+ self.last_simulation_method = None
2093
+ self.simulation_config = None
2094
+ self.evaluation_columns = []
2095
+ for widget in (self.eval_first, self.eval_second):
2096
+ widget.configure(values=["—"], state="disabled")
2097
+ widget.set("—")
2098
+ self.evaluation_button.configure(state="disabled")
2099
+ self.evaluation_label.configure(text="Run a simulation first.")
2100
+ else:
2101
+ self.evaluation_label.configure(text="Choose variables and run the evaluation.")
2102
+
2103
+ def _prepare_evaluation(self) -> None:
2104
+ self.evaluation_columns = [str(c) for c in self.reference_df.columns
2105
+ if pd.api.types.is_numeric_dtype(self.reference_df[c])
2106
+ and not pd.api.types.is_bool_dtype(self.reference_df[c])
2107
+ and not pd.api.types.is_complex_dtype(self.reference_df[c])]
2108
+ values = self.evaluation_columns or ["—"]
2109
+ for widget in (self.eval_first, self.eval_second):
2110
+ widget.configure(values=values, state="normal" if self.evaluation_columns else "disabled")
2111
+ self.eval_first.set(values[0])
2112
+ self.eval_second.set(values[min(1, len(values)-1)])
2113
+ self._evaluation_options_changed()
2114
+
2115
+ def _evaluation_options_changed(self, choice=None) -> None:
2116
+ pair = self.analysis_options[self.analysis_menu.get()] in ("correlation", "regression")
2117
+ if pair:
2118
+ self.eval_second_label.pack(anchor="w", padx=12, pady=(8, 2), before=self.handling_label)
2119
+ self.eval_second.pack(anchor="w", padx=12, pady=3, before=self.handling_label)
2120
+ else:
2121
+ self.eval_second_label.pack_forget()
2122
+ self.eval_second.pack_forget()
2123
+ handling = self.handling_options[self.handling_menu.get()]
2124
+ self._show_parameter_controls(handling, self.eval_knn_label, self.eval_knn_entry,
2125
+ self.eval_iter_label, self.eval_iter_entry,
2126
+ self.evaluation_button)
2127
+ self._clear_evaluation()
2128
+ if self.reference_df is None:
2129
+ self.evaluation_button.configure(state="disabled")
2130
+ self.evaluation_label.configure(text="Run a simulation first.")
2131
+ return
2132
+ enough = len(self.evaluation_columns) >= (2 if pair else 1)
2133
+ self.evaluation_button.configure(state="normal" if enough else "disabled")
2134
+ if not enough:
2135
+ self.evaluation_label.configure(text="Not enough numerical variables for this analysis.")
2136
+
2137
+ def _run_evaluation(self) -> None:
2138
+ if self._operation_running():
2139
+ messagebox.showinfo("Please wait", "Another operation is currently running.")
2140
+ return
2141
+ if self.reference_df is None or self.simulated_df is None:
2142
+ return
2143
+ analysis = self.analysis_options[self.analysis_menu.get()]
2144
+ handling = self.handling_options[self.handling_menu.get()]
2145
+ columns = [self.eval_first.get()]
2146
+ if analysis in ("correlation", "regression"):
2147
+ columns.append(self.eval_second.get())
2148
+ if len(set(columns)) != len(columns):
2149
+ messagebox.showerror("Invalid variables", "Choose two distinct numerical variables.")
2150
+ return
2151
+ try:
2152
+ params = self._read_parameters(handling, self.eval_knn_entry, self.eval_iter_entry)
2153
+ except ValueError as exc:
2154
+ messagebox.showerror("Invalid parameters", str(exc))
2155
+ return
2156
+ self._clear_evaluation()
2157
+ for widget in (self.analysis_menu, self.eval_first, self.eval_second, self.handling_menu,
2158
+ self.eval_knn_entry, self.eval_iter_entry, self.evaluation_button):
2159
+ widget.configure(state="disabled")
2160
+ self.evaluation_label.configure(text="Running evaluation...")
2161
+ self.status_label.configure(text="Analysis-aware evaluation is running...")
2162
+ future = self._pool.submit(evaluate_analysis, self.reference_df, self.simulated_df,
2163
+ columns, analysis=analysis, handling=handling, **params)
2164
+ config = {"analysis": analysis, "variables": list(columns), "handling": handling}
2165
+ config.update(self._report_imputation_parameters(handling, params))
2166
+ self._evaluation_future = future
2167
+ self.after(100, lambda: self._poll_evaluation(future, config))
2168
+
2169
+ def _poll_evaluation(self, future, config) -> None:
2170
+ if self._closing:
2171
+ return
2172
+ if not future.done():
2173
+ self.after(100, lambda: self._poll_evaluation(future, config))
2174
+ return
2175
+ self._evaluation_future = None
2176
+ for widget in (self.analysis_menu, self.eval_first, self.eval_second, self.handling_menu,
2177
+ self.eval_knn_entry, self.eval_iter_entry, self.evaluation_button):
2178
+ widget.configure(state="normal")
2179
+ try:
2180
+ results = future.result()
2181
+ results.insert(0, "simulation_method", self.last_simulation_method)
2182
+ self.evaluation_results = results
2183
+ self.evaluation_config = config
2184
+ for row in results.itertuples(index=False):
2185
+ self.evaluation_table.insert("", "end", values=(row.metric,
2186
+ f"{row.reference:.6g}", f"{row.simulated:.6g}", f"{row.absolute_difference:.6g}"))
2187
+ first = results.iloc[0]
2188
+ self.evaluation_label.configure(text=(
2189
+ f"Simulation: {self.last_simulation_method} | Variables: {first['variables']} | Handling: {first['handling']}\n"
2190
+ f"Reference rows: {first['reference_rows']} | Rows used after handling: {first['rows_used']}\n"
2191
+ f"Observed complete rows (selected variables): {first['observed_complete_rows']} | "
2192
+ f"Missing cells: {first['missing_cells']} | Imputed cells: {first['imputed_cells']}\n"
2193
+ "A zero difference means the selected metric is unchanged. Larger differences "
2194
+ "indicate more distortion for that metric; units differ across metrics. "
2195
+ "The reference represents sampled complete rows, not the entire original population."))
2196
+ self.export_evaluation_button.configure(state="normal")
2197
+ self.status_label.configure(text="Analysis-aware evaluation completed.")
2198
+ except Exception as exc:
2199
+ self.evaluation_label.configure(text=f"Evaluation failed: {exc}")
2200
+ self.status_label.configure(text="Evaluation failed.")
2201
+ messagebox.showerror("Evaluation error", str(exc))
2202
+
2203
+ def _export_evaluation_results(self) -> None:
2204
+ if self.evaluation_results is None or self._operation_running():
2205
+ return
2206
+ filename = filedialog.asksaveasfilename(title="Export evaluation results",
2207
+ defaultextension=".csv", filetypes=[("CSV files", "*.csv")],
2208
+ initialfile="missinglab_analysis_evaluation.csv")
2209
+ if not filename:
2210
+ return
2211
+ try:
2212
+ self.evaluation_results.to_csv(filename, index=False)
2213
+ messagebox.showinfo("Export successful", f"Evaluation results saved to:\n{filename}")
2214
+ except Exception as exc:
2215
+ messagebox.showerror("Export failed", str(exc))
2216
+
2217
+
2218
+ def _build_imputation_section(self, container) -> None:
2219
+ frame = ctk.CTkFrame(container)
2220
+ frame.pack(fill="x", pady=10)
2221
+
2222
+ ctk.CTkLabel(
2223
+ frame,
2224
+ text="Imputation and Cleaned Dataset",
2225
+ font=ctk.CTkFont(size=18, weight="bold")
2226
+ ).pack(anchor="w", padx=12, pady=8)
2227
+
2228
+ ctk.CTkLabel(
2229
+ frame,
2230
+ text="Impute a copy of the imported CSV. Mean, Median, KNN, and Iterative fill numerical columns. Mode fills categorical columns. Entirely missing columns may remain incomplete.",
2231
+ wraplength=850,
2232
+ justify="left",
2233
+ anchor="w"
2234
+ ).pack(fill="x", padx=12)
2235
+
2236
+ ctk.CTkLabel(frame, text="Method:").pack(
2237
+ anchor="w", padx=12, pady=(8, 2)
2238
+ )
2239
+
2240
+ self.imputation_menu = ctk.CTkOptionMenu(
2241
+ frame,
2242
+ values=list(METHODS),
2243
+ command=self._imputation_options_changed,
2244
+ fg_color="#A63871",
2245
+ button_color="#A63871",
2246
+ button_hover_color="#842957",
2247
+ dropdown_hover_color=("#F4DCE7", "#A63871")
2248
+ )
2249
+ self.imputation_menu.pack(anchor="w", padx=12)
2250
+
2251
+ self.knn_label = ctk.CTkLabel(
2252
+ frame, text="KNN neighbors (default 5):"
2253
+ )
2254
+ self.knn_entry = ctk.CTkEntry(frame)
2255
+ self.knn_entry.insert(0, "5")
2256
+
2257
+ self.iterative_label = ctk.CTkLabel(
2258
+ frame, text="Iterative maximum iterations (default 10):"
2259
+ )
2260
+ self.iterative_entry = ctk.CTkEntry(frame)
2261
+ self.iterative_entry.insert(0, "10")
2262
+
2263
+ self.imputation_button = ctk.CTkButton(
2264
+ frame,
2265
+ fg_color="#C45A83",
2266
+ hover_color="#A63871",
2267
+ text="Run Imputation",
2268
+ command=self._run_imputation
2269
+ )
2270
+ self.imputation_button.pack(anchor="w", padx=12, pady=8)
2271
+
2272
+ self.imputation_label = ctk.CTkLabel(
2273
+ frame,
2274
+ text="Import a dataset first.",
2275
+ anchor="w",
2276
+ justify="left",
2277
+ wraplength=850
2278
+ )
2279
+ self.imputation_label.pack(fill="x", padx=12)
2280
+
2281
+ self.cleaned_export_button = ctk.CTkButton(
2282
+ frame,
2283
+ fg_color="#C45A83",
2284
+ hover_color="#A63871",
2285
+ text="Export Imputed CSV",
2286
+ command=self._export_cleaned,
2287
+ state="disabled"
2288
+ )
2289
+ self.cleaned_export_button.pack(anchor="w", padx=12, pady=8)
2290
+
2291
+ ctk.CTkLabel(
2292
+ frame,
2293
+ text="Imputation Benchmark",
2294
+ font=ctk.CTkFont(size=18, weight="bold")
2295
+ ).pack(anchor="w", padx=12, pady=8)
2296
+
2297
+ ctk.CTkLabel(
2298
+ frame,
2299
+ text="Compare all five methods using the latest simulated dataset and its complete reference. MAE and RMSE evaluate numerical imputation, while Accuracy evaluates categorical imputation by Mode. Each method is evaluated only on the data type it supports.",
2300
+ wraplength=850,
2301
+ justify="left",
2302
+ anchor="w"
2303
+ ).pack(fill="x", padx=12)
2304
+
2305
+ ctk.CTkLabel(
2306
+ frame, text="Benchmark KNN neighbors:"
2307
+ ).pack(anchor="w", padx=12, pady=(8, 2))
2308
+
2309
+ self.benchmark_knn_entry = ctk.CTkEntry(frame)
2310
+ self.benchmark_knn_entry.insert(0, "5")
2311
+ self.benchmark_knn_entry.pack(anchor="w", padx=12)
2312
+
2313
+ ctk.CTkLabel(
2314
+ frame, text="Benchmark iterative maximum iterations:"
2315
+ ).pack(anchor="w", padx=12, pady=(8, 2))
2316
+
2317
+ self.benchmark_iter_entry = ctk.CTkEntry(frame)
2318
+ self.benchmark_iter_entry.insert(0, "10")
2319
+ self.benchmark_iter_entry.pack(anchor="w", padx=12)
2320
+
2321
+ self.benchmark_button = ctk.CTkButton(
2322
+ frame,
2323
+ fg_color="#C45A83",
2324
+ hover_color="#A63871",
2325
+ text="Run Benchmark",
2326
+ command=self._run_benchmark,
2327
+ state="disabled"
2328
+ )
2329
+ self.benchmark_button.pack(anchor="w", padx=12, pady=8)
2330
+
2331
+ self.benchmark_label = ctk.CTkLabel(
2332
+ frame,
2333
+ text="Run a simulation first.",
2334
+ anchor="w",
2335
+ justify="left",
2336
+ wraplength=850
2337
+ )
2338
+ self.benchmark_label.pack(fill="x", padx=12)
2339
+
2340
+ self.benchmark_table = ttk.Treeview(
2341
+ frame,
2342
+ columns=("method", "MAE", "RMSE", "Accuracy", "cells"),
2343
+ show="headings",
2344
+ height=5
2345
+ )
2346
+
2347
+ for key, title in [
2348
+ ("method", "Method"),
2349
+ ("MAE", "MAE"),
2350
+ ("RMSE", "RMSE"),
2351
+ ("Accuracy", "Accuracy"),
2352
+ ("cells", "Evaluated cells")
2353
+ ]:
2354
+ self.benchmark_table.heading(key, text=title)
2355
+ self.benchmark_table.column(key, width=130)
2356
+
2357
+ self.benchmark_table.pack(fill="x", padx=12, pady=8)
2358
+
2359
+ self._imputation_options_changed()
2360
+
2361
+
2362
+ def _clear_imputation(self) -> None:
2363
+ self.cleaned_df = None
2364
+ self.imputation_config = None
2365
+ self.cleaned_export_button.configure(state="disabled")
2366
+ self.imputation_label.configure(text="Choose a method and run imputation.")
2367
+
2368
+ def _clear_benchmark(self) -> None:
2369
+ self.benchmark_results = None
2370
+ self.benchmark_config = None
2371
+ self.benchmark_table.delete(*self.benchmark_table.get_children())
2372
+ self.benchmark_button.configure(state="disabled")
2373
+ self.benchmark_label.configure(text="Run a simulation first.")
2374
+
2375
+ @staticmethod
2376
+ def _show_parameter_controls(method, knn_label, knn_entry, iter_label, iter_entry, button):
2377
+ for label, entry, name in ((knn_label, knn_entry, "knn"),
2378
+ (iter_label, iter_entry, "iterative")):
2379
+ if method.lower() == name:
2380
+ label.pack(anchor="w", padx=12, pady=(8, 2), before=button)
2381
+ entry.pack(anchor="w", padx=12, before=button)
2382
+ else:
2383
+ label.pack_forget()
2384
+ entry.pack_forget()
2385
+
2386
+ def _imputation_options_changed(self, choice=None):
2387
+ self._show_parameter_controls(self.imputation_menu.get(), self.knn_label,
2388
+ self.knn_entry, self.iterative_label,
2389
+ self.iterative_entry, self.imputation_button)
2390
+
2391
+ @staticmethod
2392
+ def _read_parameters(method, knn_entry, iterative_entry):
2393
+ method = method.lower() if method is not None else None
2394
+ try:
2395
+ neighbors = int(knn_entry.get()) if method in (None, "knn") else 5
2396
+ iterations = int(iterative_entry.get()) if method in (None, "iterative") else 10
2397
+ except ValueError as exc:
2398
+ raise ValueError("Enter positive whole numbers for imputation parameters.") from exc
2399
+ if neighbors < 1 or iterations < 1:
2400
+ raise ValueError("Enter positive whole numbers for imputation parameters.")
2401
+ return {"n_neighbors": neighbors, "max_iter": iterations}
2402
+
2403
+ def _imputation_parameters(self, method=None):
2404
+ if method is None:
2405
+ return self._read_parameters(None, self.benchmark_knn_entry, self.benchmark_iter_entry)
2406
+ return self._read_parameters(method, self.knn_entry, self.iterative_entry)
2407
+
2408
+ def _run_imputation(self) -> None:
2409
+ if self._operation_running() or self.current_df is None:
2410
+ messagebox.showinfo("Imputation", "Import a dataset and wait for any running operation to finish.")
2411
+ return
2412
+ method = self.imputation_menu.get()
2413
+ try:
2414
+ params = self._imputation_parameters(method)
2415
+ except ValueError as exc:
2416
+ messagebox.showerror("Invalid parameters", str(exc))
2417
+ return
2418
+ self._clear_imputation()
2419
+ self.imputation_button.configure(state="disabled")
2420
+ self.imputation_label.configure(text="Running imputation...")
2421
+ config = {"method": method, **self._report_imputation_parameters(method, params)}
2422
+ future = self._pool.submit(impute_dataset, self.current_df.copy(deep=True), method, **params)
2423
+ self._imputation_future = future
2424
+ self.after(100, lambda: self._poll_imputation_job(future, "imputation", config))
2425
+
2426
+ def _run_benchmark(self) -> None:
2427
+ if self._operation_running() or self.reference_df is None or self.simulated_df is None:
2428
+ messagebox.showinfo("Benchmark", "Run a simulation and wait for any running operation to finish.")
2429
+ return
2430
+ try:
2431
+ params = self._imputation_parameters()
2432
+ except ValueError as exc:
2433
+ messagebox.showerror("Invalid parameters", str(exc))
2434
+ return
2435
+ self._clear_benchmark()
2436
+ self.benchmark_label.configure(text="Running benchmark...")
2437
+ config = {"simulation_method": self.last_simulation_method,
2438
+ "methods": list(METHODS),
2439
+ "knn": self._report_imputation_parameters("knn", params),
2440
+ "iterative": self._report_imputation_parameters("iterative", params)}
2441
+ future = self._pool.submit(compare_imputation_methods, self.reference_df, self.simulated_df, **params)
2442
+ self._imputation_future = future
2443
+ self.after(100, lambda: self._poll_imputation_job(future, "benchmark", config))
2444
+
2445
+
2446
+ def _poll_imputation_job(self, future, job, config) -> None:
2447
+ if self._closing:
2448
+ return
2449
+
2450
+ if not future.done():
2451
+ self.after(100, lambda: self._poll_imputation_job(future, job, config))
2452
+ return
2453
+
2454
+ label = self.imputation_label if job == "imputation" else self.benchmark_label
2455
+
2456
+ try:
2457
+ result = future.result()
2458
+
2459
+ if job == "imputation":
2460
+ self.cleaned_df = result
2461
+ self.imputation_config = config
2462
+
2463
+ before = int(self.current_df.isna().sum().sum())
2464
+ after = int(result.isna().sum().sum())
2465
+
2466
+ label.configure(
2467
+ text=f"Method: {config['method']} | Missing before: {before} | Filled: {before-after} | Remaining: {after}. Source unchanged."
2468
+ )
2469
+
2470
+ self.cleaned_export_button.configure(state="normal")
2471
+
2472
+ else:
2473
+ self.benchmark_results = result
2474
+ self.benchmark_config = config
2475
+
2476
+ # Clear previous benchmark results.
2477
+ self.benchmark_table.delete(
2478
+ *self.benchmark_table.get_children()
2479
+ )
2480
+
2481
+ for row in result.itertuples(index=False):
2482
+
2483
+ mae = "—" if pd.isna(row.MAE) else f"{row.MAE:.6g}"
2484
+ rmse = "—" if pd.isna(row.RMSE) else f"{row.RMSE:.6g}"
2485
+ accuracy = (
2486
+ "—" if pd.isna(row.Accuracy)
2487
+ else f"{row.Accuracy:.2%}"
2488
+ )
2489
+
2490
+ self.benchmark_table.insert(
2491
+ "",
2492
+ "end",
2493
+ values=(
2494
+ row.method,
2495
+ mae,
2496
+ rmse,
2497
+ accuracy,
2498
+ row.evaluated_cells
2499
+ )
2500
+ )
2501
+
2502
+ label.configure(
2503
+ text=f"Simulation: {config['simulation_method']} | Lower MAE/RMSE indicates better numerical predictions. Higher Accuracy indicates better categorical predictions."
2504
+ )
2505
+
2506
+ except Exception as exc:
2507
+ label.configure(text=f"{job.capitalize()} failed: {exc}")
2508
+ messagebox.showerror("Operation failed", str(exc))
2509
+
2510
+ finally:
2511
+ self._imputation_future = None
2512
+ self.imputation_button.configure(state="normal")
2513
+
2514
+ if self.reference_df is not None:
2515
+ self.benchmark_button.configure(state="normal")
2516
+
2517
+ def _export_cleaned(self) -> None:
2518
+ if self.cleaned_df is None or self._operation_running():
2519
+ return
2520
+ filename = filedialog.asksaveasfilename(title="Export imputed copy", defaultextension=".csv",
2521
+ filetypes=[("CSV files", "*.csv")], initialfile="missinglab_imputed.csv")
2522
+ if filename:
2523
+ try:
2524
+ export_cleaned_csv(self.cleaned_df, filename, self.source_path)
2525
+ messagebox.showinfo("Export successful", f"Imputed copy saved to:\n{filename}")
2526
+ except Exception as exc:
2527
+ messagebox.showerror("Export failed", str(exc))
2528
+
2529
+ @staticmethod
2530
+ def _report_imputation_parameters(method, params):
2531
+ if method.lower() == "knn":
2532
+ return {"n_neighbors": params["n_neighbors"], "weights": "uniform"}
2533
+ if method.lower() == "iterative":
2534
+ return {"max_iter": params["max_iter"], "random_state": DEFAULT_RANDOM_STATE,
2535
+ "tol": 0.001, "initial_strategy": "mean"}
2536
+ return {}
2537
+
2538
+ def _build_session_section(self, container) -> None:
2539
+ frame = ctk.CTkFrame(container)
2540
+ frame.pack(fill="x", pady=10)
2541
+ ctk.CTkLabel(frame, text="Session Report", font=ctk.CTkFont(size=18, weight="bold"),
2542
+ anchor="w").pack(fill="x", padx=12, pady=(10, 4))
2543
+ ctk.CTkLabel(frame, text="Export current completed results and settings as JSON. No raw dataset rows are included.",
2544
+ anchor="w", justify="left", wraplength=850).pack(fill="x", padx=12, pady=4)
2545
+ ctk.CTkButton(frame, fg_color="#C45A83", hover_color="#A63871", text="Export Session Report (JSON)",
2546
+ command=self._export_session).pack(anchor="w", padx=12, pady=(4, 12))
2547
+
2548
+ def _export_session(self) -> None:
2549
+ if self.current_df is None or self._operation_running():
2550
+ messagebox.showinfo("Session report", "Import a dataset and wait for running operations to finish.")
2551
+ return
2552
+ try:
2553
+ simulation = None
2554
+ if self.simulation_config is not None and self.simulation_comparison is not None:
2555
+ comparison = self.simulation_comparison
2556
+ simulation = {"configuration": self.simulation_config,
2557
+ "overall": comparison["overall"],
2558
+ "by_column": comparison["by_column"].rename_axis("column").reset_index(),
2559
+ "patterns": comparison["patterns"], "co_missingness": comparison["co_missingness"]}
2560
+ evaluation = None if self.evaluation_results is None else {
2561
+ "configuration": self.evaluation_config, "results": self.evaluation_results}
2562
+ imputation = None
2563
+ if self.cleaned_df is not None:
2564
+ before = int(self.current_df.isna().sum().sum())
2565
+ after = int(self.cleaned_df.isna().sum().sum())
2566
+ imputation = {"configuration": self.imputation_config,
2567
+ "missing_before": before, "filled": before - after,
2568
+ "missing_remaining": after, "by_column": column_missingness(self.cleaned_df)}
2569
+ benchmark = None if self.benchmark_results is None else {
2570
+ "configuration": self.benchmark_config, "results": self.benchmark_results}
2571
+ report = build_session_report(self.current_df, self.source_path,
2572
+ mcar=self.mcar_results, simulation=simulation, evaluation=evaluation,
2573
+ imputation=imputation, benchmark=benchmark)
2574
+ filename = filedialog.asksaveasfilename(title="Export session report", defaultextension=".json",
2575
+ filetypes=[("JSON files", "*.json")], initialfile="missinglab_session.json")
2576
+ if filename:
2577
+ export_session_report(report, filename, self.source_path)
2578
+ messagebox.showinfo("Export successful", f"Session report saved to:\n{filename}")
2579
+ except Exception as exc:
2580
+ messagebox.showerror("Export failed", str(exc))
2581
+
2582
+ # ---------------------------------------------------------
2583
+ # CLOSE APPLICATION
2584
+ # ---------------------------------------------------------
2585
+
2586
+ def _close(self) -> None:
2587
+
2588
+ self._closing = True
2589
+
2590
+ self._pool.shutdown(
2591
+ wait=False,
2592
+ cancel_futures=True
2593
+ )
2594
+
2595
+ self.destroy()