-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
1526 lines (1342 loc) · 54.2 KB
/
utils.py
File metadata and controls
1526 lines (1342 loc) · 54.2 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
"""
Utilities for cis/trans dashboard and gene expression (allele/genotype) viewer.
"""
import os
from typing import Dict, List, Literal, Optional, Tuple
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import streamlit as st
from data_bootstrap import get_data_root
from matplotlib.patches import Rectangle
# ---------------------------------------------------------------------------
# Cis/trans constants
# ---------------------------------------------------------------------------
REG_ORDER: List[str] = ["conserved", "cis", "trans", "cisxtrans", "cis+trans"]
SANKEY_ORDER: List[str] = ["conserved", "cis", "cisxtrans", "trans"]
REG_COLORS: Dict[str, str] = {
"conserved": "#D3D3D3",
"cis": "#FF4500",
"trans": "#4169E1",
"cis+trans": "#87CEEB",
"cisxtrans": "#228B22",
"not_detected": "#999999",
}
TISSUE_COMPOSITION_COLORS: Dict[str, str] = {
"conserved": "#D3D3D3",
"cis": "#FF4500",
"trans": "#4169E1",
"cis+trans": "#87CEEB",
"cisxtrans": "#228B22",
}
# ---------------------------------------------------------------------------
# Gene expression viewer constants
# ---------------------------------------------------------------------------
DATA_ROOT = str(get_data_root())
BASE_PATH = os.path.join(DATA_ROOT, "gene_count_data", "subtype")
DATA_SUFFIX = "_xgener_input_dataframe_FILTERED.csv"
META_SUFFIX = "_xgener_input_metadata_FILTERED.csv"
STRAINS_DISPLAY_ORDER = [
"A_J",
"NOD_ShiLtJ",
"129S1_SvImJ",
"NZO_HlLtJ",
"WSB_EiJ",
"PWK_PhJ",
"CAST_EiJ",
]
FOUNDER_SHORTNAME: Dict[str, str] = {
"129S1_SvImJ": "129S1J",
"A_J": "AJ",
"CAST_EiJ": "CASTJ",
"NOD_ShiLtJ": "NODJ",
"NZO_HlLtJ": "NZOJ",
"PWK_PhJ": "PWKJ",
"WSB_EiJ": "WSBJ",
}
GENO_DICT: Dict[str, str] = {
"129S1J": "#DA9CC1",
"B6J": "#C0BFBF",
"AJ": "#F4C245",
"CASTJ": "#55AF5B",
"NODJ": "#4F6EAF",
"NZOJ": "#52A5DB",
"PWKJ": "#D83026",
"WSBJ": "#683C91",
}
ALLELE_ORDER = ["P1", "H1", "H2", "P2"]
# ---------------------------------------------------------------------------
# Cis/trans data loading and caching
# ---------------------------------------------------------------------------
@st.cache_data(show_spinner=False)
def load_results_table(csv_path: str) -> pd.DataFrame:
dtypes = {
"gene": "category",
"strain": "category",
"subtype": "category",
"tissue": "category",
"subtype_tis": "category",
"reg_assignment": "category",
"colors": "category",
}
df = pd.read_csv(csv_path, dtype=dtypes, low_memory=False)
for col in [
"Parlog2FC",
"Hyblog2FC",
"fdr_cis",
"fdr_trans",
"cis_prop_reordered_fixed",
"cis_prop_reordered",
]:
if col in df.columns:
df[col] = pd.to_numeric(df[col], errors="coerce")
return df
@st.cache_data(show_spinner=False)
def precompute_bar_aggregates(
df: pd.DataFrame,
) -> Tuple[pd.DataFrame, pd.DataFrame]:
if "reg_assignment" not in df.columns:
empty = pd.DataFrame(
columns=["strain", "tissue", "subtype", "reg_assignment", "n"]
)
return empty, empty.assign(proportion=0.0)
group_cols = ["strain", "tissue", "subtype", "reg_assignment"]
counts = (
df.groupby(group_cols, observed=True)
.size()
.reset_index(name="n")
.astype({"n": "int64"})
)
totals = (
counts.groupby(["strain", "tissue", "subtype"], observed=True)["n"]
.sum()
.rename("total_n")
.reset_index()
)
props = counts.merge(totals, on=["strain", "tissue", "subtype"], how="left")
props["proportion"] = props["n"] / props["total_n"].replace(0, np.nan)
return counts, props
@st.cache_data(show_spinner=False)
def build_sankey_condition_index(
df: pd.DataFrame,
) -> Dict[Tuple[str, str, str], pd.Series]:
required_cols = {"gene", "strain", "tissue", "subtype", "reg_assignment"}
if not required_cols.issubset(df.columns):
return {}
index: Dict[Tuple[str, str, str], pd.Series] = {}
grouped = df.groupby(["strain", "tissue", "subtype"], observed=True)
for key, sub in grouped:
ser = (
sub[["gene", "reg_assignment"]]
.dropna(subset=["gene"])
.drop_duplicates(subset=["gene"])
.set_index("gene")["reg_assignment"]
)
index[(str(key[0]), str(key[1]), str(key[2]))] = ser
return index
def _apply_basic_filters(
df: pd.DataFrame,
tissue: Optional[str] = None,
strain: Optional[str] = None,
subtype: Optional[str] = None,
genes: Optional[List[str]] = None,
reg_include: Optional[List[str]] = None,
fdr_cis_max: Optional[float] = None,
fdr_trans_max: Optional[float] = None,
) -> pd.DataFrame:
mask = pd.Series(True, index=df.index)
if tissue and "tissue" in df.columns:
mask &= df["tissue"] == tissue
if strain and "strain" in df.columns:
mask &= df["strain"] == strain
if subtype and "subtype" in df.columns:
mask &= df["subtype"] == subtype
if genes and "gene" in df.columns:
mask &= df["gene"].isin(genes)
if reg_include is not None and "reg_assignment" in df.columns:
mask &= df["reg_assignment"].isin(reg_include)
if fdr_cis_max is not None and "fdr_cis" in df.columns:
mask &= df["fdr_cis"] <= fdr_cis_max
if fdr_trans_max is not None and "fdr_trans" in df.columns:
mask &= df["fdr_trans"] <= fdr_trans_max
return df[mask]
def plot_celltype_scatter_and_reg_proportions(
df: pd.DataFrame,
*,
x_col: str = "cis_prop_reordered",
y_col: str = "Parlog2FC",
color_col: str = "colors",
reg_col: str = "reg_assignment",
) -> plt.Figure:
d = df.copy()
if d.empty:
fig, ax = plt.subplots(figsize=(6, 4))
ax.text(0.5, 0.5, "No data for this selection", ha="center", va="center", fontsize=12)
ax.axis("off")
return fig
def infer_unique(col: str) -> str:
if col not in d.columns:
raise ValueError(f"Column '{col}' not found in dataframe.")
vals = d[col].dropna().unique()
if len(vals) != 1:
raise ValueError(f"Expected exactly one unique value in '{col}', found {len(vals)}.")
return str(vals[0])
strain = infer_unique("strain")
tissue = infer_unique("tissue")
subtype = infer_unique("subtype")
title = f"{tissue} {subtype} - {strain}"
bar_xtick = subtype
total_count = d[reg_col].notna().sum()
plot_df = (
d[reg_col]
.value_counts(normalize=True)
.reindex(REG_ORDER)
.fillna(0)
.to_frame("sample")
)
fig, (ax_sc, ax_bar) = plt.subplots(
1, 2, figsize=(6.6, 5.8), gridspec_kw={"width_ratios": (3.3, 1.1)}
)
band = (-0.5, 0.5)
vlines = (-1, -0.5, 0, 0.5, 1)
vline_colors = ("forestgreen", "royalblue", "lightblue", "orangered", "forestgreen")
ax_sc.axhspan(band[0], band[1], color="lightgray", alpha=0.4, zorder=0)
ax_sc.grid(True, which="major", color="#d0d0d0", linewidth=0.8)
ax_sc.grid(True, which="minor", color="#eeeeee", linewidth=0.5)
ax_sc.minorticks_on()
if color_col in d.columns and d[color_col].notna().any():
point_colors = d[color_col]
elif reg_col in d.columns:
point_colors = d[reg_col].map(REG_COLORS)
else:
point_colors = "#000000"
ax_sc.scatter(
d[x_col], d[y_col], c=point_colors, s=20, alpha=0.9, linewidths=0, zorder=1
)
ax_sc.axhline(0, color="black", linewidth=1.5, zorder=4)
for xv, col in zip(vlines, vline_colors):
ax_sc.axvline(xv, color=col, linewidth=3, alpha=0.9, zorder=2)
ax_sc.set_xlim(-1.1, 1.1)
ax_sc.set_ylim(-11, 11)
ax_sc.set_xlabel("Proportion cis", fontsize=15)
ax_sc.set_ylabel(r"$R_P$", fontsize=16)
ax_sc.tick_params(axis="both", labelsize=12)
ax_sc.set_xticks([-1, -0.5, 0, 0.5, 1])
ax_sc.set_xticklabels([0.5, 0, 0.5, 1, 0.5], fontsize=12)
ax_sc.set_axisbelow(True)
for spine in ["top", "right"]:
ax_sc.spines[spine].set_visible(False)
reg_order_for_bar = REG_ORDER
bar_colors = [REG_COLORS[c] for c in reg_order_for_bar]
plot_df.T.plot(kind="bar", stacked=True, width=0.75, color=bar_colors, ax=ax_bar, legend=False)
stack_label_min = 0.03
cumulative = 0.0
for cat in reg_order_for_bar:
value = float(plot_df.loc[cat, "sample"])
if value > stack_label_min:
ax_bar.text(0, cumulative + value / 2, f"{value:.2f}", ha="center", va="center", fontsize=11)
cumulative += value
ax_bar.text(0, 1.05, f"n={total_count}", ha="center", va="bottom", fontsize=10, fontweight="bold")
ax_bar.set_ylim(0, 1.05)
ax_bar.set_xlabel("")
ax_bar.set_xticklabels([bar_xtick], rotation=0, fontsize=12)
ax_bar.tick_params(axis="y", labelsize=12)
for spine in ["top", "right"]:
ax_bar.spines[spine].set_visible(False)
fig.suptitle(title, fontsize=21, y=0.99)
handles = [Rectangle((0, 0), 1, 1, color=REG_COLORS[c]) for c in reg_order_for_bar]
fig.legend(
handles, reg_order_for_bar, title="Reg Assignment", title_fontsize=11, fontsize=11,
ncol=len(reg_order_for_bar), loc="upper center", bbox_to_anchor=(0.5, -0.12), frameon=False,
)
plt.tight_layout(rect=[0, 0.05, 1, 0.94])
return fig
def plot_celltype_interactive_scatter_plotly(
df: pd.DataFrame,
*,
x_col: str = "cis_prop_reordered",
y_col: str = "Parlog2FC",
color_col: str = "colors",
reg_col: str = "reg_assignment",
gene_col: str = "gene",
) -> go.Figure:
"""Create interactive Plotly scatter plot with hover info (gene, reg_assignment, prop_cis)."""
d = df.copy()
if d.empty:
fig = go.Figure()
fig.add_annotation(
text="No data for this selection",
showarrow=False,
font=dict(size=14)
)
fig.update_layout(
plot_bgcolor="white",
paper_bgcolor="white"
)
return fig
# Ensure gene names are strings
if gene_col in d.columns:
# Convert categorical to string (NaNs become "nan"), then replace with "unknown"
d[gene_col] = d[gene_col].astype(str).replace("nan", "unknown")
else:
d[gene_col] = "unknown"
# Get color mapping
if color_col in d.columns and d[color_col].notna().any():
point_colors = d[color_col]
elif reg_col in d.columns:
point_colors = d[reg_col].map(REG_COLORS)
else:
point_colors = "#000000"
# Create hover text with gene, reg_assignment, prop_cis, and log2FC values
hover_text = []
for idx, row in d.iterrows():
gene = row.get(gene_col, "unknown")
reg = row.get(reg_col, "unknown")
cis_prop = row.get(x_col, np.nan)
parlog2fc = row.get(y_col, np.nan)
hyblog2fc = row.get("Hyblog2FC", np.nan)
hover_info = f"<b>{gene}</b><br>"
hover_info += f"Reg Assignment: {reg}<br>"
hover_info += f"Prop Cis: {cis_prop:.3f}<br>"
hover_info += f"Parlog2FC (R_P): {parlog2fc:.3f}<br>"
if not np.isnan(hyblog2fc):
hover_info += f"Hyblog2FC: {hyblog2fc:.3f}"
hover_text.append(hover_info)
d["hover"] = hover_text
# Create Plotly scatter
fig = go.Figure()
# Add reference bands and lines (visual guides)
# Band from -0.5 to 0.5
fig.add_shape(
type="rect",
x0=-1.1, x1=1.1, y0=-0.5, y1=0.5,
fillcolor="lightgray", opacity=0.2, line_width=0, layer="below"
)
# Vertical reference lines
vlines = [(-1, "forestgreen"), (-0.5, "royalblue"), (0, "lightblue"), (0.5, "orangered"), (1, "forestgreen")]
for xline, color in vlines:
fig.add_vline(x=xline, line_color=color, line_width=3, opacity=0.9)
# Horizontal reference line at y=0
fig.add_hline(y=0, line_color="black", line_width=2)
# Add scatter points
fig.add_trace(go.Scatter(
x=d[x_col],
y=d[y_col],
mode="markers",
marker=dict(
size=8,
color=point_colors.values if isinstance(point_colors, pd.Series) else point_colors,
opacity=0.9,
line_width=0
),
text=d["hover"],
hovertemplate="%{text}<extra></extra>",
name=""
))
# Update layout
fig.update_layout(
title="",
xaxis_title="Proportion cis",
yaxis_title="R_P",
xaxis=dict(
range=[-1.1, 1.1],
tickvals=[-1, -0.5, 0, 0.5, 1],
ticktext=["0.5", "0", "0.5", "1", "0.5"],
showgrid=True,
gridwidth=1,
gridcolor="#d0d0d0",
tickcolor="black",
tickfont=dict(color="black"),
titlefont=dict(color="black")
),
yaxis=dict(
range=[-11, 11],
showgrid=True,
gridwidth=1,
gridcolor="#d0d0d0",
tickcolor="black",
tickfont=dict(color="black"),
titlefont=dict(color="black")
),
hovermode="closest",
showlegend=False,
template="plotly_white",
plot_bgcolor="white",
paper_bgcolor="white",
height=600,
width=700,
margin=dict(l=80, r=50, t=50, b=80)
)
return fig
def plot_celltype_proportions_matplotlib(
df: pd.DataFrame,
*,
reg_col: str = "reg_assignment",
) -> plt.Figure:
"""Create matplotlib bar chart showing regulatory assignment proportions."""
d = df.copy()
if d.empty:
fig, ax = plt.subplots(figsize=(1.5, 6), facecolor='white')
ax.set_facecolor('white')
ax.text(0.5, 0.5, "No data", ha="center", va="center", fontsize=12)
ax.axis("off")
return fig
def infer_unique(col: str) -> str:
if col not in d.columns:
return "unknown"
vals = d[col].dropna().unique()
return str(vals[0]) if len(vals) > 0 else "unknown"
subtype = infer_unique("subtype")
total_count = d[reg_col].notna().sum()
plot_df = (
d[reg_col]
.value_counts(normalize=True)
.reindex(REG_ORDER)
.fillna(0)
.to_frame("sample")
)
fig, ax = plt.subplots(figsize=(2.2, 6), facecolor='white')
ax.set_facecolor('white')
reg_order_for_bar = REG_ORDER
bar_colors = [REG_COLORS[c] for c in reg_order_for_bar]
plot_df.T.plot(kind="bar", stacked=True, width=0.75, color=bar_colors, ax=ax, legend=False)
stack_label_min = 0.03
cumulative = 0.0
for cat in reg_order_for_bar:
value = float(plot_df.loc[cat, "sample"])
if value > stack_label_min:
ax.text(0, cumulative + value / 2, f"{value:.2f}", ha="center", va="center", fontsize=11)
cumulative += value
ax.text(0, 1.05, f"n={total_count}", ha="center", va="bottom", fontsize=10, fontweight="bold")
ax.set_ylim(0, 1.05)
ax.set_xlabel("")
ax.set_xticklabels([subtype], rotation=0, fontsize=11)
ax.tick_params(axis="y", labelsize=11)
for spine in ["top", "right"]:
ax.spines[spine].set_visible(False)
# Create legend to the left of the bar plot
handles = [Rectangle((0, 0), 1, 1, color=REG_COLORS[c]) for c in reg_order_for_bar]
fig.legend(
handles, reg_order_for_bar, title="Reg Assignment", title_fontsize=11, fontsize=10,
ncol=1, loc="center left", bbox_to_anchor=(-0.6, 0.5), frameon=False,
)
plt.tight_layout()
return fig
def make_celltype_strain_interactive_plotly(
props_df: pd.DataFrame,
tissue: str,
subtype: str,
sort_by: Literal["n", "conserved_prop", "cis_prop", "trans_prop"] = "n",
) -> Optional[go.Figure]:
"""Create interactive Plotly bar chart for cell type across strains with fixed strain order."""
subset = props_df[
(props_df["tissue"] == tissue) & (props_df["subtype"] == subtype)
]
if subset.empty:
return None
# Prepare data
strain_counts = subset.groupby("strain")["total_n"].first().rename("n").sort_index()
df_props = (
subset.pivot_table(
index="strain", columns="reg_assignment", values="proportion", fill_value=0.0
)
.reindex(columns=REG_ORDER, fill_value=0.0)
)
df_props = df_props.merge(strain_counts.to_frame(), left_index=True, right_index=True)
# Reorder strains to STRAINS_DISPLAY_ORDER
df_props = df_props.reindex(STRAINS_DISPLAY_ORDER).dropna(how="all")
# Create Plotly stacked bar chart
fig = go.Figure()
# Add bars for each regulation assignment
for i, reg_cat in enumerate(REG_ORDER):
fig.add_trace(go.Bar(
x=df_props.index,
y=df_props[reg_cat],
name=reg_cat,
marker_color=REG_COLORS.get(reg_cat, "#cccccc"),
text=[f"{v:.2f}" if v > 0.05 else "" for v in df_props[reg_cat]],
textposition="inside",
hovertemplate=f"<b>{reg_cat}</b><br>Strain: %{{x}}<br>Proportion: %{{y:.3f}}<extra></extra>"
))
# Update layout
fig.update_layout(
barmode="stack",
xaxis_title="Strain",
yaxis_title="Proportion",
title=f"{tissue} – {subtype}",
hovermode="x unified",
template="plotly_white",
plot_bgcolor="white",
paper_bgcolor="white",
height=600,
width=900,
showlegend=True,
legend=dict(title="Reg Assignment", orientation="v", yanchor="top", y=0.99, xanchor="right", x=0.99),
xaxis=dict(tickangle=-45),
margin=dict(l=80, r=150, t=100, b=100),
font=dict(color="black", size=12)
)
# Add count labels above bars
for i, strain in enumerate(df_props.index):
n_count = int(df_props.loc[strain, "n"])
fig.add_annotation(
x=strain, y=1.05,
text=f"n={n_count}",
showarrow=False,
font=dict(size=10, color="black"),
xanchor="center", yanchor="bottom"
)
return fig
def get_celltype_strain_data_table(
df: pd.DataFrame,
tissue: str,
subtype: str,
strain: str,
) -> pd.DataFrame:
"""Get a table of genes for a specific tissue/subtype/strain combo with key statistics."""
subset = df[
(df["tissue"] == tissue) &
(df["subtype"] == subtype) &
(df["strain"] == strain)
]
if subset.empty:
return pd.DataFrame()
# Select relevant columns for display
display_cols = ["gene", "reg_assignment", "Parlog2FC", "Hyblog2FC", "fdr_cis", "fdr_trans"]
available_cols = [col for col in display_cols if col in subset.columns]
result = subset[available_cols].drop_duplicates(subset=["gene"]).copy()
result = result.sort_values("gene").reset_index(drop=True)
return result
def make_tissue_composition_interactive_plotly(
props_df: pd.DataFrame,
tissue: str,
sort_by: Literal["n", "conserved_prop", "cis_prop", "trans_prop"] = "n",
) -> Optional[go.Figure]:
"""Create interactive Plotly bar chart for tissue-wide composition across cell types."""
subset = props_df[props_df["tissue"] == tissue]
if subset.empty:
return None
# Prepare data
subtype_counts = subset.groupby("subtype")["total_n"].first().rename("n").sort_index()
df_props = (
subset.pivot_table(
index="subtype", columns="reg_assignment", values="proportion", fill_value=0.0
)
.reindex(columns=REG_ORDER, fill_value=0.0)
)
df_props = df_props.merge(subtype_counts.to_frame(), left_index=True, right_index=True)
# Apply sorting
if sort_by == "n":
df_props = df_props.sort_values("n", ascending=False)
elif sort_by == "conserved_prop":
df_props = df_props.sort_values("conserved", ascending=False)
elif sort_by == "cis_prop":
df_props = df_props.sort_values("cis", ascending=False)
elif sort_by == "trans_prop":
df_props = df_props.sort_values("trans", ascending=False)
# Create Plotly stacked bar chart
fig = go.Figure()
# Add bars for each regulation assignment
for reg_cat in REG_ORDER:
fig.add_trace(go.Bar(
x=df_props.index,
y=df_props[reg_cat],
name=reg_cat,
marker_color=REG_COLORS.get(reg_cat, "#cccccc"),
text=[f"{v:.2f}" if v > 0.05 else "" for v in df_props[reg_cat]],
textposition="inside",
hovertemplate=f"<b>{reg_cat}</b><br>Cell Type: %{{x}}<br>Proportion: %{{y:.3f}}<extra></extra>"
))
# Update layout
fig.update_layout(
barmode="stack",
xaxis_title="Cell Type",
yaxis_title="Proportion",
title=f"{tissue} – Cell Type Composition",
hovermode="x unified",
template="plotly_white",
plot_bgcolor="white",
paper_bgcolor="white",
height=600,
width=1000,
showlegend=True,
legend=dict(title="Reg Assignment", orientation="v", yanchor="top", y=0.99, xanchor="right", x=0.99),
xaxis=dict(tickangle=-45),
margin=dict(l=80, r=150, t=100, b=120),
font=dict(color="black", size=12)
)
# Add count labels above bars
for i, subtype in enumerate(df_props.index):
n_count = int(df_props.loc[subtype, "n"])
fig.add_annotation(
x=subtype, y=1.05,
text=f"n={n_count}",
showarrow=False,
font=dict(size=10, color="black"),
xanchor="center", yanchor="bottom"
)
return fig
def get_tissue_composition_data_table(
df: pd.DataFrame,
tissue: str,
subtype: str,
strain: Optional[str] = None,
) -> pd.DataFrame:
"""Get a table of genes for tissue composition filtering by tissue, subtype, and optionally strain."""
subset = df[
(df["tissue"] == tissue) &
(df["subtype"] == subtype)
]
if strain:
subset = subset[subset["strain"] == strain]
if subset.empty:
return pd.DataFrame()
# Select relevant columns for display
display_cols = ["gene", "strain", "reg_assignment", "Parlog2FC", "Hyblog2FC", "fdr_cis", "fdr_trans"]
available_cols = [col for col in display_cols if col in subset.columns]
result = subset[available_cols].drop_duplicates(subset=["gene", "strain"]).copy()
result = result.sort_values(["strain", "gene"]).reset_index(drop=True)
return result
def make_celltype_strain_figure(
props_df: pd.DataFrame,
tissue: str,
subtype: str,
sort_by: Literal["n", "conserved_prop", "cis_prop", "trans_prop"] = "n",
) -> Optional[plt.Figure]:
subset = props_df[
(props_df["tissue"] == tissue) & (props_df["subtype"] == subtype)
]
if subset.empty:
return None
strain_counts = subset.groupby("strain")["total_n"].first().rename("n").sort_index()
df_props = (
subset.pivot_table(
index="strain", columns="reg_assignment", values="proportion", fill_value=0.0
)
.reindex(columns=REG_ORDER, fill_value=0.0)
)
df_props = df_props.merge(strain_counts.to_frame(), left_index=True, right_index=True)
# Apply sort_by logic if requested
if sort_by == "n":
df_props = df_props.sort_values("n", ascending=False)
elif sort_by == "conserved_prop":
df_props = df_props.sort_values("conserved", ascending=False)
elif sort_by == "cis_prop":
df_props = df_props.sort_values("cis", ascending=False)
elif sort_by == "trans_prop":
df_props = df_props.sort_values("trans", ascending=False)
# Reorder by STRAINS_DISPLAY_ORDER to ensure consistent display order
strain_order_available = [s for s in STRAINS_DISPLAY_ORDER if s in df_props.index]
df_props = df_props.reindex(strain_order_available)
df_n = df_props["n"]
df_vals = df_props[REG_ORDER]
n_bars = len(df_vals)
fig_w = max(6.0, 0.7 * n_bars)
fig, ax = plt.subplots(figsize=(fig_w, 6.0))
x = np.arange(n_bars)
bottom = np.zeros(n_bars)
for cat in REG_ORDER:
vals = df_vals[cat].values
ax.bar(x, vals, bottom=bottom, color=REG_COLORS.get(cat, "#cccccc"), width=0.8, edgecolor="none", label=cat)
for i, v in enumerate(vals):
if v > 0.05:
ax.text(x[i], bottom[i] + v / 2, f"{v:.2f}", ha="center", va="center", fontsize=10, color="black")
bottom += vals
for i, strain in enumerate(df_vals.index):
ax.text(x[i], 1.03, f"{int(df_n.loc[strain])}", ha="center", va="bottom", fontsize=11, color="black")
ax.set_title(f"{tissue} – {subtype}", fontsize=18)
ax.set_xlabel("Strain", fontsize=14)
ax.set_ylabel("Proportion", fontsize=14)
ax.set_ylim(0, 1.15)
ax.set_xticks(x)
ax.set_xticklabels(df_vals.index, rotation=45, ha="right", fontsize=12)
ax.tick_params(axis="y", labelsize=12, colors="black")
for spine in ["top", "right"]:
ax.spines[spine].set_visible(False)
fig.patch.set_facecolor("white")
ax.set_facecolor("white")
ax.legend(title="reg_assignment", bbox_to_anchor=(1.02, 1), loc="upper left", fontsize=10, title_fontsize=11, frameon=False)
fig.tight_layout()
return fig
def make_tissue_composition_figure(
props_df: pd.DataFrame,
tissue: str,
strain: str,
sort_by: Literal["n", "conserved_prop", "cis_prop", "trans_prop"] = "n",
) -> Optional[plt.Figure]:
subset = props_df[
(props_df["tissue"] == tissue) & (props_df["strain"] == strain)
]
if subset.empty:
return None
subtype_counts = subset.groupby("subtype")["total_n"].first().rename("n").sort_index()
df_props = (
subset.pivot_table(
index="subtype", columns="reg_assignment", values="proportion", fill_value=0.0
)
.reindex(columns=REG_ORDER, fill_value=0.0)
)
df_props = df_props.merge(subtype_counts.to_frame(), left_index=True, right_index=True)
if sort_by == "n":
df_props = df_props.sort_values("n", ascending=False)
elif sort_by == "conserved_prop":
df_props = df_props.sort_values("conserved", ascending=False)
elif sort_by == "cis_prop":
df_props = df_props.sort_values("cis", ascending=False)
elif sort_by == "trans_prop":
df_props = df_props.sort_values("trans", ascending=False)
df_n = df_props["n"]
df_vals = df_props[REG_ORDER]
n_bars = len(df_vals)
fig_w = max(6.0, 0.7 * n_bars)
fig, ax = plt.subplots(figsize=(fig_w, 6.0))
x = np.arange(n_bars)
bottom = np.zeros(n_bars)
for cat in REG_ORDER:
vals = df_vals[cat].values
ax.bar(x, vals, bottom=bottom, color=REG_COLORS.get(cat, "#cccccc"), width=0.8, edgecolor="none", label=cat)
for i, v in enumerate(vals):
if v > 0.05:
ax.text(x[i], bottom[i] + v / 2, f"{v:.2f}", ha="center", va="center", fontsize=10, color="black")
bottom += vals
for i, subtype in enumerate(df_vals.index):
ax.text(x[i], 1.03, f"{int(df_n.loc[subtype])}", ha="center", va="bottom", fontsize=11, color="black")
ax.set_title(f"{tissue} – {strain}", fontsize=18)
ax.set_xlabel("Cell type (subtype)", fontsize=14)
ax.set_ylabel("Proportion", fontsize=14)
ax.set_ylim(0, 1.15)
ax.set_xticks(x)
ax.set_xticklabels(df_vals.index, rotation=45, ha="right", fontsize=12)
ax.tick_params(axis="y", labelsize=12, colors="black")
for spine in ["top", "right"]:
ax.spines[spine].set_visible(False)
fig.patch.set_facecolor("white")
ax.set_facecolor("white")
ax.legend(title="reg_assignment", bbox_to_anchor=(1.02, 1), loc="upper left", fontsize=10, title_fontsize=11, frameon=False)
fig.tight_layout()
return fig
def _prepare_sankey_series(
condition_index: Dict[Tuple[str, str, str], pd.Series],
strain: str, tissue: str, subtype: str,
) -> Optional[pd.Series]:
key = (strain, tissue, subtype)
ser = condition_index.get(key)
if ser is None or ser.empty:
return None
ser = ser.where(ser != "cis+trans").dropna()
return ser
def get_condition_labels(
left: Tuple[str, str, str],
right: Tuple[str, str, str],
) -> Tuple[str, str]:
"""Generate meaningful column labels based on which condition differs.
Args:
left: (strain, tissue, subtype) tuple
right: (strain, tissue, subtype) tuple
Returns:
(left_label, right_label) tuple
"""
if left[0] != right[0]: # Strain differs
return f"reg_assignment ({left[0]})", f"reg_assignment ({right[0]})"
elif left[1] != right[1]: # Tissue differs
return f"reg_assignment ({left[1]})", f"reg_assignment ({right[1]})"
else: # Subtype differs
return f"reg_assignment ({left[2]})", f"reg_assignment ({right[2]})"
@st.cache_data(show_spinner=False)
@st.cache_data(show_spinner=False)
def build_sankey_transition_table(
genes_tuple: Tuple[str, ...],
condition_index_key_left: Tuple[str, str, str],
condition_index_key_right: Tuple[str, str, str],
condition_index_left_data: Tuple[Tuple[str, str], ...],
condition_index_right_data: Tuple[Tuple[str, str], ...],
left_label: str,
right_label: str,
) -> pd.DataFrame:
"""Build the gene table dataframe for a transition (cached for performance).
Args:
genes_tuple: Tuple of gene names
condition_index_key_left: Left condition tuple (strain, tissue, subtype)
condition_index_key_right: Right condition tuple (strain, tissue, subtype)
condition_index_left_data: Tuple of (gene, reg_assignment) pairs for left
condition_index_right_data: Tuple of (gene, reg_assignment) pairs for right
left_label: Column label for left condition
right_label: Column label for right condition
Returns:
DataFrame with gene, left_label, right_label columns
"""
# Convert tuples back to dicts
left_dict = dict(condition_index_left_data)
right_dict = dict(condition_index_right_data)
data = []
for gene in genes_tuple:
left_reg = left_dict.get(gene, "N/A")
right_reg = right_dict.get(gene, "N/A")
data.append({
"gene": gene,
left_label: left_reg,
right_label: right_reg,
})
return pd.DataFrame(data)
def display_sankey_gene_modal(
df: pd.DataFrame,
transition: Tuple[str, str],
genes: List[str],
condition_index: Dict[Tuple[str, str, str], pd.Series],
left_condition: Tuple[str, str, str],
right_condition: Tuple[str, str, str],
left_label: str = "From reg_assignment",
right_label: str = "To reg_assignment",
) -> None:
"""Display a modal with genes for a specific Sankey transition."""
if not genes:
st.warning("No genes found for this transition.")
return
left_state, right_state = transition
st.markdown(f"### Genes: **{left_state}** → **{right_state}** ({len(genes)} genes)")
# Build simplified dataframe with only gene and reg_assignments
data = []
for gene in genes:
left_reg = condition_index.get(left_condition, pd.Series()).get(gene, "N/A")
right_reg = condition_index.get(right_condition, pd.Series()).get(gene, "N/A")
data.append({
"gene": gene,
left_label: left_reg,
right_label: right_reg,
})
simplified_df = pd.DataFrame(data)
# Display search box for gene filtering with dynamic key to reset on transition change
transition_key = f"{left_state}_to_{right_state}"
search_query = st.text_input("Filter genes by name", value="", key=f"sankey_search_{transition_key}")
# Apply gene name filter
display_df = simplified_df.copy()
if search_query:
display_df = display_df[display_df['gene'].str.contains(search_query, case=False, na=False)]
# Display the dataframe
st.dataframe(display_df, use_container_width=True, hide_index=True)
# Download button with dynamic key
csv = display_df.to_csv(index=False)
st.download_button(
label="Download as CSV",
data=csv,
file_name=f"genes_{left_state}_to_{right_state}.csv",
mime="text/csv",
key=f"sankey_download_{transition_key}"
)
def build_sankey_figure(
condition_index: Dict[Tuple[str, str, str], pd.Series],
left: Tuple[str, str, str],
right: Tuple[str, str, str],
title: str,
) -> Optional[Tuple[go.Figure, int, int, Dict[Tuple[str, str], List[str]]]]:
left_strain, left_tissue, left_subtype = left
right_strain, right_tissue, right_subtype = right
left_ser = _prepare_sankey_series(condition_index, left_strain, left_tissue, left_subtype)
right_ser = _prepare_sankey_series(condition_index, right_strain, right_tissue, right_subtype)
if left_ser is None or right_ser is None:
return None
shared_genes = sorted(set(left_ser.index) & set(right_ser.index))
if not shared_genes:
return None
left_vals = left_ser.reindex(shared_genes)
right_vals = right_ser.reindex(shared_genes)
pair_counts: Dict[Tuple[str, str], int] = {}
gene_transitions: Dict[Tuple[str, str], List[str]] = {}
for gene, (l, r) in zip(shared_genes, zip(left_vals, right_vals)):
if (l not in SANKEY_ORDER) or (r not in SANKEY_ORDER):
continue
pair_counts[(l, r)] = pair_counts.get((l, r), 0) + 1
if (l, r) not in gene_transitions:
gene_transitions[(l, r)] = []
gene_transitions[(l, r)].append(gene)
if not pair_counts:
return None
left_nodes = [f"{lbl} (L)" for lbl in SANKEY_ORDER]
right_nodes = [f"{lbl} (R)" for lbl in SANKEY_ORDER]
labels = left_nodes + right_nodes
color_map = [REG_COLORS.get(lbl.split()[0], "#cccccc") for lbl in SANKEY_ORDER]
node_colors = color_map + color_map
label_to_index = {}
for i, lbl in enumerate(SANKEY_ORDER):
label_to_index[("L", lbl)] = i
label_to_index[("R", lbl)] = i + len(SANKEY_ORDER)
sources, targets, values, link_colors = [], [], [], []
for (l, r), count in pair_counts.items():
sources.append(label_to_index[("L", l)])
targets.append(label_to_index[("R", r)])
values.append(count)
link_colors.append(REG_COLORS.get(l, "#cccccc"))
fig = go.Figure(
data=[
go.Sankey(
node=dict(pad=15, thickness=15, line=dict(color="black", width=0.5), label=labels, color=node_colors),
link=dict(source=sources, target=targets, value=values, color=link_colors),
)
]
)
fig.update_layout(title=title, font_size=12, height=650, margin=dict(l=40, r=40, t=60, b=40))
total_genes = len(set(left_ser.index) | set(right_ser.index))
shared_n = len(shared_genes)
return fig, total_genes, shared_n, gene_transitions