-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapp.py
More file actions
2906 lines (2478 loc) · 132 KB
/
Copy pathapp.py
File metadata and controls
2906 lines (2478 loc) · 132 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
"""
RNA-seq Processing App
A Streamlit-based GUI for processing RNA-seq data using Salmon.
"""
# Raise file descriptor limit before any heavy imports
# macOS app bundles launched via Finder inherit a 256 soft limit from launchd,
# which is too low for Streamlit + the scientific Python stack.
import resource
try:
_soft, _hard = resource.getrlimit(resource.RLIMIT_NOFILE)
resource.setrlimit(resource.RLIMIT_NOFILE, (min(_hard, 8192), _hard))
except (ValueError, resource.error):
pass
import streamlit as st
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import numpy as np
import re
from pathlib import Path
import os
from datetime import datetime
import subprocess
import json
import time
import io
import threading
from PIL import Image
def _start_idle_watchdog(timeout=60):
"""Shut down Streamlit if no browser is connected for `timeout` seconds."""
def watchdog():
idle_since = None
while True:
time.sleep(10)
try:
# Check for active WebSocket connections on port 8501
result = subprocess.run(
["lsof", "-i", ":8501", "-sTCP:ESTABLISHED"],
capture_output=True, text=True
)
has_clients = bool(result.stdout.strip())
except Exception:
has_clients = True # assume connected if check fails
if has_clients:
idle_since = None
else:
if idle_since is None:
idle_since = time.time()
elif time.time() - idle_since > timeout:
os._exit(0)
t = threading.Thread(target=watchdog, daemon=True)
t.start()
# Start the idle watchdog once per process (not on every Streamlit rerun)
if not getattr(_start_idle_watchdog, "_started", False):
_start_idle_watchdog(timeout=60)
_start_idle_watchdog._started = True
from pipeline import (
SampleInfo,
PipelineConfig,
check_salmon_installed,
get_salmon_version,
download_reference_index,
build_index_from_fasta,
validate_fasta_is_transcriptome,
run_pipeline,
merge_counts,
get_mapping_stats,
validate_fastq
)
# App configuration
st.set_page_config(
page_title="GenomifySeq",
page_icon="🧬",
layout="wide"
)
# Initialize session state
if "pipeline_running" not in st.session_state:
st.session_state.pipeline_running = False
if "results" not in st.session_state:
st.session_state.results = None
if "log_messages" not in st.session_state:
st.session_state.log_messages = []
if "detected_samples" not in st.session_state:
st.session_state.detected_samples = None
if "metadata_df" not in st.session_state:
st.session_state.metadata_df = None
if "analysis_results" not in st.session_state:
st.session_state.analysis_results = None
if "de_results" not in st.session_state:
st.session_state.de_results = None
if "gsea_results" not in st.session_state:
st.session_state.gsea_results = None
if "gmt_file_path" not in st.session_state:
st.session_state.gmt_file_path = None
if "volcano_overlay" not in st.session_state:
st.session_state.volcano_overlay = None
if "geneset_overlay_genes" not in st.session_state:
st.session_state.geneset_overlay_genes = None
if "geneset_overlay_name" not in st.session_state:
st.session_state.geneset_overlay_name = None
if "volcano_overlay_r" not in st.session_state:
st.session_state.volcano_overlay_r = None
# Paths - save user data to Documents folder (not inside app bundle)
APP_DIR = Path(__file__).parent
USER_DATA_DIR = Path.home() / "Documents" / "GenomifySeq"
INDEX_DIR = USER_DATA_DIR / "indices"
RESULTS_DIR = USER_DATA_DIR / "results"
TX2GENE_DIR = USER_DATA_DIR / "tx2gene"
SESSIONS_DIR = USER_DATA_DIR / "sessions"
# Ensure directories exist
for d in [INDEX_DIR, RESULTS_DIR, TX2GENE_DIR, SESSIONS_DIR]:
d.mkdir(parents=True, exist_ok=True)
def detect_species():
"""Auto-detect species from the selected index path name."""
index_path = st.session_state.get("index_path")
if index_path and "mouse" in str(index_path).lower():
return "mouse"
return "human"
def add_log(message: str):
"""Add a message to the log."""
timestamp = datetime.now().strftime("%H:%M:%S")
st.session_state.log_messages.append(f"[{timestamp}] {message}")
def png_to_tiff(png_path: Path) -> bytes:
"""Convert a PNG file to TIFF format and return as bytes."""
img = Image.open(png_path)
# Convert to RGB if necessary (TIFF doesn't support all PNG modes well)
if img.mode in ('RGBA', 'LA', 'P'):
# Create white background for transparent images
background = Image.new('RGB', img.size, (255, 255, 255))
if img.mode == 'P':
img = img.convert('RGBA')
background.paste(img, mask=img.split()[-1] if img.mode == 'RGBA' else None)
img = background
elif img.mode != 'RGB':
img = img.convert('RGB')
buffer = io.BytesIO()
img.save(buffer, format='TIFF', compression='tiff_lzw', dpi=(300, 300))
buffer.seek(0)
return buffer.getvalue()
def plotly_to_tiff(fig: go.Figure, width: int = 1200, height: int = 900) -> bytes:
"""Convert a Plotly figure to TIFF format and return as bytes."""
# First convert to PNG using Plotly's to_image
try:
png_bytes = fig.to_image(format="png", width=width, height=height, scale=2)
img = Image.open(io.BytesIO(png_bytes))
# Convert to RGB
if img.mode != 'RGB':
img = img.convert('RGB')
buffer = io.BytesIO()
img.save(buffer, format='TIFF', compression='tiff_lzw', dpi=(300, 300))
buffer.seek(0)
return buffer.getvalue()
except Exception as e:
# Fallback: kaleido may not be installed
raise RuntimeError(f"Could not export to TIFF. Install kaleido: pip install kaleido. Error: {e}")
def format_time(seconds: float) -> str:
"""Format seconds into human-readable time string."""
if seconds < 60:
return f"{int(seconds)}s"
elif seconds < 3600:
mins = int(seconds // 60)
secs = int(seconds % 60)
return f"{mins}m {secs}s"
else:
hours = int(seconds // 3600)
mins = int((seconds % 3600) // 60)
return f"{hours}h {mins}m"
def serialize_samples(detected_samples: dict) -> dict:
"""Serialize detected_samples dict for JSON storage (convert Path to str)."""
if not detected_samples:
return None
result = {
"read_type": detected_samples.get("read_type"),
"samples": []
}
for s in detected_samples.get("samples", []):
sample_data = {
"name": s["name"],
"r1": str(s["r1"]) if s.get("r1") else None,
"r2": str(s["r2"]) if s.get("r2") else None,
}
result["samples"].append(sample_data)
return result
def deserialize_samples(data: dict) -> dict:
"""Deserialize samples dict from JSON (convert str back to Path)."""
if not data:
return None
result = {
"read_type": data.get("read_type"),
"samples": []
}
for s in data.get("samples", []):
sample_data = {
"name": s["name"],
"r1": Path(s["r1"]) if s.get("r1") else None,
"r2": Path(s["r2"]) if s.get("r2") else None,
}
result["samples"].append(sample_data)
return result
def save_session(name: str) -> Path:
"""Save current session to JSON + CSV files."""
session_dir = SESSIONS_DIR / f"{name}_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
session_dir.mkdir(parents=True, exist_ok=True)
# Save metadata_df as CSV
if st.session_state.metadata_df is not None:
st.session_state.metadata_df.to_csv(session_dir / "metadata.csv", index=False)
# Save everything else as JSON
session_data = {
"data_dir_path": st.session_state.get("data_dir_path"),
"detected_samples": serialize_samples(st.session_state.get("detected_samples")),
"index_path": str(st.session_state.get("index_path", "")) if st.session_state.get("index_path") else None,
"results": st.session_state.get("results"),
"analysis_results": st.session_state.get("analysis_results"),
"de_results": st.session_state.get("de_results"),
"gsea_results": st.session_state.get("gsea_results"),
"gmt_file_path": st.session_state.get("gmt_file_path"),
}
(session_dir / "session.json").write_text(json.dumps(session_data, indent=2, default=str))
return session_dir
def load_session(session_dir: Path):
"""Restore session from saved files."""
# Load JSON
session_data = json.loads((session_dir / "session.json").read_text())
# Restore to session state
st.session_state.data_dir_path = session_data.get("data_dir_path")
st.session_state.detected_samples = deserialize_samples(session_data.get("detected_samples"))
if session_data.get("index_path"):
st.session_state.index_path = Path(session_data["index_path"])
st.session_state.results = session_data.get("results")
st.session_state.analysis_results = session_data.get("analysis_results")
st.session_state.de_results = session_data.get("de_results")
st.session_state.gsea_results = session_data.get("gsea_results")
st.session_state.gmt_file_path = session_data.get("gmt_file_path")
# Load metadata CSV - ensure all columns are strings for data_editor compatibility
metadata_file = session_dir / "metadata.csv"
if metadata_file.exists():
metadata_df = pd.read_csv(metadata_file, dtype=str)
# Replace NaN with empty strings
metadata_df = metadata_df.fillna("")
st.session_state.metadata_df = metadata_df
def create_interactive_volcano(
df: pd.DataFrame,
lfc_threshold: float = 1.0,
padj_threshold: float = 0.05,
search_genes: list = None,
label_genes: list = None,
highlight_genes: list = None,
title: str = "Volcano Plot"
) -> go.Figure:
"""
Create an interactive volcano plot with Plotly.
Parameters:
-----------
df : DataFrame with columns 'gene', 'log2FoldChange', 'padj' (and optionally 'pvalue', 'baseMean')
lfc_threshold : Log2 fold change threshold for significance
padj_threshold : Adjusted p-value threshold for significance
search_genes : List of genes to highlight from search
label_genes : List of genes to label on the plot
highlight_genes : List of genes to highlight (e.g., from gene set)
title : Plot title
Returns:
--------
Plotly Figure object
"""
# Make a copy to avoid modifying original
plot_df = df.copy()
# Calculate -log10(padj) for y-axis
plot_df["neg_log10_padj"] = -np.log10(plot_df["padj"].clip(lower=1e-300))
# Determine significance category
def get_significance(row):
if pd.isna(row["padj"]) or pd.isna(row["log2FoldChange"]):
return "NS"
if row["padj"] < padj_threshold and row["log2FoldChange"] > lfc_threshold:
return "Up"
elif row["padj"] < padj_threshold and row["log2FoldChange"] < -lfc_threshold:
return "Down"
else:
return "NS"
plot_df["category"] = plot_df.apply(get_significance, axis=1)
# Color mapping (blue=up, red=down)
color_map = {"Up": "#3498db", "Down": "#e74c3c", "NS": "#95a5a6"}
# Create base figure
fig = go.Figure()
# Add scatter traces for each category (for legend)
for category, color in color_map.items():
mask = plot_df["category"] == category
subset = plot_df[mask]
if len(subset) == 0:
continue
# Check if these genes should be highlighted
if search_genes:
search_mask = subset["gene"].isin(search_genes)
# Non-searched genes (smaller, more transparent)
non_search = subset[~search_mask]
if len(non_search) > 0:
fig.add_trace(go.Scatter(
x=non_search["log2FoldChange"],
y=non_search["neg_log10_padj"],
mode="markers",
marker=dict(color=color, size=6, opacity=0.3),
name=f"{category} ({len(non_search)})",
text=non_search["gene"],
customdata=np.stack([
non_search["log2FoldChange"].round(3),
non_search["padj"].apply(lambda x: f"{x:.2e}"),
non_search.get("baseMean", pd.Series(["N/A"] * len(non_search))),
], axis=-1) if "baseMean" in non_search.columns else np.stack([
non_search["log2FoldChange"].round(3),
non_search["padj"].apply(lambda x: f"{x:.2e}"),
], axis=-1),
hovertemplate="<b>%{text}</b><br>" +
"log2FC: %{customdata[0]}<br>" +
"padj: %{customdata[1]}<br>" +
"<extra></extra>",
showlegend=True,
legendgroup=category,
))
# Searched genes (larger, fully opaque)
search_subset = subset[search_mask]
if len(search_subset) > 0:
fig.add_trace(go.Scatter(
x=search_subset["log2FoldChange"],
y=search_subset["neg_log10_padj"],
mode="markers",
marker=dict(color=color, size=12, opacity=1.0,
line=dict(color="black", width=2)),
name=f"Search match ({len(search_subset)})",
text=search_subset["gene"],
customdata=np.stack([
search_subset["log2FoldChange"].round(3),
search_subset["padj"].apply(lambda x: f"{x:.2e}"),
], axis=-1),
hovertemplate="<b>%{text}</b><br>" +
"log2FC: %{customdata[0]}<br>" +
"padj: %{customdata[1]}<br>" +
"<extra></extra>",
showlegend=True,
legendgroup="search",
))
else:
# Normal display without search
fig.add_trace(go.Scatter(
x=subset["log2FoldChange"],
y=subset["neg_log10_padj"],
mode="markers",
marker=dict(color=color, size=6, opacity=0.7),
name=f"{category} ({len(subset)})",
text=subset["gene"],
customdata=np.stack([
subset["log2FoldChange"].round(3),
subset["padj"].apply(lambda x: f"{x:.2e}"),
], axis=-1),
hovertemplate="<b>%{text}</b><br>" +
"log2FC: %{customdata[0]}<br>" +
"padj: %{customdata[1]}<br>" +
"<extra></extra>",
showlegend=True,
legendgroup=category,
))
# Highlight significant genes from gene set overlay (matching R behavior)
if highlight_genes:
highlight_mask = (plot_df["gene"].isin(highlight_genes)) & (plot_df["category"] != "NS")
highlight_subset = plot_df[highlight_mask]
if len(highlight_subset) > 0:
# Add black outline circles around significant genes in the set
fig.add_trace(go.Scatter(
x=highlight_subset["log2FoldChange"],
y=highlight_subset["neg_log10_padj"],
mode="markers",
marker=dict(
color="rgba(0,0,0,0)", # Transparent fill
size=7, # Slightly larger than points (size 6) for visibility
line=dict(color="black", width=1.5),
symbol="circle"
),
name=f"Gene set sig. ({len(highlight_subset)})",
text=highlight_subset["gene"],
customdata=np.stack([
highlight_subset["log2FoldChange"].round(3),
highlight_subset["padj"].apply(lambda x: f"{x:.2e}"),
], axis=-1),
hovertemplate="<b>%{text}</b><br>" +
"log2FC: %{customdata[0]}<br>" +
"padj: %{customdata[1]}<br>" +
"<extra></extra>",
showlegend=True,
))
# Add labels for top 10 significant genes from the gene set (sorted by padj)
top_highlight = highlight_subset.nsmallest(10, "padj")
if len(top_highlight) > 0:
fig.add_trace(go.Scatter(
x=top_highlight["log2FoldChange"],
y=top_highlight["neg_log10_padj"],
mode="text",
text=top_highlight["gene"],
textposition="top center",
textfont=dict(size=10, color="black"),
name=f"Labels ({len(top_highlight)})",
hoverinfo="skip",
showlegend=False,
))
# Add gene labels
if label_genes:
label_mask = plot_df["gene"].isin(label_genes)
label_subset = plot_df[label_mask]
if len(label_subset) > 0:
# Add labeled points with larger markers
fig.add_trace(go.Scatter(
x=label_subset["log2FoldChange"],
y=label_subset["neg_log10_padj"],
mode="markers+text",
marker=dict(
color="purple",
size=10,
opacity=1.0,
line=dict(color="white", width=2),
),
text=label_subset["gene"],
textposition="top center",
textfont=dict(size=11, color="black"),
name=f"Labeled ({len(label_subset)})",
customdata=np.stack([
label_subset["log2FoldChange"].round(3),
label_subset["padj"].apply(lambda x: f"{x:.2e}"),
], axis=-1),
hovertemplate="<b>%{text}</b><br>" +
"log2FC: %{customdata[0]}<br>" +
"padj: %{customdata[1]}<br>" +
"<extra></extra>",
showlegend=True,
))
# Add threshold lines
neg_log10_padj_threshold = -np.log10(padj_threshold)
# Horizontal line for p-value threshold
fig.add_hline(y=neg_log10_padj_threshold, line_dash="dash",
line_color="gray", opacity=0.7,
annotation_text=f"padj = {padj_threshold}",
annotation_position="bottom right")
# Vertical lines for fold change thresholds
fig.add_vline(x=lfc_threshold, line_dash="dash",
line_color="gray", opacity=0.7)
fig.add_vline(x=-lfc_threshold, line_dash="dash",
line_color="gray", opacity=0.7,
annotation_text=f"|log2FC| = {lfc_threshold}",
annotation_position="bottom left")
# Update layout
fig.update_layout(
title=dict(text=title, x=0.5, xanchor="center"),
xaxis_title="log2 Fold Change",
yaxis_title="-log10(adjusted p-value)",
hovermode="closest",
legend=dict(
yanchor="top",
y=0.99,
xanchor="left",
x=1.02,
bgcolor="rgba(255,255,255,0.8)"
),
plot_bgcolor="white",
width=800,
height=600,
)
# Add gridlines
fig.update_xaxes(showgrid=True, gridwidth=1, gridcolor="lightgray",
zeroline=True, zerolinewidth=1, zerolinecolor="gray")
fig.update_yaxes(showgrid=True, gridwidth=1, gridcolor="lightgray",
zeroline=True, zerolinewidth=1, zerolinecolor="gray")
return fig
def open_folder_dialog(initial_dir: str = None) -> str:
"""Open native macOS folder picker dialog using AppleScript."""
initial = initial_dir or str(Path.home())
script = f'''
set initialPath to POSIX file "{initial}" as alias
try
set selectedFolder to choose folder with prompt "Select FASTQ Directory" default location initialPath
return POSIX path of selectedFolder
on error
return ""
end try
'''
try:
result = subprocess.run(
['osascript', '-e', script],
capture_output=True,
text=True,
timeout=120
)
return result.stdout.strip()
except Exception:
return ""
def open_file_dialog(initial_dir: str = None) -> str:
"""Open native macOS file picker dialog using AppleScript."""
initial = initial_dir or str(Path.home())
script = f'''
set initialPath to POSIX file "{initial}" as alias
try
set selectedFile to choose file with prompt "Select FASTA File" default location initialPath of type {{"fa", "fasta", "gz", "public.data"}}
return POSIX path of selectedFile
on error
return ""
end try
'''
try:
result = subprocess.run(
['osascript', '-e', script],
capture_output=True,
text=True,
timeout=120
)
return result.stdout.strip()
except Exception:
return ""
def open_gmt_dialog(initial_dir: str = None) -> str:
"""Open native macOS file picker for GMT files."""
initial = initial_dir or str(Path.home())
script = f'''
set initialPath to POSIX file "{initial}" as alias
try
set selectedFile to choose file with prompt "Select GMT Gene Set File" default location initialPath
return POSIX path of selectedFile
on error
return ""
end try
'''
try:
result = subprocess.run(
['osascript', '-e', script],
capture_output=True,
text=True,
timeout=120
)
return result.stdout.strip()
except Exception:
return ""
def get_basename(filename: str) -> str:
"""Strip FASTQ extensions to get base name."""
name = filename
# Remove .gz first if present
if name.endswith('.gz'):
name = name[:-3]
# Remove .fastq or .fq
if name.endswith('.fastq'):
name = name[:-6]
elif name.endswith('.fq'):
name = name[:-3]
return name
def detect_read_pair(filename: str) -> tuple[str, int]:
"""
Detect if a file is Read 1 or Read 2 based on END of filename.
Returns (sample_base_name, read_number) where read_number is 1, 2, or 0 (unknown).
Supports patterns at end of basename:
- _1, _2 (e.g., sample_1.fastq.gz, sample_2.fastq.gz)
- _R1, _R2 (e.g., sample_R1.fastq.gz, sample_R2.fastq.gz)
- .R1, .R2 (e.g., sample.R1.fastq.gz)
- _read1, _read2 (e.g., sample_read1.fastq.gz)
"""
basename = get_basename(filename)
# Patterns to check at END of basename (order matters - check more specific first)
# Each tuple: (regex pattern, read number, replacement to get sample name)
end_patterns = [
(r'[_.]read1$', 1),
(r'[_.]read2$', 2),
(r'[_.]R1$', 1),
(r'[_.]R2$', 2),
(r'[_.]1$', 1),
(r'[_.]2$', 2),
]
for pattern, read_num in end_patterns:
match = re.search(pattern, basename, re.IGNORECASE)
if match:
sample_name = basename[:match.start()]
return (sample_name, read_num)
# No paired pattern found
return (basename, 0)
def scan_fastq_directory(directory: Path) -> dict:
"""
Scan a directory for FASTQ files and detect paired-end samples.
Returns dict with 'samples' list and 'read_type' (paired/single).
"""
fastq_extensions = {'.fastq', '.fq', '.fastq.gz', '.fq.gz'}
# Find all FASTQ files
fastq_files = []
for f in directory.iterdir():
if f.is_file():
# Check extension (handle .fastq.gz)
if f.suffix == '.gz':
ext = ''.join(f.suffixes[-2:]) if len(f.suffixes) >= 2 else f.suffix
else:
ext = f.suffix
if ext.lower() in fastq_extensions:
fastq_files.append(f)
if not fastq_files:
return {"samples": [], "read_type": None, "error": "No FASTQ files found"}
# Detect read pairs based on END of filename
file_info = []
for f in fastq_files:
sample_name, read_num = detect_read_pair(f.name)
file_info.append({
"file": f,
"sample_name": sample_name,
"read_num": read_num
})
# Group by sample name
samples_dict = {}
for info in file_info:
name = info["sample_name"]
if name not in samples_dict:
samples_dict[name] = {"r1": None, "r2": None, "unpaired": []}
if info["read_num"] == 1:
samples_dict[name]["r1"] = info["file"]
elif info["read_num"] == 2:
samples_dict[name]["r2"] = info["file"]
else:
samples_dict[name]["unpaired"].append(info["file"])
# Determine if we have valid paired-end samples
paired_samples = []
single_files = []
for name, files in samples_dict.items():
if files["r1"] and files["r2"]:
# Valid pair
paired_samples.append({
"name": name,
"r1": files["r1"],
"r2": files["r2"]
})
else:
# Collect as single-end
if files["r1"]:
single_files.append(files["r1"])
if files["r2"]:
single_files.append(files["r2"])
single_files.extend(files["unpaired"])
# Return paired if we have pairs, otherwise single
if paired_samples:
paired_samples.sort(key=lambda x: x["name"])
return {"samples": paired_samples, "read_type": "paired"}
elif single_files:
single_files.sort(key=lambda x: x.name)
samples = []
for f in single_files:
sample_name = get_basename(f.name)
samples.append({
"name": sample_name,
"r1": f,
"r2": None
})
return {"samples": samples, "read_type": "single"}
return {"samples": [], "read_type": None, "error": "Could not determine read type"}
def main():
st.title("🧬 GenomifySeq")
st.markdown("*End-to-end RNA-seq analysis: quantification, differential expression, and gene set enrichment*")
# Sidebar - System Status
with st.sidebar:
st.header("System Status")
# Check Salmon
salmon_ok = check_salmon_installed()
if salmon_ok:
st.success(f"Salmon: {get_salmon_version()}")
else:
st.error("Salmon not found!")
st.markdown("""
Please run the setup script first:
```bash
./setup.sh
```
Then launch with:
```bash
./run_app.sh
```
""")
return
st.divider()
# Available indices
st.subheader("Available Indices")
existing_indices = [d for d in INDEX_DIR.iterdir() if d.is_dir()] if INDEX_DIR.exists() else []
if existing_indices:
for idx in existing_indices:
st.text(f"• {idx.name}")
else:
st.text("No indices downloaded yet")
st.divider()
# Settings
st.subheader("Settings")
threads = st.slider("CPU threads", 1, os.cpu_count() or 4, min(4, os.cpu_count() or 4))
st.divider()
# About / Methods section for publications
st.subheader("About / Methods")
with st.expander("View methods for publication"):
st.markdown("""
**RNA-seq Quantification and Analysis Methods**
*Copy and adapt this text for your Methods section:*
---
**Transcript Quantification**
Raw RNA-seq reads were quantified using Salmon v1.10 (Patro et al., 2017) with the `--validateMappings` flag for improved accuracy. Reads were mapped to the [human/mouse] GENCODE reference transcriptome (version [X]). Salmon employs a quasi-mapping approach that provides fast and accurate transcript-level abundance estimates.
**Gene-Level Summarization**
Transcript-level counts were summarized to gene-level using tximport (Soneson et al., 2015) with the `lengthScaledTPM` method, which accounts for changes in average transcript length across samples.
**Normalization and Quality Control**
Count data were normalized using the median-of-ratios method implemented in DESeq2 (Love et al., 2014). Principal component analysis (PCA) was performed on variance-stabilized transformed (VST) counts to assess sample clustering and identify potential outliers.
**Differential Expression Analysis**
Differential gene expression was assessed using DESeq2 with default parameters. Genes were considered significantly differentially expressed with an adjusted p-value (Benjamini-Hochberg) < 0.05 and |log2 fold change| > 1.0.
**Gene Set Enrichment Analysis**
Gene set enrichment analysis was performed using fgsea (Korotkevich et al., 2021) with genes pre-ranked by the Wald statistic from DESeq2. Gene sets were obtained from MSigDB (Liberzon et al., 2015).
---
**References**
- Patro R, et al. (2017) Salmon provides fast and bias-aware quantification of transcript expression. *Nature Methods* 14:417-419.
- Soneson C, et al. (2015) Differential analyses for RNA-seq: transcript-level estimates improve gene-level inferences. *F1000Research* 4:1521.
- Love MI, et al. (2014) Moderated estimation of fold change and dispersion for RNA-seq data with DESeq2. *Genome Biology* 15:550.
- Korotkevich G, et al. (2021) Fast gene set enrichment analysis. *bioRxiv* doi:10.1101/060012.
- Liberzon A, et al. (2015) The Molecular Signatures Database Hallmark Gene Set Collection. *Cell Systems* 1:417-425.
""")
# Add copy button for the methods text
methods_text = """Transcript Quantification: Raw RNA-seq reads were quantified using Salmon v1.10 (Patro et al., 2017) with the --validateMappings flag. Reads were mapped to the GENCODE reference transcriptome.
Gene-Level Summarization: Transcript-level counts were summarized to gene-level using tximport (Soneson et al., 2015) with the lengthScaledTPM method.
Normalization and Quality Control: Count data were normalized using DESeq2 (Love et al., 2014). PCA was performed on variance-stabilized transformed counts.
Differential Expression: Differential expression was assessed using DESeq2. Genes with adjusted p-value < 0.05 and |log2FC| > 1.0 were considered significant.
Gene Set Enrichment: GSEA was performed using fgsea (Korotkevich et al., 2021) with genes ranked by DESeq2 Wald statistic."""
st.download_button(
"Download Methods Text",
methods_text,
file_name="rnaseq_methods.txt",
mime="text/plain"
)
st.divider()
# Uninstall
with st.expander("Uninstall"):
st.markdown(
"To fully remove GenomifySeq, delete these two locations:\n\n"
"1. **The app** — drag *GenomifySeq.app* from Applications to Trash\n"
"2. **Dependencies (~2 GB)** — delete the hidden folder `~/.genomifyseq`\n"
"3. **Your data** *(optional)* — delete `~/Documents/GenomifySeq`"
)
if st.button("Reveal dependency folder in Finder", use_container_width=True):
dep_dir = Path.home() / ".genomifyseq"
dep_dir.mkdir(exist_ok=True)
subprocess.Popen(["open", str(dep_dir)])
if st.button("Reveal data folder in Finder", use_container_width=True):
USER_DATA_DIR.mkdir(parents=True, exist_ok=True)
subprocess.Popen(["open", str(USER_DATA_DIR)])
st.divider()
if st.button("Quit App", type="secondary", use_container_width=True):
st.info("Shutting down...")
os._exit(0)
# Main content - Tabs
tab1, tab2, tab3, tab4, tab5 = st.tabs(["📁 Select Data", "📚 Reference Index", "▶️ Run Pipeline", "📊 Results", "🔬 Analysis"])
# Tab 1: Select Data (Local Directory)
with tab1:
st.header("Select FASTQ Data Directory")
st.markdown("""
Enter the path to a folder containing your FASTQ files. The app will automatically detect:
- **Paired-end** samples (files with `_R1`/`_R2` or `_1`/`_2` patterns)
- **Single-end** samples
Supported formats: `.fastq`, `.fq`, `.fastq.gz`, `.fq.gz`
""")
# Directory input with Browse button
col_input, col_browse = st.columns([4, 1])
with col_input:
data_dir = st.text_input(
"FASTQ directory path:",
value=st.session_state.get("data_dir_path", ""),
help="Enter the full path to your FASTQ files folder",
placeholder="Click 'Browse' or paste a path..."
)
with col_browse:
st.markdown("<br>", unsafe_allow_html=True) # Align button with input
if st.button("📂 Browse"):
selected = open_folder_dialog(st.session_state.get("data_dir_path"))
if selected:
st.session_state.data_dir_path = selected
st.rerun()
col1, col2 = st.columns([1, 3])
with col1:
scan_button = st.button("🔍 Scan Directory", type="primary", disabled=not data_dir)
if scan_button and data_dir:
data_path = Path(data_dir)
if not data_path.exists():
st.error(f"Directory not found: {data_dir}")
elif not data_path.is_dir():
st.error(f"Not a directory: {data_dir}")
else:
# Warn if files are on cloud storage (Google Drive, iCloud, Dropbox, OneDrive)
cloud_keywords = ["CloudStorage", "Google Drive", "GoogleDrive", "iCloud", "Dropbox", "OneDrive"]
if any(kw in data_dir for kw in cloud_keywords):
st.warning(
"These files appear to be on cloud storage (e.g. Google Drive). "
"Large FASTQ files streamed from cloud storage often fail mid-processing. "
"**Copy your FASTQ files to a local folder first** for reliable results."
)
st.session_state.data_dir_path = data_dir
with st.spinner("Scanning for FASTQ files..."):
result = scan_fastq_directory(data_path)
st.session_state.detected_samples = result
# Show detected samples
if st.session_state.detected_samples:
result = st.session_state.detected_samples
if "error" in result:
st.error(result["error"])
elif result["samples"]:
read_type = result["read_type"]
samples = result["samples"]
st.success(f"Found {len(samples)} {read_type}-end samples")
# Display samples in a table
st.subheader("Detected Samples")
if read_type == "paired":
sample_data = []
for s in samples:
sample_data.append({
"Sample Name": s["name"],
"Read 1": s["r1"].name,
"Read 2": s["r2"].name
})
st.dataframe(pd.DataFrame(sample_data), width="stretch")
else:
sample_data = []
for s in samples:
sample_data.append({
"Sample Name": s["name"],
"File": s["r1"].name
})
st.dataframe(pd.DataFrame(sample_data), width="stretch")
# Store for pipeline
st.session_state.samples_ready = True
# Tab 2: Reference Index
with tab2:
st.header("Reference Transcriptome Index")
st.markdown("""
Select a reference transcriptome for quantification. You can either:
1. **Download pre-built** - Human or Mouse from GENCODE
2. **Use existing** - Select a previously downloaded index
3. **Build from FASTA** - Provide your own transcriptome file path
""")
index_source = st.radio(
"Index source:",
["Download pre-built", "Use existing", "Build from FASTA"],
horizontal=True
)
if index_source == "Download pre-built":
organism = st.selectbox(
"Select organism:",
["human_gencode_v36", "human_gencode_v44", "mouse_gencode_vM25", "mouse_gencode_vM33"],
format_func=lambda x: {
"human_gencode_v36": "Human (GENCODE v36 / GRCh38.p13)",
"human_gencode_v44": "Human (GENCODE v44 / GRCh38.p14)",
"mouse_gencode_vM25": "Mouse (GENCODE vM25 / GRCm38)",
"mouse_gencode_vM33": "Mouse (GENCODE vM33 / GRCm39)"
}.get(x, x)
)
index_path = INDEX_DIR / organism
if (index_path / "complete_ref_lens.bin").exists():
st.success(f"Index already downloaded: {index_path}")