Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -483,7 +483,7 @@ def parse_input_csv(filepath):
|
|
| 483 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 484 |
# MAIN ANALYSIS
|
| 485 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 486 |
-
def run_mta_analysis(input_file, target_markers):
|
| 487 |
try:
|
| 488 |
if input_file is None:
|
| 489 |
return ("β οΈ Please upload a CSV file.", None, None, None, None, None, None)
|
|
@@ -494,6 +494,11 @@ def run_mta_analysis(input_file, target_markers):
|
|
| 494 |
for d in [results_dir, plots_dir]:
|
| 495 |
os.makedirs(d, exist_ok=True)
|
| 496 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 497 |
# ββ LOAD & PARSE ββββββββββββββββββββββββββ
|
| 498 |
sample_ids, phenotypes, genotypes, marker_names, chromosome_dict = \
|
| 499 |
parse_input_csv(input_file)
|
|
@@ -506,15 +511,52 @@ def run_mta_analysis(input_file, target_markers):
|
|
| 506 |
n_markers = len(marker_names)
|
| 507 |
|
| 508 |
# ββ QC ββββββββββββββββββββββββββββββββββββ
|
|
|
|
| 509 |
miss_m = np.isnan(genotypes).sum(axis=0) / max(n_samples, 1)
|
|
|
|
| 510 |
miss_s = np.isnan(genotypes).sum(axis=1) / max(n_markers, 1)
|
| 511 |
-
maf = np.array([
|
| 512 |
-
min(np.nanmean(genotypes[:,i])/2, 1-np.nanmean(genotypes[:,i])/2)
|
| 513 |
-
if not np.all(np.isnan(genotypes[:,i])) else 0
|
| 514 |
-
for i in range(n_markers)])
|
| 515 |
|
| 516 |
-
|
| 517 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 518 |
|
| 519 |
geno_qc = genotypes[np.ix_(qc_s, qc_m)].copy()
|
| 520 |
pheno_qc = phenotypes[qc_s]
|
|
@@ -525,12 +567,13 @@ def run_mta_analysis(input_file, target_markers):
|
|
| 525 |
n_rm_m = n_markers - len(mnames_qc)
|
| 526 |
n_rm_s = n_samples - len(ids_qc)
|
| 527 |
|
| 528 |
-
# Impute missing
|
| 529 |
for i in range(geno_qc.shape[1]):
|
| 530 |
-
col
|
| 531 |
mask = np.isnan(col)
|
| 532 |
if mask.any():
|
| 533 |
-
|
|
|
|
| 534 |
|
| 535 |
# Remove samples with NaN phenotype
|
| 536 |
valid_pheno = ~np.isnan(pheno_qc)
|
|
@@ -539,19 +582,22 @@ def run_mta_analysis(input_file, target_markers):
|
|
| 539 |
ids_qc = ids_qc[valid_pheno]
|
| 540 |
|
| 541 |
# ββ MINIMUM SAMPLE GUARD ββββββββββββββββββ
|
| 542 |
-
# FIX: Warn early if too few samples survive QC.
|
| 543 |
-
# mutual_info_regression requires n_neighbors < n_samples_fit.
|
| 544 |
-
# With < 10 samples, results are also statistically unreliable.
|
| 545 |
if len(ids_qc) < 10:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 546 |
return (
|
| 547 |
f"## β οΈ Insufficient Samples After QC\n\n"
|
| 548 |
-
f"Only **{len(ids_qc)}** sample(s) passed QC filters "
|
| 549 |
f"(started with {n_samples}).\n\n"
|
| 550 |
-
f"
|
| 551 |
-
f"
|
| 552 |
-
f"-
|
| 553 |
-
f"-
|
| 554 |
-
f"
|
|
|
|
|
|
|
| 555 |
f"**Tip:** Use `-1` to encode missing genotypes, not blanks or text.",
|
| 556 |
None, None, None, None, None, None
|
| 557 |
)
|
|
@@ -736,9 +782,10 @@ def run_mta_analysis(input_file, target_markers):
|
|
| 736 |
| Samples (raw β QC) | {n_samples} β **{len(ids_qc)}** ({n_rm_s} removed) |
|
| 737 |
| Markers (raw β QC) | {n_markers} β **{len(mnames_qc)}** ({n_rm_m} removed) |
|
| 738 |
| Chromosomes | **{len(unique_chroms)}** |
|
| 739 |
-
| MAF filter |
|
| 740 |
-
|
|
| 741 |
-
|
|
|
|
| 742 |
## π¬ GWAS Results
|
| 743 |
| Metric | Value |
|
| 744 |
|--------|-------|
|
|
@@ -1163,16 +1210,35 @@ with gr.Blocks(css=THEME_CSS, title="MTA Analysis Platform") as app:
|
|
| 1163 |
gr.HTML(HERO_HTML)
|
| 1164 |
|
| 1165 |
with gr.Row():
|
| 1166 |
-
with gr.Column(scale=1, min_width=
|
| 1167 |
gr.HTML(FMT_HTML)
|
| 1168 |
gr.HTML('<div class="sec-head">Configure</div>')
|
| 1169 |
|
| 1170 |
input_file = gr.File(label="π Upload CSV File", file_types=[".csv"])
|
|
|
|
| 1171 |
target_markers = gr.Slider(
|
| 1172 |
100, 5000, value=3000, step=100,
|
| 1173 |
-
label="Target Markers for ML Selection",
|
| 1174 |
info="Controls ML feature voting; GWAS p-values are unaffected")
|
| 1175 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1176 |
with gr.Row(elem_classes=["run-btn"]):
|
| 1177 |
run_btn = gr.Button("β¨ Run GWAS Analysis", variant="primary", size="lg")
|
| 1178 |
|
|
@@ -1181,7 +1247,10 @@ with gr.Blocks(css=THEME_CSS, title="MTA Analysis Platform") as app:
|
|
| 1181 |
with gr.Column(scale=2):
|
| 1182 |
gr.HTML('<div class="sec-head">Results Summary</div>')
|
| 1183 |
with gr.Column(elem_classes=["sum-card"]):
|
| 1184 |
-
summary_out = gr.Markdown(
|
|
|
|
|
|
|
|
|
|
| 1185 |
|
| 1186 |
gr.HTML('<div class="sec-head" style="margin-top:10px">Visualizations</div>')
|
| 1187 |
|
|
@@ -1216,9 +1285,9 @@ with gr.Blocks(css=THEME_CSS, title="MTA Analysis Platform") as app:
|
|
| 1216 |
|
| 1217 |
run_btn.click(
|
| 1218 |
fn=run_mta_analysis,
|
| 1219 |
-
inputs=[input_file, target_markers],
|
| 1220 |
outputs=[summary_out, manhattan_out, qq_out, ld_out,
|
| 1221 |
vol_out, top_out, download_out])
|
| 1222 |
|
| 1223 |
if __name__ == "__main__":
|
| 1224 |
-
app.launch(share=True, show_error=True)
|
|
|
|
| 483 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 484 |
# MAIN ANALYSIS
|
| 485 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 486 |
+
def run_mta_analysis(input_file, target_markers, miss_rate_sample, miss_rate_marker, maf_thresh):
|
| 487 |
try:
|
| 488 |
if input_file is None:
|
| 489 |
return ("β οΈ Please upload a CSV file.", None, None, None, None, None, None)
|
|
|
|
| 494 |
for d in [results_dir, plots_dir]:
|
| 495 |
os.makedirs(d, exist_ok=True)
|
| 496 |
|
| 497 |
+
# Convert slider percent values β fractions
|
| 498 |
+
miss_s_thresh = miss_rate_sample / 100.0 # e.g. 50 β 0.50
|
| 499 |
+
miss_m_thresh = miss_rate_marker / 100.0
|
| 500 |
+
maf_thresh_f = maf_thresh / 100.0
|
| 501 |
+
|
| 502 |
# ββ LOAD & PARSE ββββββββββββββββββββββββββ
|
| 503 |
sample_ids, phenotypes, genotypes, marker_names, chromosome_dict = \
|
| 504 |
parse_input_csv(input_file)
|
|
|
|
| 511 |
n_markers = len(marker_names)
|
| 512 |
|
| 513 |
# ββ QC ββββββββββββββββββββββββββββββββββββ
|
| 514 |
+
# Per-marker missing rate and MAF
|
| 515 |
miss_m = np.isnan(genotypes).sum(axis=0) / max(n_samples, 1)
|
| 516 |
+
# Per-sample missing rate
|
| 517 |
miss_s = np.isnan(genotypes).sum(axis=1) / max(n_markers, 1)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 518 |
|
| 519 |
+
# MAF: computed from 0/1/2 dosage (nanmean/2 gives allele freq)
|
| 520 |
+
maf = np.zeros(n_markers)
|
| 521 |
+
for i in range(n_markers):
|
| 522 |
+
col = genotypes[:, i]
|
| 523 |
+
valid = col[~np.isnan(col)]
|
| 524 |
+
if len(valid) > 0:
|
| 525 |
+
freq = np.mean(valid) / 2.0 # alt allele frequency
|
| 526 |
+
maf[i] = min(freq, 1.0 - freq)
|
| 527 |
+
|
| 528 |
+
# Apply user-specified thresholds
|
| 529 |
+
qc_m = (miss_m < miss_m_thresh) & (maf >= maf_thresh_f)
|
| 530 |
+
qc_s = miss_s < miss_s_thresh
|
| 531 |
+
|
| 532 |
+
# ββ ADAPTIVE FALLBACK βββββββββββββββββββββ
|
| 533 |
+
# If QC is too aggressive, automatically relax thresholds step by step
|
| 534 |
+
# so we always retain enough samples to run the analysis.
|
| 535 |
+
fallback_applied = False
|
| 536 |
+
fallback_msg = ""
|
| 537 |
+
for relaxed_s, relaxed_m in [
|
| 538 |
+
(miss_s_thresh, miss_m_thresh), # original
|
| 539 |
+
(0.60, 0.60),
|
| 540 |
+
(0.70, 0.70),
|
| 541 |
+
(0.80, 0.80),
|
| 542 |
+
(0.90, 0.90),
|
| 543 |
+
(1.00, 1.00), # keep everything
|
| 544 |
+
]:
|
| 545 |
+
qc_m_try = (miss_m < relaxed_m) & (maf >= maf_thresh_f)
|
| 546 |
+
qc_s_try = miss_s < relaxed_s
|
| 547 |
+
n_ok = int(qc_s_try.sum())
|
| 548 |
+
if n_ok >= 10:
|
| 549 |
+
qc_m = qc_m_try
|
| 550 |
+
qc_s = qc_s_try
|
| 551 |
+
if relaxed_s > miss_s_thresh or relaxed_m > miss_m_thresh:
|
| 552 |
+
fallback_applied = True
|
| 553 |
+
fallback_msg = (
|
| 554 |
+
f"\n> β οΈ **QC thresholds auto-relaxed** to "
|
| 555 |
+
f"sample missing < {relaxed_s*100:.0f}% / "
|
| 556 |
+
f"marker missing < {relaxed_m*100:.0f}% "
|
| 557 |
+
f"to retain β₯10 samples.\n"
|
| 558 |
+
)
|
| 559 |
+
break
|
| 560 |
|
| 561 |
geno_qc = genotypes[np.ix_(qc_s, qc_m)].copy()
|
| 562 |
pheno_qc = phenotypes[qc_s]
|
|
|
|
| 567 |
n_rm_m = n_markers - len(mnames_qc)
|
| 568 |
n_rm_s = n_samples - len(ids_qc)
|
| 569 |
|
| 570 |
+
# Impute missing genotypes with per-marker mean
|
| 571 |
for i in range(geno_qc.shape[1]):
|
| 572 |
+
col = geno_qc[:, i]
|
| 573 |
mask = np.isnan(col)
|
| 574 |
if mask.any():
|
| 575 |
+
fill = np.nanmean(col) if not np.all(mask) else 0.0
|
| 576 |
+
geno_qc[mask, i] = fill
|
| 577 |
|
| 578 |
# Remove samples with NaN phenotype
|
| 579 |
valid_pheno = ~np.isnan(pheno_qc)
|
|
|
|
| 582 |
ids_qc = ids_qc[valid_pheno]
|
| 583 |
|
| 584 |
# ββ MINIMUM SAMPLE GUARD ββββββββββββββββββ
|
|
|
|
|
|
|
|
|
|
| 585 |
if len(ids_qc) < 10:
|
| 586 |
+
# Compute per-sample missing rates to help user diagnose
|
| 587 |
+
sample_miss_pct = (np.isnan(genotypes).sum(axis=1) / max(n_markers, 1) * 100)
|
| 588 |
+
worst5 = np.sort(sample_miss_pct)[::-1][:5]
|
| 589 |
+
worst5_str = ", ".join(f"{v:.0f}%" for v in worst5)
|
| 590 |
return (
|
| 591 |
f"## β οΈ Insufficient Samples After QC\n\n"
|
| 592 |
+
f"Only **{len(ids_qc)}** sample(s) passed all QC filters "
|
| 593 |
f"(started with {n_samples}).\n\n"
|
| 594 |
+
f"**Diagnosis:**\n"
|
| 595 |
+
f"- Sample missing rate filter used: **< {miss_s_thresh*100:.0f}%**\n"
|
| 596 |
+
f"- Samples with most missing data: `{worst5_str}`\n"
|
| 597 |
+
f"- Try increasing the **Sample Missing Rate** slider to 50β80%\n\n"
|
| 598 |
+
f"**Your data appears to have high missing rates per sample** "
|
| 599 |
+
f"(common in large rice/plant GWAS panels). "
|
| 600 |
+
f"Raising the missing rate threshold to 50% or higher is standard practice.\n\n"
|
| 601 |
f"**Tip:** Use `-1` to encode missing genotypes, not blanks or text.",
|
| 602 |
None, None, None, None, None, None
|
| 603 |
)
|
|
|
|
| 782 |
| Samples (raw β QC) | {n_samples} β **{len(ids_qc)}** ({n_rm_s} removed) |
|
| 783 |
| Markers (raw β QC) | {n_markers} β **{len(mnames_qc)}** ({n_rm_m} removed) |
|
| 784 |
| Chromosomes | **{len(unique_chroms)}** |
|
| 785 |
+
| MAF filter | β₯ {maf_thresh:.1f}% |
|
| 786 |
+
| Sample missing rate filter | < {miss_rate_sample:.0f}% |
|
| 787 |
+
| Marker missing rate filter | < {miss_rate_marker:.0f}% |
|
| 788 |
+
{fallback_msg}
|
| 789 |
## π¬ GWAS Results
|
| 790 |
| Metric | Value |
|
| 791 |
|--------|-------|
|
|
|
|
| 1210 |
gr.HTML(HERO_HTML)
|
| 1211 |
|
| 1212 |
with gr.Row():
|
| 1213 |
+
with gr.Column(scale=1, min_width=320):
|
| 1214 |
gr.HTML(FMT_HTML)
|
| 1215 |
gr.HTML('<div class="sec-head">Configure</div>')
|
| 1216 |
|
| 1217 |
input_file = gr.File(label="π Upload CSV File", file_types=[".csv"])
|
| 1218 |
+
|
| 1219 |
target_markers = gr.Slider(
|
| 1220 |
100, 5000, value=3000, step=100,
|
| 1221 |
+
label="π― Target Markers for ML Selection",
|
| 1222 |
info="Controls ML feature voting; GWAS p-values are unaffected")
|
| 1223 |
|
| 1224 |
+
gr.HTML('<div class="sec-head" style="margin-top:16px">QC Thresholds</div>')
|
| 1225 |
+
|
| 1226 |
+
miss_rate_sample = gr.Slider(
|
| 1227 |
+
10, 100, value=50, step=5,
|
| 1228 |
+
label="π Sample Missing Rate Cutoff (%)",
|
| 1229 |
+
info="Remove samples with more than this % missing genotypes. "
|
| 1230 |
+
"Raise to 50β80% for typical plant GWAS panels with many -1 values.")
|
| 1231 |
+
|
| 1232 |
+
miss_rate_marker = gr.Slider(
|
| 1233 |
+
10, 100, value=50, step=5,
|
| 1234 |
+
label="𧬠Marker Missing Rate Cutoff (%)",
|
| 1235 |
+
info="Remove markers with more than this % missing across samples.")
|
| 1236 |
+
|
| 1237 |
+
maf_thresh = gr.Slider(
|
| 1238 |
+
0.0, 10.0, value=1.0, step=0.5,
|
| 1239 |
+
label="βοΈ Minor Allele Frequency (MAF) Threshold (%)",
|
| 1240 |
+
info="Remove markers with MAF below this value. 1% is standard; lower if needed.")
|
| 1241 |
+
|
| 1242 |
with gr.Row(elem_classes=["run-btn"]):
|
| 1243 |
run_btn = gr.Button("β¨ Run GWAS Analysis", variant="primary", size="lg")
|
| 1244 |
|
|
|
|
| 1247 |
with gr.Column(scale=2):
|
| 1248 |
gr.HTML('<div class="sec-head">Results Summary</div>')
|
| 1249 |
with gr.Column(elem_classes=["sum-card"]):
|
| 1250 |
+
summary_out = gr.Markdown(
|
| 1251 |
+
value="*Upload a CSV file and click **Run GWAS Analysis** to begin.*\n\n"
|
| 1252 |
+
"**π‘ Tip for high-missing datasets (rice/plant panels):** "
|
| 1253 |
+
"Set Sample & Marker Missing Rate to **50%** before running.")
|
| 1254 |
|
| 1255 |
gr.HTML('<div class="sec-head" style="margin-top:10px">Visualizations</div>')
|
| 1256 |
|
|
|
|
| 1285 |
|
| 1286 |
run_btn.click(
|
| 1287 |
fn=run_mta_analysis,
|
| 1288 |
+
inputs=[input_file, target_markers, miss_rate_sample, miss_rate_marker, maf_thresh],
|
| 1289 |
outputs=[summary_out, manhattan_out, qq_out, ld_out,
|
| 1290 |
vol_out, top_out, download_out])
|
| 1291 |
|
| 1292 |
if __name__ == "__main__":
|
| 1293 |
+
app.launch(share=True, show_error=True)
|