Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,11 +1,16 @@
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
"""
|
| 3 |
-
MTA Analysis Tool v6.
|
| 4 |
Soft Pastel Theme Β· Corrected CSV Format Parser
|
| 5 |
CSV Format:
|
| 6 |
Row 1 (header): ID, Phenotype, marker1, marker2, ...
|
| 7 |
Row 2 (chr row): -, -, chr_number, chr_number, ...
|
| 8 |
Row 3+: sample_id, phenotype_value, genotype, genotype, ...
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
"""
|
| 10 |
|
| 11 |
import gradio as gr
|
|
@@ -438,10 +443,6 @@ def plot_top_hits(marker_names, chromosomes, p_values, effects, bonf_thresh,
|
|
| 438 |
|
| 439 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 440 |
# CSV FORMAT PARSER
|
| 441 |
-
# Format:
|
| 442 |
-
# Row 1 (header): ID, Phenotype, marker1, marker2, ...
|
| 443 |
-
# Row 2 (chr row): anything, anything, chr_num, chr_num, ...
|
| 444 |
-
# Row 3+: sample_id, pheno_value, geno, geno, ...
|
| 445 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 446 |
def parse_input_csv(filepath):
|
| 447 |
"""
|
|
@@ -451,10 +452,10 @@ def parse_input_csv(filepath):
|
|
| 451 |
- Rows 2+: actual sample data
|
| 452 |
"""
|
| 453 |
df = pd.read_csv(filepath, header=0, dtype=str)
|
| 454 |
-
|
| 455 |
# Identify marker columns (everything after col 0=ID, col 1=Phenotype)
|
| 456 |
marker_cols = df.columns[2:].tolist()
|
| 457 |
-
|
| 458 |
# First row = chromosome assignments for markers
|
| 459 |
chr_row = df.iloc[0]
|
| 460 |
chromosome_dict = {}
|
|
@@ -464,18 +465,18 @@ def parse_input_csv(filepath):
|
|
| 464 |
if val.endswith('.0'):
|
| 465 |
val = val[:-2]
|
| 466 |
chromosome_dict[m] = val
|
| 467 |
-
|
| 468 |
# Remaining rows = actual sample data
|
| 469 |
df_samples = df.iloc[1:].reset_index(drop=True)
|
| 470 |
-
|
| 471 |
sample_ids = df_samples.iloc[:, 0].astype(str).values
|
| 472 |
phenotypes = pd.to_numeric(df_samples.iloc[:, 1], errors='coerce').values
|
| 473 |
-
|
| 474 |
# Genotype matrix β replace -1 with NaN (missing data code)
|
| 475 |
geno_raw = df_samples[marker_cols].apply(pd.to_numeric, errors='coerce')
|
| 476 |
geno_raw = geno_raw.replace(-1, np.nan)
|
| 477 |
genotypes = geno_raw.values
|
| 478 |
-
|
| 479 |
return sample_ids, phenotypes, genotypes, marker_cols, chromosome_dict
|
| 480 |
|
| 481 |
|
|
@@ -537,6 +538,24 @@ def run_mta_analysis(input_file, target_markers):
|
|
| 537 |
pheno_qc = pheno_qc[valid_pheno]
|
| 538 |
ids_qc = ids_qc[valid_pheno]
|
| 539 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 540 |
TARGET = min(int(target_markers), len(mnames_qc))
|
| 541 |
|
| 542 |
# ββ GWAS ββββββββββββββββββββββββββββββββββ
|
|
@@ -572,17 +591,38 @@ def run_mta_analysis(input_file, target_markers):
|
|
| 572 |
X = scaler.fit_transform(geno_qc)
|
| 573 |
y = pheno_qc
|
| 574 |
|
| 575 |
-
|
| 576 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 577 |
rf_fs.fit(X, y)
|
| 578 |
|
| 579 |
-
gb_fs = GradientBoostingRegressor(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 580 |
gb_fs.fit(X, y)
|
| 581 |
|
| 582 |
-
|
|
|
|
|
|
|
| 583 |
en_fs.fit(X, y)
|
| 584 |
|
| 585 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 586 |
fsc, _ = f_regression(X, y)
|
| 587 |
|
| 588 |
votes = np.zeros(len(mnames_qc))
|
|
@@ -630,10 +670,12 @@ def run_mta_analysis(input_file, target_markers):
|
|
| 630 |
pd.DataFrame({
|
| 631 |
'Metric': ['Samples_raw','Samples_QC','Markers_raw','Markers_QC',
|
| 632 |
'Target_Selected','Chromosomes',
|
| 633 |
-
'Bonferroni_threshold_logP','N_Significant','N_Suggestive'
|
|
|
|
| 634 |
'Value' : [n_samples, len(ids_qc), n_markers, len(mnames_qc),
|
| 635 |
TARGET, len(unique_chroms),
|
| 636 |
-
round(bonf,4), n_sig, n_sugg
|
|
|
|
| 637 |
}).to_csv(os.path.join(results_dir,'qc_summary.csv'), index=False)
|
| 638 |
|
| 639 |
# ββ PLOTS βββββββββββββββββββββββββββββββββ
|
|
@@ -680,6 +722,13 @@ def run_mta_analysis(input_file, target_markers):
|
|
| 680 |
f"{int(r['N_Significant'])} | {r['Best_logP']:.3f} | {r['Top_Marker']} |"
|
| 681 |
for _, r in chr_df.head(5).iterrows())
|
| 682 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 683 |
summary = f"""
|
| 684 |
## π QC Summary
|
| 685 |
| Metric | Value |
|
|
@@ -701,7 +750,7 @@ def run_mta_analysis(input_file, target_markers):
|
|
| 701 |
|
| 702 |
## π LD Summary
|
| 703 |
Global mean rΒ² = **{gm_r2:.4f}** β {ld_txt}
|
| 704 |
-
|
| 705 |
## π Top 8 GWAS Hits
|
| 706 |
| Rank | Marker | Chr | Effect Ξ² | P-value | βlogββP |
|
| 707 |
|------|--------|-----|----------|---------|---------|
|
|
@@ -1072,7 +1121,8 @@ FMT_HTML = """
|
|
| 1072 |
<span class="val">2</span> , ...
|
| 1073 |
<span class="note">
|
| 1074 |
β οΈ <strong>Missing values:</strong> Use <code>-1</code> for missing genotypes β they are automatically converted to NaN during QC.<br>
|
| 1075 |
-
β
<strong>Genotype coding:</strong> 0 = homozygous ref Β· 1 = heterozygous Β· 2 = homozygous alt
|
|
|
|
| 1076 |
</span>
|
| 1077 |
</div>
|
| 1078 |
"""
|
|
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
"""
|
| 3 |
+
MTA Analysis Tool v6.1
|
| 4 |
Soft Pastel Theme Β· Corrected CSV Format Parser
|
| 5 |
CSV Format:
|
| 6 |
Row 1 (header): ID, Phenotype, marker1, marker2, ...
|
| 7 |
Row 2 (chr row): -, -, chr_number, chr_number, ...
|
| 8 |
Row 3+: sample_id, phenotype_value, genotype, genotype, ...
|
| 9 |
+
|
| 10 |
+
FIXES in v6.1:
|
| 11 |
+
- mutual_info_regression n_neighbors dynamically set to min(3, n_samples-1)
|
| 12 |
+
- Minimum sample guard added (< 10 samples β early warning)
|
| 13 |
+
- GradientBoostingRegressor / RandomForestRegressor also guarded for tiny datasets
|
| 14 |
"""
|
| 15 |
|
| 16 |
import gradio as gr
|
|
|
|
| 443 |
|
| 444 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 445 |
# CSV FORMAT PARSER
|
|
|
|
|
|
|
|
|
|
|
|
|
| 446 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 447 |
def parse_input_csv(filepath):
|
| 448 |
"""
|
|
|
|
| 452 |
- Rows 2+: actual sample data
|
| 453 |
"""
|
| 454 |
df = pd.read_csv(filepath, header=0, dtype=str)
|
| 455 |
+
|
| 456 |
# Identify marker columns (everything after col 0=ID, col 1=Phenotype)
|
| 457 |
marker_cols = df.columns[2:].tolist()
|
| 458 |
+
|
| 459 |
# First row = chromosome assignments for markers
|
| 460 |
chr_row = df.iloc[0]
|
| 461 |
chromosome_dict = {}
|
|
|
|
| 465 |
if val.endswith('.0'):
|
| 466 |
val = val[:-2]
|
| 467 |
chromosome_dict[m] = val
|
| 468 |
+
|
| 469 |
# Remaining rows = actual sample data
|
| 470 |
df_samples = df.iloc[1:].reset_index(drop=True)
|
| 471 |
+
|
| 472 |
sample_ids = df_samples.iloc[:, 0].astype(str).values
|
| 473 |
phenotypes = pd.to_numeric(df_samples.iloc[:, 1], errors='coerce').values
|
| 474 |
+
|
| 475 |
# Genotype matrix β replace -1 with NaN (missing data code)
|
| 476 |
geno_raw = df_samples[marker_cols].apply(pd.to_numeric, errors='coerce')
|
| 477 |
geno_raw = geno_raw.replace(-1, np.nan)
|
| 478 |
genotypes = geno_raw.values
|
| 479 |
+
|
| 480 |
return sample_ids, phenotypes, genotypes, marker_cols, chromosome_dict
|
| 481 |
|
| 482 |
|
|
|
|
| 538 |
pheno_qc = pheno_qc[valid_pheno]
|
| 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"GWAS requires **at least 10 samples** for statistically meaningful results. "
|
| 551 |
+
f"Please check:\n"
|
| 552 |
+
f"- Your CSV has enough data rows (each row after the chromosome row = 1 sample)\n"
|
| 553 |
+
f"- Missing rate per sample is < 10% (samples with β₯10% missing genotypes are removed)\n"
|
| 554 |
+
f"- Phenotype values are numeric and not all missing\n\n"
|
| 555 |
+
f"**Tip:** Use `-1` to encode missing genotypes, not blanks or text.",
|
| 556 |
+
None, None, None, None, None, None
|
| 557 |
+
)
|
| 558 |
+
|
| 559 |
TARGET = min(int(target_markers), len(mnames_qc))
|
| 560 |
|
| 561 |
# ββ GWAS ββββββββββββββββββββββββββββββββββ
|
|
|
|
| 591 |
X = scaler.fit_transform(geno_qc)
|
| 592 |
y = pheno_qc
|
| 593 |
|
| 594 |
+
n_samples_fit = len(y)
|
| 595 |
+
|
| 596 |
+
# Guard: cap n_estimators/tree depth for very small datasets
|
| 597 |
+
safe_depth_rf = min(10, max(2, n_samples_fit // 5))
|
| 598 |
+
safe_depth_gb = min(5, max(1, n_samples_fit // 10))
|
| 599 |
+
|
| 600 |
+
rf_fs = RandomForestRegressor(
|
| 601 |
+
n_estimators=100,
|
| 602 |
+
max_depth=safe_depth_rf,
|
| 603 |
+
random_state=42,
|
| 604 |
+
n_jobs=-1
|
| 605 |
+
)
|
| 606 |
rf_fs.fit(X, y)
|
| 607 |
|
| 608 |
+
gb_fs = GradientBoostingRegressor(
|
| 609 |
+
n_estimators=100,
|
| 610 |
+
max_depth=safe_depth_gb,
|
| 611 |
+
random_state=42
|
| 612 |
+
)
|
| 613 |
gb_fs.fit(X, y)
|
| 614 |
|
| 615 |
+
# ElasticNet: use cv = min(5, n_samples) folds
|
| 616 |
+
safe_cv = min(5, max(2, n_samples_fit))
|
| 617 |
+
en_fs = ElasticNetCV(cv=safe_cv, random_state=42, max_iter=5000)
|
| 618 |
en_fs.fit(X, y)
|
| 619 |
|
| 620 |
+
# FIX: mutual_info_regression requires n_neighbors < n_samples_fit.
|
| 621 |
+
# Default n_neighbors=3 crashes when n_samples_fit <= 3.
|
| 622 |
+
# We set it to max(1, min(3, n_samples_fit - 1)) to be safe for any size.
|
| 623 |
+
safe_n_neighbors = max(1, min(3, n_samples_fit - 1))
|
| 624 |
+
mi = mutual_info_regression(X, y, random_state=42, n_neighbors=safe_n_neighbors)
|
| 625 |
+
|
| 626 |
fsc, _ = f_regression(X, y)
|
| 627 |
|
| 628 |
votes = np.zeros(len(mnames_qc))
|
|
|
|
| 670 |
pd.DataFrame({
|
| 671 |
'Metric': ['Samples_raw','Samples_QC','Markers_raw','Markers_QC',
|
| 672 |
'Target_Selected','Chromosomes',
|
| 673 |
+
'Bonferroni_threshold_logP','N_Significant','N_Suggestive',
|
| 674 |
+
'MI_n_neighbors_used'],
|
| 675 |
'Value' : [n_samples, len(ids_qc), n_markers, len(mnames_qc),
|
| 676 |
TARGET, len(unique_chroms),
|
| 677 |
+
round(bonf,4), n_sig, n_sugg,
|
| 678 |
+
safe_n_neighbors]
|
| 679 |
}).to_csv(os.path.join(results_dir,'qc_summary.csv'), index=False)
|
| 680 |
|
| 681 |
# ββ PLOTS βββββββββββββββββββββββββββββββββ
|
|
|
|
| 722 |
f"{int(r['N_Significant'])} | {r['Best_logP']:.3f} | {r['Top_Marker']} |"
|
| 723 |
for _, r in chr_df.head(5).iterrows())
|
| 724 |
|
| 725 |
+
# Note if n_neighbors was reduced
|
| 726 |
+
mi_note = ""
|
| 727 |
+
if safe_n_neighbors < 3:
|
| 728 |
+
mi_note = (f"\n> βΉοΈ **Note:** Mutual information estimation used "
|
| 729 |
+
f"`n_neighbors={safe_n_neighbors}` (reduced from default 3) "
|
| 730 |
+
f"due to small sample size ({n_samples_fit} samples after QC).\n")
|
| 731 |
+
|
| 732 |
summary = f"""
|
| 733 |
## π QC Summary
|
| 734 |
| Metric | Value |
|
|
|
|
| 750 |
|
| 751 |
## π LD Summary
|
| 752 |
Global mean rΒ² = **{gm_r2:.4f}** β {ld_txt}
|
| 753 |
+
{mi_note}
|
| 754 |
## π Top 8 GWAS Hits
|
| 755 |
| Rank | Marker | Chr | Effect Ξ² | P-value | βlogββP |
|
| 756 |
|------|--------|-----|----------|---------|---------|
|
|
|
|
| 1121 |
<span class="val">2</span> , ...
|
| 1122 |
<span class="note">
|
| 1123 |
β οΈ <strong>Missing values:</strong> Use <code>-1</code> for missing genotypes β they are automatically converted to NaN during QC.<br>
|
| 1124 |
+
β
<strong>Genotype coding:</strong> 0 = homozygous ref Β· 1 = heterozygous Β· 2 = homozygous alt<br>
|
| 1125 |
+
π <strong>Minimum samples:</strong> At least <strong>10 samples</strong> required after QC for reliable GWAS results.
|
| 1126 |
</span>
|
| 1127 |
</div>
|
| 1128 |
"""
|