-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathutils.py
More file actions
1928 lines (1612 loc) · 68.7 KB
/
Copy pathutils.py
File metadata and controls
1928 lines (1612 loc) · 68.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import re
import scanpy as sc
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import matplotlib.patheffects as pe
import seaborn as sns
import pandas as pd
from sklearn.metrics import adjusted_rand_score, normalized_mutual_info_score, silhouette_score
from sklearn.manifold import TSNE
import anndata as ad
from typing import Union, List, Tuple, Dict, Any, Optional
import numpy as np
import torch
import networkx as nx
from scipy.stats import ranksums
def create_segmented_colormap(n_labels: int, labels_per_segment: int = 5):
# Base color families (pick distinct hues)
color_families = [
'Blues', # 0-4
'Reds', # 5-9
'Greens', # 10-14
'Purples', # 15-19
'Oranges', # 20-24
'YlOrBr', # 25-29
'PuBu', # 30-34
'RdPu', # 35-39
'YlGn', # 40-44
'OrRd', # 45-49
'BuGn', # 50-54
'PuRd', # 55-59
]
colors = []
n_segments = int(np.ceil(n_labels / labels_per_segment))
for seg_idx in range(n_segments):
# Get color family for this segment
family = color_families[seg_idx % len(color_families)]
cmap = plt.cm.get_cmap(family)
# How many labels in this segment?
start_label = seg_idx * labels_per_segment
end_label = min((seg_idx + 1) * labels_per_segment, n_labels)
n_in_segment = end_label - start_label
# Create gradient within this family
# Start from 0.3 (not too light) to 1.0 (full intensity)
gradient_positions = np.linspace(0.3, 1.0, n_in_segment)
for pos in gradient_positions:
colors.append(cmap(pos))
return mcolors.ListedColormap(colors[:n_labels])
def _sanitize_filename_component(value: str) -> str:
cleaned = re.sub(r"[^A-Za-z0-9_-]+", "_", str(value)).strip("_")
return cleaned or "label"
def _ordered_label_categories(labels) -> Tuple[np.ndarray, np.ndarray]:
series = pd.Series(labels)
if pd.api.types.is_categorical_dtype(series):
categories = series.cat.categories.astype(str).to_numpy()
else:
categories = np.sort(series.astype(str).unique())
values = series.astype(str).to_numpy()
return values, categories
def _plot_embedding_clean(
coords: np.ndarray,
labels,
title: str,
save_path: str,
segmented: bool = False,
group_num: int = 5,
annotate: bool = False,
point_size: float = 5.0,
alpha: float = 0.85,
figsize: Tuple[float, float] = (8.5, 8.0),
):
label_values, categories = _ordered_label_categories(labels)
n_labels = len(categories)
if segmented:
cmap = create_segmented_colormap(max(n_labels, 1), labels_per_segment=group_num)
palette = [cmap(i) for i in range(max(n_labels, 1))]
else:
palette = sns.color_palette("husl", max(n_labels, 1))
color_map = {label: palette[i] for i, label in enumerate(categories)}
point_colors = [color_map[label] for label in label_values]
def _legend_handles():
return [
plt.Line2D(
[0],
[0],
marker="o",
color="w",
label=str(label),
markerfacecolor=color_map[label],
markersize=6,
)
for label in categories
]
fig, ax = plt.subplots(figsize=figsize)
ax.scatter(
coords[:, 0],
coords[:, 1],
c=point_colors,
s=point_size,
alpha=alpha,
linewidths=0,
rasterized=True,
)
ax.set_xlabel("")
ax.set_ylabel("")
ax.set_xticks([])
ax.set_yticks([])
ax.set_title(title, fontsize=13, fontweight="bold")
if annotate and 1 < n_labels <= 30:
for label in categories:
mask = label_values == label
if not np.any(mask):
continue
x_med = float(np.median(coords[mask, 0]))
y_med = float(np.median(coords[mask, 1]))
txt = ax.text(
x_med,
y_med,
str(label),
fontsize=8 if n_labels > 16 else 9,
ha="center",
va="center",
color="black",
zorder=3,
)
txt.set_path_effects([pe.withStroke(linewidth=3, foreground="white")])
elif n_labels <= 18:
handles = _legend_handles()
ax.legend(
handles=handles,
bbox_to_anchor=(1.02, 1.0),
loc="upper left",
frameon=False,
fontsize=8,
)
fig.tight_layout()
fig.savefig(save_path, dpi=300, bbox_inches="tight")
plt.close(fig)
if n_labels > 18:
legend_fig_height = max(4.0, min(18.0, 0.28 * n_labels + 1.5))
legend_fig, legend_ax = plt.subplots(figsize=(8.5, legend_fig_height))
legend_ax.axis("off")
legend_ax.legend(
handles=_legend_handles(),
loc="upper left",
frameon=False,
fontsize=8,
ncol=2 if n_labels <= 40 else 3,
columnspacing=1.2,
handletextpad=0.6,
)
legend_fig.tight_layout()
legend_path = save_path.replace(".png", "_legend.png")
legend_fig.savefig(legend_path, dpi=300, bbox_inches="tight")
plt.close(legend_fig)
def plot_umap(
adata: ad.AnnData,
embedding_key: str = 'X_umap',
label_key: str = 'cell_type',
save_path: Optional[str] = None,
title: Optional[str] = None,
figsize: Tuple[int, int] = (8, 6),
dpi: int = 300,
segment: bool = False,
group_num: int = 5,
**kwargs
):
# Compute UMAP if not already present
if embedding_key not in adata.obsm:
print(f"Computing UMAP (embedding not found in adata.obsm['{embedding_key}'])...")
sc.pp.neighbors(adata, use_rep='X')
sc.tl.umap(adata)
# Prepare colormap if segmented
palette = None
plot_label_key = label_key
if segment:
if pd.api.types.is_categorical_dtype(adata.obs[label_key]):
n_labels = len(adata.obs[label_key].cat.categories)
# Create numeric version
numeric_key = f"{label_key}_numeric"
adata.obs[numeric_key] = adata.obs[label_key].cat.codes
plot_label_key = numeric_key
# Create segmented colormap
palette = create_segmented_colormap(n_labels, labels_per_segment=group_num)
print(f"Using segmented colormap: {n_labels} labels, {group_num} per color family")
else:
print(f"Warning: {label_key} is not categorical. Segment mode requires categorical labels.")
print("Using default colors instead.")
# Plot
fig = plt.figure(figsize=figsize)
if palette is not None:
sc.pl.umap(
adata,
color=plot_label_key,
show=False,
palette=palette,
**kwargs
)
else:
sc.pl.umap(
adata,
color=label_key,
show=False,
**kwargs
)
if title:
plt.title(title, fontsize=14, fontweight='bold')
if save_path:
plt.savefig(save_path, dpi=dpi, bbox_inches='tight')
print(f"Saved UMAP to {save_path}")
return fig
def plot_umap_tsne(
adata,
save_dir: str,
best_params: Dict[str, Any],
label_key: str = "cell_type",
split: str = "train",
epoch: int = 0,
min_dist: float = 0.3,
spread: float = 1.0,
dpi: int = 300,
return_fig: bool = False,
segment: bool = False,
group_num: int = 5,
):
# Create umap subdirectory under save_dir
umap_dir = os.path.join(save_dir, 'umap')
os.makedirs(umap_dir, exist_ok=True)
# Compute neighbors if not already done
_get_knn_indices(adata, use_rep="cell_embed", n_neighbors=best_params['n_neighbors'],
random_state=42, calc_knn=True)
# Clustering
if best_params['method'] == 'leiden':
sc.tl.leiden(adata, resolution=best_params['resolution'], key_added='best_clustering')
elif best_params['method'] == 'louvain':
sc.tl.louvain(adata, resolution=best_params['resolution'], key_added='best_clustering')
ari = best_params['ari']
nmi = best_params['nmi']
asw = best_params.get('asw', 0.0)
# Compute UMAP and TSNE
sc.tl.umap(adata, min_dist=min_dist, spread=spread)
sc.tl.tsne(adata, use_rep="cell_embed")
# Prepare base color variables
color_by_categorical = [label_key]
if 'best_clustering' in adata.obs.columns:
color_by_categorical = ['best_clustering', label_key]
# ========== UMAP PLOT (with optional segmented colors) ==========
palette_umap = None
color_by_umap = color_by_categorical
if segment:
# Create segmented continuous colormap for UMAP only
if pd.api.types.is_categorical_dtype(adata.obs[label_key]):
n_labels = len(adata.obs[label_key].cat.categories)
# Create numeric version of labels
numeric_key = f"{label_key}_numeric"
adata.obs[numeric_key] = adata.obs[label_key].cat.codes
# Update color_by for UMAP
if 'best_clustering' in adata.obs.columns:
color_by_umap = ['best_clustering', numeric_key]
else:
color_by_umap = [numeric_key]
# Create segmented colormap
palette_umap = create_segmented_colormap(n_labels, labels_per_segment=group_num)
else:
print(f"Warning: {label_key} is not categorical, segment mode requires categorical labels. Using default colors.")
# Generate filenames
ari_batch = best_params.get('ari_batch', 0)
segment_str = f"_seg{group_num}" if segment else ""
if ari_batch > 0:
fname_base = f"_{split}_epoch{epoch:02d}_ari{ari:.3f}_arib{ari_batch:.3f}_nmi{nmi:.3f}_asw{asw:.3f}_{best_params['method']}_res{best_params['resolution']}_nn{best_params['n_neighbors']}{segment_str}"
else:
fname_base = f"_{split}_epoch{epoch:02d}_ari{ari:.3f}_nmi{nmi:.3f}_asw{asw:.3f}_{best_params['method']}_res{best_params['resolution']}_nn{best_params['n_neighbors']}{segment_str}"
fname_umap = fname_base + "_umap.png"
fname_tsne = fname_base.replace(segment_str, "") + "_tsne.png" # TSNE never gets segment suffix
# Plot UMAP (with segmented colors if requested)
if palette_umap is not None:
fig_umap = sc.pl.umap(
adata,
color=color_by_umap,
show=False,
return_fig=True,
size=40,
palette=palette_umap,
)
else:
fig_umap = sc.pl.umap(
adata,
color=color_by_umap,
show=False,
return_fig=True,
size=40,
)
# Add title for UMAP
title = f"{split.upper()} - Epoch {epoch} | ARI: {ari:.4f}, NMI: {nmi:.4f}, ASW: {asw:.4f}"
fig_umap.suptitle(title, fontsize=14, fontweight='bold', y=1.02)
# Save UMAP
fig_path_umap = os.path.join(umap_dir, fname_umap)
fig_umap.savefig(fig_path_umap, dpi=dpi, bbox_inches='tight')
# ========== TSNE PLOT (always categorical colors) ==========
fig_tsne = sc.pl.tsne(
adata,
color=color_by_categorical, # Always use categorical colors
show=False,
return_fig=True,
size=40,
)
# Add title for TSNE
fig_tsne.suptitle(title, fontsize=14, fontweight='bold', y=1.02)
# Save TSNE
fig_path_tsne = os.path.join(umap_dir, fname_tsne)
fig_tsne.savefig(fig_path_tsne, dpi=dpi, bbox_inches='tight')
# Save cleaner single-panel versions without the oversized Scanpy legends.
label_key_safe = _sanitize_filename_component(label_key)
clean_title_prefix = f"{split.upper()} - Epoch {epoch}"
if "best_clustering" in adata.obs.columns:
_plot_embedding_clean(
adata.obsm["X_umap"],
adata.obs["best_clustering"],
title=f"{clean_title_prefix} | best_clustering",
save_path=os.path.join(umap_dir, fname_umap.replace(".png", "_clean_best_clustering.png")),
segmented=True,
group_num=group_num,
annotate=False,
point_size=4.0,
alpha=0.9,
)
_plot_embedding_clean(
adata.obsm["X_tsne"],
adata.obs["best_clustering"],
title=f"{clean_title_prefix} | best_clustering",
save_path=os.path.join(umap_dir, fname_tsne.replace(".png", "_clean_best_clustering.png")),
segmented=True,
group_num=group_num,
annotate=False,
point_size=4.0,
alpha=0.9,
)
_plot_embedding_clean(
adata.obsm["X_umap"],
adata.obs[label_key],
title=f"{clean_title_prefix} | {label_key}",
save_path=os.path.join(umap_dir, fname_umap.replace(".png", f"_clean_{label_key_safe}.png")),
segmented=False,
annotate=True,
point_size=4.0,
alpha=0.9,
)
_plot_embedding_clean(
adata.obsm["X_tsne"],
adata.obs[label_key],
title=f"{clean_title_prefix} | {label_key}",
save_path=os.path.join(umap_dir, fname_tsne.replace(".png", f"_clean_{label_key_safe}.png")),
segmented=False,
annotate=True,
point_size=4.0,
alpha=0.9,
)
if return_fig:
return fig_umap, fig_tsne
else:
fig_umap.clf()
plt.close(fig_umap)
fig_tsne.clf()
plt.close(fig_tsne)
def evaluate_clustering(adata: ad.AnnData, key: str, batch_key: str = None) -> Dict[str, Any]:
clustering_methods = ["leiden", "louvain"]
resolutions = [0.32, 0.48, 0.64, 0.80] # More granular resolution search
n_neighbors_list = [15, 30] # Reduced from 3 to 2 (30 is often optimal)
best_params = {
'resolution': 0,
'ari': -1,
'ari_batch': 1.0, # NEW: batch ARI metric (lower is better)
'nmi': 0,
'asw': -1, # Average Silhouette Width (higher is better)
'method': None,
'n_neighbors': 0
}
for n_neighbor in n_neighbors_list:
# Compute KNN graph with current n_neighbors
_get_knn_indices(adata, use_rep="cell_embed", n_neighbors=n_neighbor,
random_state=42, calc_knn=True)
for method in clustering_methods:
clustering_func = sc.tl.leiden if method == 'leiden' else sc.tl.louvain
for resolution in resolutions:
clustering_func(adata, resolution=resolution, key_added=method)
# ARI with ground truth (KEEP FULL PRECISION - no rounding)
ari = adjusted_rand_score(adata.obs[key], adata.obs[method])
nmi = normalized_mutual_info_score(adata.obs[key], adata.obs[method])
# Compute ASW (Average Silhouette Width) using cell embeddings
# ASW measures cluster separation quality (higher is better, range: -1 to 1)
asw = 0.0
try:
# Need at least 2 clusters to compute silhouette
n_clusters = len(adata.obs[method].unique())
if n_clusters > 1 and n_clusters < len(adata):
asw = silhouette_score(
adata.obsm['cell_embed'],
adata.obs[method],
metric='euclidean'
)
except:
asw = 0.0
# NEW: Batch ARI if batch info available
# Lower batch ARI = better (clustering transcends batch boundaries)
ari_batch = 1.0
if batch_key and batch_key in adata.obs:
ari_batch = adjusted_rand_score(adata.obs[batch_key], adata.obs[method])
# Update best params: prioritize high ARI, use low batch ARI as tie-breaker
should_update = False
if ari > best_params['ari']:
should_update = True
elif ari == best_params['ari'] and ari_batch < best_params['ari_batch']:
# Tie-breaking: prefer clustering with lower batch ARI
should_update = True
if should_update:
best_params.update({
'resolution': resolution,
'ari': ari,
'ari_batch': ari_batch,
'method': method,
'n_neighbors': n_neighbor
})
if nmi > best_params['nmi']:
best_params['nmi'] = nmi
if asw > best_params['asw']:
best_params['asw'] = asw
return best_params
def _get_knn_indices(adata: ad.AnnData,
use_rep: str = "delta",
n_neighbors: int = 25,
random_state: int = 0,
calc_knn: bool = True
) -> np.ndarray:
if calc_knn:
assert use_rep == 'X' or use_rep in adata.obsm, f'{use_rep} not in adata.obsm and is not "X"'
neighbors = sc.Neighbors(adata)
neighbors.compute_neighbors(n_neighbors=n_neighbors, knn=True, use_rep=use_rep, random_state=random_state)
adata.obsp['distances'] = neighbors.distances
adata.obsp['connectivities'] = neighbors.connectivities
# Get knn_indices - compute from distances if not available
if hasattr(neighbors, 'knn_indices') and neighbors.knn_indices is not None:
adata.obsm['knn_indices'] = neighbors.knn_indices
else:
# Compute knn_indices from distances matrix
from scipy.sparse import issparse
if issparse(neighbors.distances):
distances_array = neighbors.distances.toarray()
else:
distances_array = neighbors.distances
# Get indices of k nearest neighbors (sorted by distance)
adata.obsm['knn_indices'] = np.argsort(distances_array, axis=1)[:, :n_neighbors]
adata.uns['neighbors'] = {
'connectivities_key': 'connectivities',
'distances_key': 'distances',
'knn_indices_key': 'knn_indices',
'params': {
'n_neighbors': n_neighbors,
'use_rep': use_rep,
'metric': 'euclidean',
'method': 'umap'
}
}
else:
assert 'neighbors' in adata.uns, 'No precomputed knn exists.'
assert adata.uns['neighbors']['params'][
'n_neighbors'] >= n_neighbors, f"pre-computed n_neighbors is {adata.uns['neighbors']['params']['n_neighbors']}, which is smaller than {n_neighbors}"
return adata.obsm['knn_indices']
def plot_theta_by_celltype_heatmap(
theta: np.ndarray,
cell_type_labels: np.ndarray,
save_path: str,
figsize: Tuple[int, int] = (14, 10),
cmap: Optional[str] = "Blues",
title: Optional[str] = None,
dpi: int = 300,
min_topic_proportion: float = 0.05,
vmin: float = 0.0,
vmax: float = 0.5,
topics_to_plot: Optional[List[int]] = None,
keep_topics_order: bool = False,
cell_barcodes: Optional[np.ndarray] = None,
highlight_multi_topic_cells: bool = False,
multi_topic_threshold: float = 0.05,
barcode_membership_topics: Optional[List[int]] = None,
barcode_membership_threshold: float = 0.05,
cell_sort_scores: Optional[np.ndarray] = None,
preserve_cell_order: bool = False,
):
# Convert to pandas DataFrame for easier manipulation
df = pd.DataFrame(theta, columns=[f'Topic_{i}' for i in range(theta.shape[1])])
df['cell_type'] = cell_type_labels
if cell_barcodes is not None:
if len(cell_barcodes) != theta.shape[0]:
raise ValueError(
f"cell_barcodes length ({len(cell_barcodes)}) must match theta rows ({theta.shape[0]})."
)
df['cell_barcode'] = np.asarray(cell_barcodes).astype(str)
if cell_sort_scores is not None:
if len(cell_sort_scores) != theta.shape[0]:
raise ValueError(
f"cell_sort_scores length ({len(cell_sort_scores)}) must match theta rows ({theta.shape[0]})."
)
df['cell_sort_score'] = np.asarray(cell_sort_scores, dtype=float)
# Calculate average topic proportions per cell type (topic columns only).
topic_cols_all = [f'Topic_{i}' for i in range(theta.shape[1])]
topic_avg_by_celltype = df.groupby('cell_type')[topic_cols_all].mean() # [num_cell_types, num_topics]
# Use the exact grouped index order to keep label mapping consistent.
unique_cell_types = topic_avg_by_celltype.index.tolist()
if topics_to_plot is not None:
max_topic_idx = theta.shape[1] - 1
seen = set()
topics_valid = []
for t in topics_to_plot:
ti = int(t)
if ti in seen:
continue
seen.add(ti)
if 0 <= ti <= max_topic_idx:
topics_valid.append(ti)
else:
print(f"Warning: topic {ti} is out of range [0, {max_topic_idx}] and will be ignored.")
if len(topics_valid) == 0:
print("Warning: no valid topics left after --topics_to_plot filtering; skipping heatmap.")
return
topic_info = []
for topic_idx in topics_valid:
topic_col = f'Topic_{topic_idx}'
avg_proportions = topic_avg_by_celltype[topic_col].values
max_celltype_idx = int(np.argmax(avg_proportions))
max_proportion = float(avg_proportions[max_celltype_idx])
topic_info.append({
'original_idx': topic_idx,
'best_celltype': unique_cell_types[max_celltype_idx],
'best_celltype_idx': max_celltype_idx,
'max_proportion': max_proportion
})
if keep_topics_order:
topic_order = list(topics_valid)
info_by_topic = {x['original_idx']: x for x in topic_info}
topic_info_sorted = [info_by_topic[t] for t in topic_order]
else:
topic_info_sorted = sorted(topic_info, key=lambda x: (x['best_celltype_idx'], -x['max_proportion']))
topic_order = [t['original_idx'] for t in topic_info_sorted]
else:
# Step 1: Ensure each cell type has at least one topic (its best topic)
guaranteed_topics = set()
for ct_idx, ct_name in enumerate(unique_cell_types):
# Find the topic with highest average proportion for this cell type
ct_proportions = topic_avg_by_celltype.loc[ct_name].values
best_topic_idx = np.argmax(ct_proportions)
guaranteed_topics.add(best_topic_idx)
# Step 2: Add topics that are significant in at least one cell type
topic_info = []
for topic_idx in range(theta.shape[1]):
topic_col = f'Topic_{topic_idx}'
avg_proportions = topic_avg_by_celltype[topic_col].values
max_celltype_idx = np.argmax(avg_proportions)
max_proportion = avg_proportions[max_celltype_idx]
# Keep topic if: (1) it's guaranteed for a cell type OR (2) it's above threshold
if topic_idx in guaranteed_topics or max_proportion >= min_topic_proportion:
topic_info.append({
'original_idx': topic_idx,
'best_celltype': unique_cell_types[max_celltype_idx],
'best_celltype_idx': max_celltype_idx,
'max_proportion': max_proportion
})
# Sort topics by: (1) their best cell type, (2) max proportion (descending)
topic_info_sorted = sorted(topic_info, key=lambda x: (x['best_celltype_idx'], -x['max_proportion']))
# Get the reordered topic indices
topic_order = [t['original_idx'] for t in topic_info_sorted]
print(f"Filtered topics: {len(topic_order)} out of {theta.shape[1]} topics kept")
print(f"Dropped {theta.shape[1] - len(topic_order)} insignificant topics")
if len(topic_order) == 0:
print("Warning: No topics passed significance threshold!")
return
# Sort rows (default: by cell type, optional: preserve incoming order).
if preserve_cell_order:
df_sorted = df.copy()
else:
df_sorted = df.copy()
df_sorted['cell_type'] = pd.Categorical(
df_sorted['cell_type'],
categories=unique_cell_types,
ordered=True
)
sort_cols = ['cell_type']
sort_ascending = [True]
if 'cell_sort_score' in df_sorted.columns:
sort_cols.append('cell_sort_score')
sort_ascending.append(False)
df_sorted = df_sorted.sort_values(sort_cols, ascending=sort_ascending, kind='mergesort')
# Select and reorder topics
topic_cols = [f'Topic_{i}' for i in topic_order]
theta_sorted = df_sorted[topic_cols].values # [num_cells, num_filtered_topics]
cell_types_sorted = df_sorted['cell_type'].values
barcodes_sorted = None
if 'cell_barcode' in df_sorted.columns:
barcodes_sorted = df_sorted['cell_barcode'].astype(str).values
# Get cell type boundaries for visualization
cell_type_boundaries = [0]
current_type = cell_types_sorted[0]
for i in range(1, len(cell_types_sorted)):
if cell_types_sorted[i] != current_type:
cell_type_boundaries.append(i)
current_type = cell_types_sorted[i]
cell_type_boundaries.append(len(cell_types_sorted))
# Create figure with GridSpec for row color bar
fig = plt.figure(figsize=figsize)
gs = fig.add_gridspec(1, 20, hspace=0, wspace=0.02)
ax_colorbar = fig.add_subplot(gs[0, :1]) # Left color bar for cell types
ax_heatmap = fig.add_subplot(gs[0, 1:]) # Main heatmap
# Plot main heatmap: cells (rows) × topics (columns)
im = ax_heatmap.imshow(
theta_sorted,
aspect='auto',
cmap=cmap,
interpolation='nearest',
vmin=vmin,
vmax=vmax
)
show_barcode_labels = barcodes_sorted is not None
cbar_pad = 0.12 if show_barcode_labels else 0.04
# Add colorbar for topic proportions
cbar = plt.colorbar(im, ax=ax_heatmap, fraction=0.046, pad=cbar_pad)
cbar.set_label('Topic Proportion', fontsize=10)
# Set labels
ax_heatmap.set_xlabel('Topics', fontsize=12)
ax_heatmap.set_ylabel('', fontsize=12)
# Set x-axis ticks for topics - use original topic indices
num_topics_shown = len(topic_order)
if num_topics_shown <= 30:
ax_heatmap.set_xticks(range(num_topics_shown))
ax_heatmap.set_xticklabels([f'{i}' for i in topic_order], fontsize=7, rotation=90)
else:
# Show every nth topic
step = max(1, num_topics_shown // 30)
tick_positions = range(0, num_topics_shown, step)
ax_heatmap.set_xticks(tick_positions)
ax_heatmap.set_xticklabels([f'{topic_order[i]}' for i in tick_positions],
fontsize=7, rotation=90)
# Optional per-cell y-axis labels (barcodes). Show all for small sets, sparse ticks otherwise.
barcode_count_color_map = {}
if barcodes_sorted is not None:
n_cells = len(barcodes_sorted)
if n_cells <= 120:
tick_idx = np.arange(n_cells)
else:
step = max(1, n_cells // 120)
tick_idx = np.arange(0, n_cells, step)
ax_heatmap.set_yticks(tick_idx)
ax_heatmap.yaxis.tick_right()
ax_heatmap.tick_params(axis='y', labelright=True, labelleft=False, pad=2)
ax_heatmap.set_yticklabels(
[barcodes_sorted[i] for i in tick_idx],
fontsize=5 if n_cells > 120 else 6
)
# Optional color-coding by number of active topics in a user-provided topic set.
membership_counts = None
if barcode_membership_topics is not None and len(barcode_membership_topics) > 0:
topic_pos = {int(t): i for i, t in enumerate(topic_order)}
sel_pos = [topic_pos[int(t)] for t in barcode_membership_topics if int(t) in topic_pos]
if len(sel_pos) > 0:
thr = float(max(0.0, barcode_membership_threshold))
membership_counts = (theta_sorted[:, sel_pos] >= thr).sum(axis=1).astype(int)
max_count = int(max(len(sel_pos), 1))
cmap_counts = plt.cm.get_cmap("turbo", max_count + 1)
for c in range(0, max_count + 1):
barcode_count_color_map[int(c)] = cmap_counts(c)
# Fallback: cells with >1 active topics are highlighted in red.
multi_topic_rows = set()
if membership_counts is None and highlight_multi_topic_cells:
thr = float(max(0.0, multi_topic_threshold))
active_counts = (theta_sorted >= thr).sum(axis=1)
multi_topic_rows = {int(i) for i, c in enumerate(active_counts.tolist()) if int(c) > 1}
for pos, tick in zip(tick_idx.tolist(), ax_heatmap.get_yticklabels()):
tick.set_horizontalalignment('left')
if membership_counts is not None:
tick.set_color(barcode_count_color_map.get(int(membership_counts[pos]), "black"))
elif pos in multi_topic_rows:
tick.set_color('red')
else:
# Remove y-axis ticks (too many cells)
ax_heatmap.set_yticks([])
# Use a categorical palette so the row bar and legend match the colored style.
cmap_cell_types = plt.cm.get_cmap('tab20', len(unique_cell_types))
colors = [cmap_cell_types(i)[:3] for i in range(len(unique_cell_types))]
cell_type_colors = np.zeros((len(cell_types_sorted), 1, 3))
for i, ct in enumerate(unique_cell_types):
mask = cell_types_sorted == ct
cell_type_colors[mask, 0, :] = np.asarray(colors[i], dtype=float)
ax_colorbar.imshow(cell_type_colors, aspect='auto', interpolation='nearest')
ax_colorbar.set_xticks([])
ax_colorbar.set_yticks([])
# Add a legend for cell types to the right of the figure
from matplotlib.patches import Patch
legend_handles = [
Patch(facecolor=colors[i], edgecolor='none', label=ct)
for i, ct in enumerate(unique_cell_types)
]
cell_type_legend = ax_heatmap.legend(
handles=legend_handles,
title="Cell Types",
loc='upper center',
bbox_to_anchor=(0.5, -0.08),
ncol=min(6, len(unique_cell_types)),
frameon=False,
fontsize=9,
title_fontsize=10
)
ax_heatmap.add_artist(cell_type_legend)
if barcodes_sorted is not None and len(barcode_count_color_map) > 0:
from matplotlib.lines import Line2D
membership_handles = []
for c in sorted(barcode_count_color_map.keys()):
membership_handles.append(
Line2D([0], [0], color=barcode_count_color_map[c], lw=3, label=f"{c} topics")
)
ax_heatmap.legend(
handles=membership_handles,
title="Barcode Topic Membership",
loc='upper center',
bbox_to_anchor=(0.5, -0.18),
ncol=min(8, len(membership_handles)),
frameon=False,
fontsize=8,
title_fontsize=9,
)
if title is None:
title = f'Topic Distribution by Cell\n({len(topic_order)} significant topics, ordered by cell type)'
fig.suptitle(title, fontsize=14, fontweight='bold', y=0.98)
# Tight layout with space on the right for colorbar + legend
plt.tight_layout()
fig.subplots_adjust(bottom=0.26 if len(barcode_count_color_map) > 0 else 0.15)
# Save to heatmap subdirectory
save_dir = os.path.dirname(save_path)
filename = os.path.basename(save_path)
heatmap_dir = os.path.join(save_dir, 'heatmap')
os.makedirs(heatmap_dir, exist_ok=True)
final_path = os.path.join(heatmap_dir, filename)
fig.savefig(final_path, dpi=dpi, bbox_inches='tight')
plt.close(fig)
print(f"Saved theta by cell type heatmap to {final_path}")
print(f"Topic ordering by cell type:")
for ct in unique_cell_types:
ct_topics = [t['original_idx'] for t in topic_info_sorted if t['best_celltype'] == ct]
print(f" {ct}: {len(ct_topics)} topics - {ct_topics[:10]}{'...' if len(ct_topics) > 10 else ''}")
def topic_wilcoxon_ad_vs_control(
theta: np.ndarray,
condition_labels: np.ndarray,
save_path: str,
ad_label: str = "AD",
control_label: str = "Control"
):
cond = pd.Series(condition_labels).astype(str).values
ad_mask = cond == ad_label
ctrl_mask = cond == control_label
n_ad = int(ad_mask.sum())
n_ctrl = int(ctrl_mask.sum())
if n_ad == 0 or n_ctrl == 0:
raise ValueError(
f"Wilcoxon requires both groups. Found {n_ad} '{ad_label}' and {n_ctrl} '{control_label}' cells."
)
rows = []
num_topics = theta.shape[1]
for topic_idx in range(num_topics):
ad_vals = theta[ad_mask, topic_idx]
ctrl_vals = theta[ctrl_mask, topic_idx]
stat, pval = ranksums(ad_vals, ctrl_vals)
mean_ad = float(np.mean(ad_vals))
mean_ctrl = float(np.mean(ctrl_vals))
delta = mean_ad - mean_ctrl
rows.append({
"Topic": topic_idx,
f"Mean_{ad_label}": mean_ad,
f"Mean_{control_label}": mean_ctrl,
"Delta_Mean": delta,
"RankSum_Statistic": float(stat),
"P_Value": float(pval),
f"N_{ad_label}": n_ad,
f"N_{control_label}": n_ctrl,
})
df = pd.DataFrame(rows).sort_values("P_Value", ascending=True).reset_index(drop=True)
# Benjamini-Hochberg FDR correction
pvals = df["P_Value"].to_numpy()
m = len(pvals)
ranks = np.arange(1, m + 1)
qvals = pvals * m / ranks
qvals = np.minimum.accumulate(qvals[::-1])[::-1]
qvals = np.clip(qvals, 0.0, 1.0)
df["FDR_BH"] = qvals
os.makedirs(os.path.dirname(save_path), exist_ok=True)
df.to_csv(save_path, index=False)
print(f"Saved topic Wilcoxon AD vs control results to {save_path}")
return df
def plot_topic_top_genes_heatmap(
beta: np.ndarray,
gene_names: np.ndarray,
save_path: str,
top_k: int = 5,
figsize: Tuple[int, int] = (8, 22),
cmap: str = 'RdBu_r',
title: Optional[str] = None,
dpi: int = 300,
topics_to_plot: Optional[List[int]] = None,
protein_coding_only: bool = True,
protein_coding_file: str = "/home/mcb/users/wdong12/aGraphETM_4/data/gene_with_protein_product.txt",
cell_type_labels: Optional[np.ndarray] = None,
theta: Optional[np.ndarray] = None,
apoe_only: bool = False,
apoe_offset: float = 0.0,
unique_genes: bool = True,
gene_offsets: Optional[Dict[str, float]] = None,
vmin: float = -1.0,
vmax: float = 1.0,
):
num_topics = beta.shape[0]
# Select topics to plot
if topics_to_plot is None:
topics_to_plot = list(range(num_topics))
# Sort topics by cell type if theta and cell_type_labels provided
topic_celltype_map = {}
if theta is not None and cell_type_labels is not None:
# Calculate average topic proportions per cell type
df = pd.DataFrame(theta[:, topics_to_plot],
columns=[f'Topic_{i}' for i in topics_to_plot])
df['cell_type'] = cell_type_labels
topic_avg_by_celltype = df.groupby('cell_type').mean()
# For each topic, find which cell type has highest average proportion
for i, topic_idx in enumerate(topics_to_plot):
topic_col = f'Topic_{topic_idx}'
avg_proportions = topic_avg_by_celltype[topic_col].values
best_celltype_idx = np.argmax(avg_proportions)
best_celltype = topic_avg_by_celltype.index[best_celltype_idx]
topic_celltype_map[topic_idx] = (best_celltype, best_celltype_idx)
# Sort topics by their best cell type
topics_to_plot = sorted(topics_to_plot,
key=lambda t: (topic_celltype_map[t][1], -topic_avg_by_celltype.loc[topic_celltype_map[t][0], f'Topic_{t}']))
print(f"Topics sorted by cell type associations")
# Optional per-gene offsets (case-insensitive), applied to ranking and plotted values.
gene_offsets = gene_offsets or {}
gene_offsets_upper = {str(k).upper(): float(v) for k, v in gene_offsets.items()}
# APOE-only mode: show APOE across selected topics only
gene_name_to_idx = {gene: idx for idx, gene in enumerate(gene_names)}
gene_name_to_idx_upper = {str(gene).upper(): idx for idx, gene in enumerate(gene_names)}
apoe_idx = gene_name_to_idx.get("APOE")
def _offset_for_gene(gene_name: str) -> float:
offset = gene_offsets_upper.get(str(gene_name).upper(), 0.0)
if str(gene_name) == "APOE":
offset += apoe_offset
return offset
if apoe_only:
if apoe_idx is None:
print("Error: APOE not found in gene list; cannot plot APOE-only heatmap.")
return
ordered_genes = ["APOE"]
heatmap_data = np.zeros((1, len(topics_to_plot)))
for i, topic_idx in enumerate(topics_to_plot):
heatmap_data[0, i] = beta[topic_idx, apoe_idx] + _offset_for_gene("APOE")
print(f"APOE-only mode enabled. Added offset {apoe_offset} to APOE scores.")
# Save CSV with APOE per topic
csv_data = []
for topic_idx in topics_to_plot:
if topic_idx in topic_celltype_map:
cell_type, _ = topic_celltype_map[topic_idx]
else:
cell_type = 'Unknown'
csv_data.append({
'Topic': topic_idx,
'Gene': "APOE",
'Beta_Weight': beta[topic_idx, apoe_idx] + _offset_for_gene("APOE"),