clustrust 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.
clustrust/gui/app.py ADDED
@@ -0,0 +1,853 @@
1
+ """ClusTrust main window: data options, settings, background runs, evidence verdict, export."""
2
+ import os
3
+ import queue
4
+ import shutil
5
+ import threading
6
+ import time
7
+ import warnings
8
+ import tkinter as tk
9
+ from tkinter import ttk, filedialog, messagebox
10
+
11
+ import numpy as np
12
+ import pandas as pd
13
+ from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
14
+ from matplotlib.figure import Figure
15
+ from sklearn.decomposition import PCA
16
+
17
+ from clustrust.core.algorithms import ALGORITHMS, SEED
18
+ from clustrust.core.consensus import consensus, point_confidence
19
+ from clustrust.core.defaults import DEFAULTS, PRESETS, value
20
+ from clustrust.core.evidence import evidence_profile, summarize, criteria
21
+ from clustrust.core.indices import silhouette_band
22
+ from clustrust.core.profiles import cluster_profiles
23
+ from clustrust.core.runner import sweep, stability_sweep
24
+ from clustrust.core.stability import cluster_jaccard, jaccard_band
25
+ from clustrust.core.tendency import tendency_check
26
+ from clustrust.gui.tooltip import Tooltip
27
+ from clustrust.io.export import build_config, save_json, save_script
28
+ from clustrust.io.loaders import load_csv, prepare, numeric_frame
29
+
30
+ MAX_ROWS_CONSENSUS = 2000 # the co-association matrix has n x n entries
31
+ VERDICT_COLORS = {"No evidence of clusters": "firebrick",
32
+ "Weak or ambiguous structure": "darkorange",
33
+ "Clear structure": "forestgreen"}
34
+
35
+
36
+ class App(tk.Tk):
37
+ def __init__(self):
38
+ super().__init__()
39
+ self.title("ClusTrust")
40
+ self.geometry("1280x800")
41
+ self.df = self.X = self.num = self.csv_path = None
42
+ self.cols = []
43
+ self.queue = queue.Queue()
44
+ self.run_id = 0
45
+ self.tab_frames = {}
46
+ self._busy = False
47
+ self._busy_since = 0.0
48
+ self._busy_label = ""
49
+ self._tick_id = None
50
+ self._clear_results()
51
+ self._figs = []
52
+ self._settings_hidden = False
53
+ try:
54
+ self.state("zoomed") # start maximised on Windows
55
+ except tk.TclError:
56
+ pass
57
+ self._build()
58
+
59
+ def _clear_results(self):
60
+ self.results = self.stab = self.prof = self.cal = None
61
+ self.summary = self.cons = self.jac = self.ev_used = None
62
+
63
+ # ================= layout helpers =================
64
+ def _combo(self, parent, label, var, values, row, col, width=11):
65
+ ttk.Label(parent, text=label).grid(row=row, column=col, sticky="e", padx=(8, 2), pady=2)
66
+ w = ttk.Combobox(parent, values=values, textvariable=var, width=width, state="readonly")
67
+ w.grid(row=row, column=col + 1, sticky="w", pady=2)
68
+ return w
69
+
70
+ def _spin(self, parent, label, var, lo, hi, row, col, width=6, step=1, fmt=None):
71
+ ttk.Label(parent, text=label).grid(row=row, column=col, sticky="e", padx=(8, 2), pady=2)
72
+ kw = {"format": fmt} if fmt else {}
73
+ w = ttk.Spinbox(parent, from_=lo, to=hi, increment=step, width=width,
74
+ textvariable=var, **kw)
75
+ w.grid(row=row, column=col + 1, sticky="w", pady=2)
76
+ return w
77
+
78
+ def _tip(self, widget, text, key=None):
79
+ if key:
80
+ d = DEFAULTS[key]
81
+ text += f"\nDefault: {d['value']} ({d['kind']}: {d['source']})"
82
+ Tooltip(widget, text)
83
+
84
+ def _tree(self, parent, height=8):
85
+ wrap = ttk.Frame(parent)
86
+ tree = ttk.Treeview(wrap, show="headings", height=height)
87
+ ys = ttk.Scrollbar(wrap, orient="vertical", command=tree.yview)
88
+ xs = ttk.Scrollbar(wrap, orient="horizontal", command=tree.xview)
89
+ tree.configure(yscrollcommand=ys.set, xscrollcommand=xs.set)
90
+ tree.grid(row=0, column=0, sticky="nsew")
91
+ ys.grid(row=0, column=1, sticky="ns")
92
+ xs.grid(row=1, column=0, sticky="ew")
93
+ wrap.rowconfigure(0, weight=1)
94
+ wrap.columnconfigure(0, weight=1)
95
+ return wrap, tree
96
+
97
+ @staticmethod
98
+ def _fill_tree(tree, columns, rows, width=95):
99
+ tree.delete(*tree.get_children())
100
+ tree["columns"] = list(columns)
101
+ for c in columns:
102
+ tree.heading(c, text=str(c))
103
+ tree.column(c, width=width, anchor="center", stretch=False)
104
+ for r in rows:
105
+ tree.insert("", "end", values=list(r))
106
+
107
+ def _tab(self, title):
108
+ frame = ttk.Frame(self.tabs)
109
+ self.tabs.add(frame, text=title)
110
+ self.tab_frames[title] = frame
111
+ return frame
112
+
113
+ def _plot_tab(self, title, size=(6, 5)):
114
+ frame = self._tab(title)
115
+ fig = Figure(figsize=size, dpi=100)
116
+ canvas = FigureCanvasTkAgg(fig, master=frame)
117
+ canvas.get_tk_widget().pack(fill="both", expand=True)
118
+ self._figs.append((fig, canvas))
119
+ return fig, canvas
120
+
121
+ @staticmethod
122
+ def _tidy(fig):
123
+ """tight_layout without the warning when the figure is momentarily too small."""
124
+ with warnings.catch_warnings():
125
+ warnings.simplefilter("ignore")
126
+ try:
127
+ fig.tight_layout()
128
+ except Exception:
129
+ pass
130
+
131
+ def _relayout(self):
132
+ """Re-fit the plots of the tab that is now visible."""
133
+ for fig, cv in self._figs:
134
+ if cv.get_tk_widget().winfo_ismapped():
135
+ self._tidy(fig)
136
+ cv.draw_idle()
137
+
138
+ def toggle_settings(self):
139
+ if self._settings_hidden:
140
+ self.data_box.pack(fill="x", before=self.bar)
141
+ self.settings_box.pack(fill="x", pady=(4, 0), before=self.bar)
142
+ self.btn_hide.config(text="Hide settings")
143
+ else:
144
+ self.data_box.pack_forget()
145
+ self.settings_box.pack_forget()
146
+ self.btn_hide.config(text="Show settings")
147
+ self._settings_hidden = not self._settings_hidden
148
+ self.after(80, self._relayout)
149
+
150
+ def _show_tab(self, title):
151
+ self.tabs.select(self.tab_frames[title])
152
+
153
+ # ================= layout =================
154
+ def _build(self):
155
+ top = ttk.Frame(self, padding=6)
156
+ top.pack(fill="x")
157
+ self._build_data_box(top)
158
+ self._build_settings_box(top)
159
+ self._build_buttons(top)
160
+
161
+ self.status = ttk.Label(self, text="Ready", padding=(8, 0))
162
+ self.status.pack(fill="x")
163
+ self.progress = ttk.Progressbar(self, mode="indeterminate")
164
+ self.progress.pack(fill="x", padx=8, pady=4)
165
+
166
+ self.tabs = ttk.Notebook(self)
167
+ self.tabs.pack(fill="both", expand=True, padx=8, pady=8)
168
+ self.tabs.bind("<<NotebookTabChanged>>", lambda _e: self.after(80, self._relayout))
169
+ self._build_tabs()
170
+
171
+ def _build_data_box(self, parent):
172
+ box = ttk.LabelFrame(parent, text="1. Data", padding=6)
173
+ box.pack(fill="x")
174
+ self.data_box = box
175
+ top_row = ttk.Frame(box)
176
+ top_row.pack(fill="x")
177
+ ttk.Button(top_row, text="Load CSV", command=self.load_file).pack(side="left", padx=4)
178
+ self.file_label = ttk.Label(top_row, text="No file loaded", wraplength=1000,
179
+ justify="left")
180
+ self.file_label.pack(side="left", padx=8, fill="x", expand=True)
181
+
182
+ opts = ttk.Frame(box)
183
+ opts.pack(fill="x", pady=(4, 0))
184
+ self.scale_var = tk.StringVar(value="standard")
185
+ self.missing_var = tk.StringVar(value="drop")
186
+ self.pca_var = tk.IntVar(value=0)
187
+ self.log1p_var = tk.BooleanVar(value=False)
188
+ cb_scale = self._combo(opts, "Scaling", self.scale_var,
189
+ ["standard", "robust", "minmax", "none"], 0, 0)
190
+ cb_missing = self._combo(opts, "Missing values", self.missing_var,
191
+ ["drop", "median"], 0, 2, 8)
192
+ sp_pca = self._spin(opts, "PCA components (0 = off)", self.pca_var, 0, 50, 0, 4, width=4)
193
+ ck_log = ttk.Checkbutton(opts, text="log(1 + x) first", variable=self.log1p_var)
194
+ ck_log.grid(row=0, column=6, padx=8)
195
+ ttk.Button(opts, text="Apply to data", command=self.apply_prep).grid(
196
+ row=0, column=7, padx=8)
197
+
198
+ self._tip(cb_scale, "Standard: mean 0, spread 1. Robust: uses the median, less sensitive to "
199
+ "outliers. MinMax: squeezes every column to 0-1.")
200
+ self._tip(cb_missing, "Drop removes rows with missing values. Median fills them with the "
201
+ "column median.")
202
+ self._tip(sp_pca, "Reduces the data to this many components before clustering. 0 = no reduction.")
203
+ self._tip(ck_log, "Applies log(1 + x) to every column first. Useful for skewed, non-negative "
204
+ "data such as spending.")
205
+
206
+ def _build_settings_box(self, parent):
207
+ box = ttk.LabelFrame(parent, text="2. Settings", padding=6)
208
+ self.settings_box = box
209
+ box.pack(fill="x", pady=(4, 0))
210
+ self.algo_vars = {}
211
+ for i, name in enumerate(ALGORITHMS):
212
+ var = tk.BooleanVar(value=True)
213
+ self.algo_vars[name] = var
214
+ ttk.Checkbutton(box, text=name, variable=var).grid(row=0, column=i, padx=4, sticky="w")
215
+ self.kmin, self.kmax = tk.IntVar(value=2), tk.IntVar(value=8)
216
+ self.seed = tk.IntVar(value=SEED)
217
+ self._spin(box, "k min", self.kmin, 2, 30, 0, 3, width=4)
218
+ self._spin(box, "k max", self.kmax, 3, 30, 0, 5, width=4)
219
+ sp_seed = self._spin(box, "seed", self.seed, 0, 999999, 0, 7, width=8)
220
+ self._tip(sp_seed, "One random seed is used for every random step, so a run can be repeated exactly.")
221
+
222
+ # run size
223
+ self.preset_var = tk.StringVar(value="quick")
224
+ self.n_rounds_var = tk.IntVar(value=PRESETS["quick"]["n_rounds"])
225
+ self.n_null_var = tk.IntVar(value=PRESETS["quick"]["n_null"])
226
+ self.null_var = tk.StringVar(value=PRESETS["quick"]["null_model"])
227
+ self.jobs_var = tk.IntVar(value=1)
228
+ cb_preset = self._combo(box, "Run size", self.preset_var, ["quick", "literature"], 1, 0, 10)
229
+ cb_preset.bind("<<ComboboxSelected>>", lambda _e: self._apply_preset(self.preset_var.get()))
230
+ sp_rounds = self._spin(box, "Resamples", self.n_rounds_var, 5, 1000, 1, 2)
231
+ sp_null = self._spin(box, "Null sets", self.n_null_var, 5, 1000, 1, 4)
232
+ cb_null = self._combo(box, "Null model", self.null_var,
233
+ ["gaussian", "pca_uniform", "both"], 1, 6)
234
+ sp_jobs = self._spin(box, "Parallel jobs", self.jobs_var, 1, 8, 1, 8, width=3)
235
+ self._tip(cb_preset, "Quick: 20 resamples, 20 null sets, Gaussian null. For exploring.\n"
236
+ "Literature: 100 resamples, 100 null sets, both nulls. Much slower.")
237
+ self._tip(sp_rounds, "How many times the data is resampled for stability and consensus.",
238
+ "n_rounds")
239
+ self._tip(sp_null, "How many structureless datasets each score is compared with.", "n_null")
240
+ self._tip(cb_null, "Structureless reference data. Gaussian keeps the data's means and "
241
+ "correlations; pca_uniform is uniform in the box around the principal axes; "
242
+ "both requires a result to beat both.", "null_model")
243
+ self._tip(sp_jobs, "Null datasets run in parallel. Keep at 1 unless you have tested more on "
244
+ "your computer.")
245
+
246
+ # verdict thresholds
247
+ self.z_var = tk.DoubleVar(value=value("z_cutoff"))
248
+ self.minidx_var = tk.IntVar(value=value("min_indices"))
249
+ self.stab_var = tk.DoubleVar(value=value("stability_ari"))
250
+ self.agree_var = tk.DoubleVar(value=value("agreement_ari"))
251
+ sp_z = self._spin(box, "z cutoff", self.z_var, 0.5, 10, 2, 0, 5, 0.5, "%.1f")
252
+ sp_mi = self._spin(box, "Indices needed", self.minidx_var, 1, 3, 2, 2, width=3)
253
+ sp_st = self._spin(box, "Stability min", self.stab_var, 0, 1, 2, 4, 5, 0.05, "%.2f")
254
+ sp_ag = self._spin(box, "Agreement min", self.agree_var, 0, 1, 2, 6, 5, 0.05, "%.2f")
255
+ ttk.Button(box, text="Update verdict", command=self._refresh_verdict).grid(
256
+ row=2, column=8, padx=6)
257
+ ttk.Button(box, text="Literature defaults", command=self.literature_defaults).grid(
258
+ row=2, column=9, padx=6)
259
+ self._tip(sp_z, "A score beats the null data when its z-score is above this. "
260
+ "Two standard deviations is a statistical convention.", "z_cutoff")
261
+ self._tip(sp_mi, "How many of the 3 indices must beat the null for a k to count.", "min_indices")
262
+ self._tip(sp_st, "Minimum mean agreement (adjusted Rand index) between resampled solutions.",
263
+ "stability_ari")
264
+ self._tip(sp_ag, "Minimum mean agreement (adjusted Rand index) between algorithms.",
265
+ "agreement_ari")
266
+
267
+ # consensus
268
+ self.cons_algo = tk.StringVar(value=ALGORITHMS[0])
269
+ self.cons_k = tk.IntVar(value=3)
270
+ cb_ca = self._combo(box, "Consensus algorithm", self.cons_algo, list(ALGORITHMS), 3, 0, 14)
271
+ sp_ck = self._spin(box, "Consensus k", self.cons_k, 2, 30, 3, 2, width=4)
272
+ self._tip(cb_ca, "Algorithm used for the resamples behind consensus, PAC and point confidence.")
273
+ self._tip(sp_ck, "Number of groups for the consensus clustering. Filled in with the best "
274
+ "supported k after an evidence run.")
275
+
276
+ def _build_buttons(self, parent):
277
+ bar = ttk.Frame(parent)
278
+ self.bar = bar
279
+ bar.pack(fill="x", pady=(6, 0))
280
+ self.btn_tend = ttk.Button(bar, text="Check tendency", command=self.run_tendency)
281
+ self.btn_indices = ttk.Button(bar, text="Run indices", command=self.run_indices)
282
+ self.btn_stab = ttk.Button(bar, text="Run stability", command=self.run_stability)
283
+ self.btn_cons = ttk.Button(bar, text="Run consensus", command=self.run_consensus)
284
+ self.btn_ev = ttk.Button(bar, text="Run evidence analysis", command=self.run_evidence)
285
+ self.btn_export = ttk.Button(bar, text="Export session", command=self.export_session)
286
+ self.btn_stop = ttk.Button(bar, text="Stop waiting", command=self.stop_waiting,
287
+ state="disabled")
288
+ self._run_buttons = [self.btn_tend, self.btn_indices, self.btn_stab, self.btn_cons,
289
+ self.btn_ev, self.btn_export]
290
+ for b in self._run_buttons + [self.btn_stop]:
291
+ b.pack(side="left", padx=4)
292
+ self.btn_hide = ttk.Button(bar, text="Hide settings", command=self.toggle_settings)
293
+ self.btn_hide.pack(side="right", padx=4)
294
+ self._tip(self.btn_tend, "Tests whether the data has any group structure before clustering. "
295
+ "A Hopkins statistic above 0.75 suggests clustering tendency.",
296
+ "hopkins_tendency")
297
+ self._tip(self.btn_indices, "Scores every algorithm for every k. Silhouette and "
298
+ "Calinski-Harabasz: higher is better. Davies-Bouldin: lower is better.")
299
+ self._tip(self.btn_stab, "Re-clusters random 80% samples and checks whether the groups stay "
300
+ "the same. Close to 1 means reproducible.", "subsample_fraction")
301
+ self._tip(self.btn_cons, "Counts how often each pair of rows lands in the same group across "
302
+ "resamples, and builds a final grouping, a confidence per point and "
303
+ "a stability per cluster.")
304
+ self._tip(self.btn_ev, "Compares every score with random data that has no groups, adds "
305
+ "stability, PAC and agreement between algorithms, and gives a verdict.")
306
+ self._tip(self.btn_export, "Saves the settings, parameter sources, results and a script that "
307
+ "repeats the analysis.")
308
+ self._tip(self.btn_stop, "Stops waiting for the current run. The computation finishes quietly "
309
+ "in the background and its result is thrown away.")
310
+
311
+ def _build_tabs(self):
312
+ idx = self._tab("Indices")
313
+ wrap, self.table = self._tree(idx, height=8)
314
+ wrap.pack(fill="x", padx=6, pady=4)
315
+ self.fig_idx = Figure(figsize=(6, 5), dpi=100)
316
+ self.cv_idx = FigureCanvasTkAgg(self.fig_idx, master=idx)
317
+ self.cv_idx.get_tk_widget().pack(fill="both", expand=True)
318
+ self._figs.append((self.fig_idx, self.cv_idx))
319
+
320
+ self.fig_stab, self.cv_stab = self._plot_tab("Stability")
321
+ self.fig_cons, self.cv_cons = self._plot_tab("Consensus")
322
+
323
+ ev = self._tab("Evidence")
324
+ self.verdict_label = ttk.Label(ev, text="Run the evidence analysis to see the verdict.",
325
+ font=("TkDefaultFont", 12, "bold"), padding=(8, 6),
326
+ wraplength=900)
327
+ self.verdict_label.pack(fill="x")
328
+ self.reason_label = ttk.Label(ev, text="", wraplength=900, padding=(8, 0))
329
+ self.reason_label.pack(fill="x")
330
+ wrap, self.ev_table = self._tree(ev, height=12)
331
+ wrap.pack(fill="both", expand=True, padx=6, pady=4)
332
+ self.fig_ev, self.cv_ev = self._plot_tab("Evidence plots", (6, 6))
333
+
334
+ tend = self._tab("Tendency")
335
+ self.tend_label = ttk.Label(tend, wraplength=900, padding=8,
336
+ text="Press 'Check tendency' to test whether the data has any "
337
+ "group structure.")
338
+ self.tend_label.pack(fill="x")
339
+ self.fig_tend = Figure(figsize=(6, 4), dpi=100)
340
+ self.cv_tend = FigureCanvasTkAgg(self.fig_tend, master=tend)
341
+ self.cv_tend.get_tk_widget().pack(fill="both", expand=True)
342
+ self._figs.append((self.fig_tend, self.cv_tend))
343
+
344
+ prof = self._tab("Profiles")
345
+ self.prof_label = ttk.Label(prof, wraplength=900, padding=8,
346
+ text="Run consensus to see what each cluster looks like and "
347
+ "how far to trust it.")
348
+ self.prof_label.pack(fill="x")
349
+ wrap, self.prof_table = self._tree(prof, height=12)
350
+ wrap.pack(fill="both", expand=True, padx=6, pady=4)
351
+
352
+ # ================= data =================
353
+ def load_file(self):
354
+ path = filedialog.askopenfilename(filetypes=[("CSV files", "*.csv")])
355
+ if not path:
356
+ return
357
+ try:
358
+ df = load_csv(path)
359
+ self._prepare(df)
360
+ except Exception as e:
361
+ messagebox.showerror("Could not load file", str(e))
362
+ return
363
+ self.df, self.csv_path = df, path
364
+ self._clear_results()
365
+ self._show_data_label()
366
+ self.status.config(text="File loaded. Choose settings and run.")
367
+
368
+ def _prepare(self, df):
369
+ missing = self.missing_var.get()
370
+ X, cols = prepare(df, scale=self.scale_var.get(), missing=missing,
371
+ pca=self.pca_var.get() or None, log1p=self.log1p_var.get())
372
+ self.num = numeric_frame(df, missing) # original units, used by the Profiles tab
373
+ self.X, self.cols = X, cols
374
+
375
+ def _show_data_label(self):
376
+ cols = list(self.cols)
377
+ shown = ", ".join(cols[:8]) + (f", ... (+{len(cols) - 8} more)" if len(cols) > 8 else "")
378
+ self.file_label.config(text=f"{self.csv_path} | {self.X.shape[0]} rows, "
379
+ f"{len(cols)} columns used: {shown}")
380
+
381
+ def apply_prep(self):
382
+ if self.df is None:
383
+ messagebox.showinfo("No data", "Load a CSV file first.")
384
+ return
385
+ try:
386
+ self._prepare(self.df)
387
+ except Exception as e:
388
+ messagebox.showerror("Could not apply options", str(e))
389
+ return
390
+ self._clear_results()
391
+ self._show_data_label()
392
+ self.status.config(text="Data options applied. Earlier results used the old options; run again.")
393
+
394
+ # ================= settings =================
395
+ def _apply_preset(self, name):
396
+ p = PRESETS[name]
397
+ self.n_rounds_var.set(p["n_rounds"])
398
+ self.n_null_var.set(p["n_null"])
399
+ self.null_var.set(p["null_model"])
400
+
401
+ def literature_defaults(self):
402
+ self.preset_var.set("literature")
403
+ self._apply_preset("literature")
404
+ self.z_var.set(value("z_cutoff"))
405
+ self.minidx_var.set(value("min_indices"))
406
+ self.stab_var.set(value("stability_ari"))
407
+ self.agree_var.set(value("agreement_ari"))
408
+ self.status.config(text="Literature defaults restored. Sources are in the tooltips and session.json.")
409
+
410
+ def _read_settings(self):
411
+ if self.X is None:
412
+ messagebox.showinfo("No data", "Load a CSV file first.")
413
+ return None
414
+ algos = [n for n, v in self.algo_vars.items() if v.get()]
415
+ if not algos:
416
+ messagebox.showinfo("No algorithm", "Select at least one algorithm.")
417
+ return None
418
+ try:
419
+ s = {"algos": algos, "kmin": self.kmin.get(), "kmax": self.kmax.get(),
420
+ "seed": self.seed.get(), "n_rounds": self.n_rounds_var.get(),
421
+ "n_null": self.n_null_var.get(), "null": self.null_var.get(),
422
+ "jobs": self.jobs_var.get()}
423
+ except tk.TclError:
424
+ messagebox.showerror("Invalid input", "k range, seed, resamples, null sets and jobs "
425
+ "must be whole numbers.")
426
+ return None
427
+ if s["kmin"] < 2 or s["kmax"] <= s["kmin"] or s["kmax"] >= len(self.X):
428
+ messagebox.showerror("Invalid k range", "Need 2 <= k min < k max < number of rows.")
429
+ return None
430
+ if s["n_rounds"] < 5 or s["n_null"] < 5 or s["jobs"] < 1:
431
+ messagebox.showerror("Invalid input", "Use at least 5 resamples, 5 null sets and 1 job.")
432
+ return None
433
+ return s
434
+
435
+ def _read_thresholds(self):
436
+ try:
437
+ thr = {"z": self.z_var.get(), "min_indices": self.minidx_var.get(),
438
+ "stability": self.stab_var.get(), "agreement": self.agree_var.get()}
439
+ except tk.TclError:
440
+ messagebox.showerror("Invalid input", "Thresholds must be numbers.")
441
+ return None
442
+ if not (1 <= thr["min_indices"] <= 3):
443
+ messagebox.showerror("Invalid input", "Indices needed must be 1, 2 or 3.")
444
+ return None
445
+ return thr
446
+
447
+ def _too_many_rows(self):
448
+ if len(self.X) > MAX_ROWS_CONSENSUS:
449
+ messagebox.showinfo("Too many rows",
450
+ f"Consensus builds an n x n matrix. The limit is {MAX_ROWS_CONSENSUS} "
451
+ f"rows (this file has {len(self.X)}). Use a smaller sample.")
452
+ return True
453
+ return False
454
+
455
+ # ================= background runs =================
456
+ def _set_busy(self, busy, text=None):
457
+ self._busy = busy
458
+ for b in self._run_buttons:
459
+ b.config(state="disabled" if busy else "normal")
460
+ self.btn_stop.config(state="normal" if busy else "disabled")
461
+ if busy:
462
+ self._busy_label = text or "Running..."
463
+ self._busy_since = time.time()
464
+ self.progress.start(10)
465
+ self._tick()
466
+ else:
467
+ self.progress.stop()
468
+ if self._tick_id is not None:
469
+ self.after_cancel(self._tick_id)
470
+ self._tick_id = None
471
+ if text:
472
+ self.status.config(text=text)
473
+
474
+ def _tick(self):
475
+ if not self._busy:
476
+ return
477
+ self.status.config(text=f"{self._busy_label} [{int(time.time() - self._busy_since)} s]")
478
+ self._tick_id = self.after(1000, self._tick)
479
+
480
+ def _start(self, label, func, on_done):
481
+ """Run func() in a background thread; call on_done(result) in the GUI thread."""
482
+ self.run_id += 1
483
+ rid = self.run_id
484
+ self._set_busy(True, label)
485
+
486
+ def worker(): # background thread: never touch the GUI here
487
+ try:
488
+ self.queue.put((rid, "done", func(), on_done))
489
+ except Exception as e:
490
+ self.queue.put((rid, "error", str(e), None))
491
+
492
+ threading.Thread(target=worker, daemon=True).start()
493
+ self.after(100, self._poll)
494
+
495
+ def _poll(self):
496
+ try:
497
+ rid, kind, payload, on_done = self.queue.get_nowait()
498
+ except queue.Empty:
499
+ self.after(100, self._poll)
500
+ return
501
+ if rid != self.run_id: # a run the user stopped waiting for: discard it
502
+ return
503
+ elapsed = time.time() - self._busy_since
504
+ self._set_busy(False)
505
+ if kind == "error":
506
+ self.status.config(text="Error")
507
+ messagebox.showerror("Run failed", payload)
508
+ else:
509
+ on_done(payload)
510
+ self.status.config(text=self.status.cget("text") + f" ({elapsed:.0f} s)")
511
+
512
+ def stop_waiting(self):
513
+ self.run_id += 1
514
+ self._set_busy(False, "Stopped waiting. The background job finishes quietly and its "
515
+ "result is discarded.")
516
+
517
+ # ================= indices =================
518
+ def run_indices(self):
519
+ s = self._read_settings()
520
+ if s is None:
521
+ return
522
+ X = self.X
523
+ self._start("Running indices...",
524
+ lambda: sweep(X, algorithms=s["algos"],
525
+ k_range=range(s["kmin"], s["kmax"] + 1), seed=s["seed"]),
526
+ self._show_indices)
527
+
528
+ def _show_indices(self, res):
529
+ self.results = res
530
+ self.status.config(text=f"Indices done: {len(res)} clusterings scored.")
531
+ rows = [(r["algorithm"], int(r["k"]), f"{r['silhouette']:.3f}",
532
+ silhouette_band(r["silhouette"]), f"{r['calinski_harabasz']:.1f}",
533
+ f"{r['davies_bouldin']:.3f}")
534
+ for _, r in res.sort_values("silhouette", ascending=False).iterrows()]
535
+ self._fill_tree(self.table, ("algorithm", "k", "silhouette", "meaning",
536
+ "calinski_harabasz", "davies_bouldin"), rows, 88)
537
+ self.fig_idx.clear()
538
+ metrics = [("silhouette", "higher is better"), ("calinski_harabasz", "higher is better"),
539
+ ("davies_bouldin", "lower is better")]
540
+ for i, (m, note) in enumerate(metrics, start=1):
541
+ ax = self.fig_idx.add_subplot(3, 1, i)
542
+ for name, grp in res.groupby("algorithm"):
543
+ ax.plot(grp["k"], grp[m], marker="o", label=name)
544
+ ax.set_ylabel(m, fontsize=8)
545
+ ax.set_title(note, fontsize=8)
546
+ ax.set_xlabel("k" if i == 3 else "")
547
+ if i == 1:
548
+ ax.legend(fontsize=7)
549
+ self._tidy(self.fig_idx)
550
+ self.cv_idx.draw()
551
+ self._show_tab("Indices")
552
+
553
+ # ================= stability =================
554
+ def run_stability(self):
555
+ s = self._read_settings()
556
+ if s is None:
557
+ return
558
+ X = self.X
559
+ self._start("Running stability (resampling)...",
560
+ lambda: stability_sweep(X, algorithms=s["algos"],
561
+ k_range=range(s["kmin"], s["kmax"] + 1),
562
+ n_rounds=s["n_rounds"], seed=s["seed"]),
563
+ self._show_stability)
564
+
565
+ def _show_stability(self, res):
566
+ self.stab = res
567
+ self.status.config(text="Stability done. Values near 1 mean the groups are reproducible.")
568
+ self.fig_stab.clear()
569
+ ax = self.fig_stab.add_subplot(1, 1, 1)
570
+ for name, grp in res.groupby("algorithm"):
571
+ ax.errorbar(grp["k"], grp["stability_mean"], yerr=grp["stability_std"],
572
+ marker="o", capsize=3, label=name)
573
+ ax.axhline(self.stab_var.get(), color="gray", linestyle="--", linewidth=0.8)
574
+ ax.set_xlabel("k")
575
+ ax.set_ylabel("stability (mean ARI over resamples)")
576
+ ax.set_title("Higher = groups change less when the data changes (dashed: minimum)")
577
+ ax.set_ylim(min(0.0, res["stability_mean"].min() - 0.1), 1.05)
578
+ ax.legend(fontsize=8)
579
+ self._tidy(self.fig_stab)
580
+ self.cv_stab.draw()
581
+ self._show_tab("Stability")
582
+
583
+ # ================= consensus, point confidence, profiles =================
584
+ def run_consensus(self):
585
+ s = self._read_settings()
586
+ if s is None or self._too_many_rows():
587
+ return
588
+ try:
589
+ k = self.cons_k.get()
590
+ except tk.TclError:
591
+ messagebox.showerror("Invalid input", "Consensus k must be a whole number.")
592
+ return
593
+ if k < 2 or k >= len(self.X):
594
+ messagebox.showerror("Invalid k", "Need 2 <= k < number of rows.")
595
+ return
596
+ algo, X, num = self.cons_algo.get(), self.X, self.num
597
+
598
+ def job():
599
+ labels, C = consensus(algo, X, k, n_rounds=s["n_rounds"], seed=s["seed"])
600
+ jac = cluster_jaccard(algo, X, k, n_rounds=s["n_rounds"], seed=s["seed"],
601
+ reference=labels)
602
+ return labels, C, jac
603
+
604
+ self._start("Running consensus...", job,
605
+ lambda res: self._show_consensus(res, algo, k, X, num))
606
+
607
+ def _show_consensus(self, res, algo, k, X, num):
608
+ labels, C, jac = res
609
+ conf = point_confidence(C, labels)
610
+ self.cons = {"labels": labels, "C": C, "conf": conf, "algo": algo, "k": k}
611
+ self.jac = jac
612
+ order = np.argsort(labels, kind="stable")
613
+ self.status.config(text=f"Consensus done ({algo}, k={k}). "
614
+ f"Group sizes: {np.bincount(labels).tolist()}")
615
+ self.fig_cons.clear()
616
+ ax = self.fig_cons.add_subplot(1, 2, 1)
617
+ im = ax.imshow(C[np.ix_(order, order)], vmin=0, vmax=1, cmap="viridis")
618
+ ax.set_title("Co-association matrix\nbright blocks = trustworthy groups", fontsize=8)
619
+ ax.set_xlabel("rows sorted by group", fontsize=8)
620
+ self.fig_cons.colorbar(im, ax=ax, fraction=0.046)
621
+ ax2 = self.fig_cons.add_subplot(1, 2, 2)
622
+ if X.shape[1] >= 2:
623
+ P = PCA(n_components=2).fit_transform(X)
624
+ sc = ax2.scatter(P[:, 0], P[:, 1], c=conf, cmap="RdYlGn", vmin=0, vmax=1, s=10)
625
+ ax2.set_xlabel("PC1", fontsize=8)
626
+ ax2.set_ylabel("PC2", fontsize=8)
627
+ self.fig_cons.colorbar(sc, ax=ax2, fraction=0.046)
628
+ ax2.set_title("Point confidence\n(1 = always with its group)", fontsize=8)
629
+ self._tidy(self.fig_cons)
630
+ self.cv_cons.draw()
631
+ self._show_profiles(num, labels, conf, jac, k)
632
+ self._show_tab("Consensus")
633
+
634
+ def _show_profiles(self, num, labels, conf, jac, k):
635
+ means, sep = cluster_profiles(num, labels)
636
+ mean_conf = pd.Series(conf).groupby(labels).mean()
637
+ jac = jac.set_index("cluster")
638
+ features = list(means.columns[1:])
639
+ columns = ["cluster", "size", "confidence", "jaccard", "trust"] + features
640
+ rows = []
641
+ for cl, row in means.iterrows():
642
+ j = float(jac.loc[cl, "mean_jaccard"]) if cl in jac.index else float("nan")
643
+ c = mean_conf.get(cl, float("nan"))
644
+ rows.append([int(cl), int(row["size"]), f"{c:.2f}", f"{j:.2f}",
645
+ jaccard_band(j) if j == j else "n/a"] + [f"{row[f]:.3f}" for f in features])
646
+ self._fill_tree(self.prof_table, columns, rows, 88)
647
+ top = ", ".join(f"{n} ({v:.2f})" for n, v in sep.head(3).items())
648
+ dissolved = [int(c) for c in jac.index if bool(jac.loc[c, "dissolved"])]
649
+ msg = (f"k = {k}. Feature means are in original units. Features that best separate the "
650
+ f"clusters (share of variance explained): {top}.")
651
+ if dissolved:
652
+ msg += f" Dissolved clusters, do not rely on them: {dissolved}."
653
+ verdict = self.summary["verdict"] if self.summary else None
654
+ if verdict is None:
655
+ lead, color = ("The evidence analysis has not been run, so it is not known whether "
656
+ "these clusters are real.", "darkorange")
657
+ elif verdict == "No evidence of clusters":
658
+ lead, color = ("WARNING: the evidence analysis found no evidence of clusters in this "
659
+ "data. These groups only come from forcing k clusters; high stability "
660
+ "or confidence here does not show that real clusters exist.", "firebrick")
661
+ else:
662
+ lead, color = (f"Evidence verdict: {verdict}.", "black")
663
+ self.prof_label.config(text=f"{lead} {msg}", foreground=color)
664
+
665
+ # ================= tendency =================
666
+ def run_tendency(self):
667
+ if self.X is None:
668
+ messagebox.showinfo("No data", "Load a CSV file first.")
669
+ return
670
+ try:
671
+ n_null, seed = self.n_null_var.get(), self.seed.get()
672
+ except tk.TclError:
673
+ messagebox.showerror("Invalid input", "Null sets and seed must be whole numbers.")
674
+ return
675
+ X = self.X
676
+ self._start("Checking clustering tendency...",
677
+ lambda: tendency_check(X, n_null=n_null, seed=seed),
678
+ lambda t: self._show_tendency(t, X))
679
+
680
+ def _show_tendency(self, t, X):
681
+ cutoff, zcut = value("hopkins_tendency"), self.z_var.get()
682
+ h, z = t["hopkins"], t["hopkins_z"]
683
+ beats_null = bool(np.isfinite(z) and z > zcut)
684
+ lines = [f"Hopkins statistic: {h:.3f}. The literature reads values above {cutoff} as "
685
+ "clustering tendency; that rule assumes evenly spread (uniform) data as the baseline.",
686
+ f"Structureless data with the same means and correlations scores "
687
+ f"{t['null_mean']:.3f} +/- {t['null_std']:.3f} (z = {z:.1f})."]
688
+ if t["dip_p"] is not None:
689
+ lines.append(f"Dip test on the first principal component: p = {t['dip_p']:.3f}")
690
+ else:
691
+ lines.append("Dip test not run (package diptest is not installed).")
692
+ if h > cutoff and beats_null:
693
+ lines.append("Clustering tendency: above the literature cutoff and above structureless data.")
694
+ color = "forestgreen"
695
+ elif h > cutoff:
696
+ lines.append("Above the literature cutoff, but structureless data with the same means and "
697
+ "correlations scores about as high, so this is not evidence of clusters.")
698
+ color = "darkorange"
699
+ elif beats_null:
700
+ lines.append("Below the literature cutoff, but more clustered than structureless data.")
701
+ color = "darkorange"
702
+ else:
703
+ lines.append("No clear clustering tendency. Be careful with any clusters found.")
704
+ color = "firebrick"
705
+ self.tend_label.config(text="\n".join(lines), foreground=color)
706
+ self.fig_tend.clear()
707
+ ax = self.fig_tend.add_subplot(1, 1, 1)
708
+ if X.shape[1] >= 2:
709
+ P = PCA(n_components=2).fit_transform(X)
710
+ ax.scatter(P[:, 0], P[:, 1], s=8, alpha=0.6)
711
+ ax.set_xlabel("PC1")
712
+ ax.set_ylabel("PC2")
713
+ else:
714
+ ax.hist(X[:, 0], bins=30)
715
+ ax.set_title("Look for visible groups", fontsize=9)
716
+ self._tidy(self.fig_tend)
717
+ self.cv_tend.draw()
718
+ self.status.config(text="Tendency check done.")
719
+ self._show_tab("Tendency")
720
+
721
+ # ================= evidence =================
722
+ def run_evidence(self):
723
+ s = self._read_settings()
724
+ if s is None or self._too_many_rows():
725
+ return
726
+ X, cons_algo = self.X, self.cons_algo.get()
727
+ label = (f"Running evidence analysis ({s['n_null']} null sets, {s['n_rounds']} resamples, "
728
+ f"{s['null']} null)...")
729
+ self._start(label,
730
+ lambda: evidence_profile(X, algorithms=s["algos"],
731
+ k_range=range(s["kmin"], s["kmax"] + 1),
732
+ n_null=s["n_null"], n_rounds=s["n_rounds"],
733
+ seed=s["seed"], cons_algo=cons_algo,
734
+ null=s["null"], n_jobs=s["jobs"]),
735
+ lambda res: self._show_evidence(res, dict(s, cons_algo=cons_algo)))
736
+
737
+ def _show_evidence(self, res, used):
738
+ self.prof, self.cal = res
739
+ self.ev_used = used
740
+ self._refresh_verdict()
741
+ self._show_tab("Evidence")
742
+
743
+ def _refresh_verdict(self):
744
+ if self.prof is None:
745
+ messagebox.showinfo("No evidence yet", "Run the evidence analysis first.")
746
+ return
747
+ thr = self._read_thresholds()
748
+ if thr is None:
749
+ return
750
+ s = summarize(self.prof, **thr)
751
+ crit = criteria(self.prof, **thr)
752
+ self.summary = s
753
+ best = f" (best supported k = {s['best_k']})" if s["best_k"] is not None else ""
754
+ self.verdict_label.config(text=s["verdict"] + best,
755
+ foreground=VERDICT_COLORS.get(s["verdict"], "black"))
756
+ self.reason_label.config(text=s["reason"])
757
+ if s["best_k"] is not None:
758
+ self.cons_k.set(s["best_k"])
759
+
760
+ zcols = [c for c in self.prof.columns if c.endswith("_z")]
761
+ rows = []
762
+ for i, r in self.prof.iterrows():
763
+ mark = "yes" if bool(crit.loc[i, "passes"]) else "no"
764
+ if s["best_k"] is not None and int(r["k"]) == s["best_k"]:
765
+ mark += " *"
766
+ agr = "n/a" if pd.isna(r["agreement"]) else f"{r['agreement']:.2f}"
767
+ rows.append([int(r["k"])] + [f"{r[c]:.1f}" for c in zcols] +
768
+ [f"{r['stability']:.2f}", f"{r['pac']:.3f}", agr, mark])
769
+ self._fill_tree(self.ev_table, ["k"] + [c[:-2] + " z" for c in zcols] +
770
+ ["stability", "PAC", "agreement", "passes"], rows, 100)
771
+
772
+ grid = self.prof.set_index("k")[zcols].T
773
+ self.fig_ev.clear()
774
+ ax = self.fig_ev.add_subplot(2, 1, 1)
775
+ im = ax.imshow(grid.to_numpy(), aspect="auto", cmap="RdYlGn", vmin=-5, vmax=10)
776
+ ax.set_xticks(range(grid.shape[1]))
777
+ ax.set_xticklabels(list(grid.columns))
778
+ ax.set_yticks(range(grid.shape[0]))
779
+ ax.set_yticklabels([c[:-2] for c in grid.index], fontsize=8)
780
+ for i in range(grid.shape[0]):
781
+ for j in range(grid.shape[1]):
782
+ ax.text(j, i, f"{grid.iat[i, j]:.1f}", ha="center", va="center", fontsize=8)
783
+ ax.set_title(f"z-score against null data (above {thr['z']} beats noise; "
784
+ "Davies-Bouldin flipped)", fontsize=8)
785
+ self.fig_ev.colorbar(im, ax=ax, fraction=0.046)
786
+ ax2 = self.fig_ev.add_subplot(2, 1, 2)
787
+ ks = self.prof["k"]
788
+ ax2.plot(ks, self.prof["stability"], marker="o", label="stability")
789
+ ax2.plot(ks, self.prof["agreement"], marker="s", label="agreement")
790
+ ax2.plot(ks, self.prof["pac"], marker="^", linestyle=":", label="PAC (lower is better)")
791
+ ax2.axhline(thr["stability"], color="C0", linestyle="--", linewidth=0.8)
792
+ ax2.axhline(thr["agreement"], color="C1", linestyle="--", linewidth=0.8)
793
+ ax2.set_xlabel("k")
794
+ ax2.set_ylim(-0.05, 1.05)
795
+ ax2.legend(fontsize=7)
796
+ self._tidy(self.fig_ev)
797
+ self.cv_ev.draw()
798
+ self.status.config(text=f"Verdict: {s['verdict']}")
799
+
800
+ # ================= export =================
801
+ def _changed_since_evidence(self, s):
802
+ cur = dict(s, cons_algo=self.cons_algo.get())
803
+ used = {k: v for k, v in self.ev_used.items() if k != "jobs"}
804
+ return any(cur.get(k) != v for k, v in used.items())
805
+
806
+ def export_session(self):
807
+ s = self._read_settings()
808
+ if s is None:
809
+ return
810
+ thr = self._read_thresholds()
811
+ if thr is None:
812
+ return
813
+ if self.ev_used is not None and self._changed_since_evidence(s):
814
+ if not messagebox.askyesno("Settings changed",
815
+ "The settings changed since the last evidence run, so the "
816
+ "replay script will not match the results shown. "
817
+ "Export the current settings anyway?"):
818
+ return
819
+ folder = filedialog.askdirectory(title="Choose a folder for the export")
820
+ if not folder:
821
+ return
822
+ cons_algo = self.cons["algo"] if self.cons else self.cons_algo.get()
823
+ cons_k = self.cons["k"] if self.cons else self.cons_k.get()
824
+ try:
825
+ dest = os.path.join(folder, os.path.basename(self.csv_path))
826
+ if os.path.abspath(dest) != os.path.abspath(self.csv_path):
827
+ shutil.copy2(self.csv_path, dest) # the data travels with the export
828
+ cfg = build_config(os.path.basename(self.csv_path), self.cols, self.scale_var.get(),
829
+ s["algos"], s["kmin"], s["kmax"], s["seed"], s["n_null"],
830
+ cons_algo, cons_k, missing=self.missing_var.get(),
831
+ pca=self.pca_var.get() or None, log1p=self.log1p_var.get(),
832
+ n_rounds=s["n_rounds"], null=s["null"], thresholds=thr,
833
+ preset=self.preset_var.get())
834
+ save_json(cfg, os.path.join(folder, "session.json"), self.summary)
835
+ save_script(cfg, os.path.join(folder, "replay.py"))
836
+ for name, df in (("indices.csv", self.results), ("stability.csv", self.stab),
837
+ ("evidence_profile.csv", self.prof), ("calibrated.csv", self.cal),
838
+ ("cluster_trust.csv", self.jac)):
839
+ if df is not None:
840
+ df.to_csv(os.path.join(folder, name), index=False)
841
+ if self.cons is not None and len(self.cons["labels"]) == len(self.num):
842
+ out = self.num.copy()
843
+ out["cluster"] = self.cons["labels"]
844
+ out["confidence"] = self.cons["conf"]
845
+ out.to_csv(os.path.join(folder, "labels.csv"), index=False)
846
+ except Exception as e:
847
+ messagebox.showerror("Export failed", str(e))
848
+ return
849
+ self.status.config(text=f"Exported to {folder}")
850
+
851
+
852
+ def main():
853
+ App().mainloop()