Spaces:
Running
Running
Upload 5 files
Browse files- README.md +7 -9
- app.py +89 -0
- requirements.txt +7 -0
- runtime.txt +1 -0
- user_script.py +161 -0
README.md
CHANGED
|
@@ -1,14 +1,12 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
|
| 5 |
-
colorTo: yellow
|
| 6 |
-
sdk: gradio
|
| 7 |
-
sdk_version: 5.49.1
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
-
license: other
|
| 11 |
-
short_description: pneumococcal serotyping based on bag-of-words approach
|
| 12 |
---
|
| 13 |
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Serotype k-mer classifier (STRICT uniques)
|
| 3 |
+
emoji: 🧬
|
| 4 |
+
sdk: streamlit
|
|
|
|
|
|
|
|
|
|
| 5 |
app_file: app.py
|
| 6 |
pinned: false
|
|
|
|
|
|
|
| 7 |
---
|
| 8 |
|
| 9 |
+
# Serotype k-mer classifier — STRICT uniques (Streamlit)
|
| 10 |
+
|
| 11 |
+
Upload **known** and **unknown** sequences as FASTA files or a ZIP containing multiple FASTA files.
|
| 12 |
+
Choose DNA/Protein, enter k values, and click **Run**. The app computes strictly unique k-mers per serotype across k and classifies unknowns.
|
app.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import math
|
| 4 |
+
from user_script import (
|
| 5 |
+
read_uploaded_fasta_or_zip,
|
| 6 |
+
derive_serotype_names_from_sources,
|
| 7 |
+
compute_unique_kmers_per_serotype,
|
| 8 |
+
classify_unknown_sequences,
|
| 9 |
+
parse_k_input,
|
| 10 |
+
plot_counts_by_serotype,
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
st.set_page_config(page_title="Serotype k-mer classifier", layout="wide")
|
| 14 |
+
st.title("🧬 Serotype k-mer classifier — STRICT uniques (Streamlit)")
|
| 15 |
+
|
| 16 |
+
st.markdown("""Upload **known serotype** sequences (FASTA or a ZIP with one FASTA per serotype) and **unknown** sequences,
|
| 17 |
+
choose parameters, then click **Run**. The app computes strictly unique k-mers per serotype across k and classifies unknowns.
|
| 18 |
+
""")
|
| 19 |
+
|
| 20 |
+
st.sidebar.header("Inputs")
|
| 21 |
+
known_file = st.sidebar.file_uploader("Known serotypes (FASTA or ZIP of FASTA files)", type=["fasta","fa","fas","fna","zip"])
|
| 22 |
+
unknown_file = st.sidebar.file_uploader("Unknown sequences (FASTA or ZIP of FASTA files)", type=["fasta","fa","fas","fna","zip"])
|
| 23 |
+
|
| 24 |
+
seqtype = st.sidebar.selectbox("Sequence type", ["DNA", "Protein"])
|
| 25 |
+
is_protein = (seqtype == "Protein")
|
| 26 |
+
default_k = 9 if is_protein else 21
|
| 27 |
+
k_input = st.sidebar.text_input("k values (e.g. 21 or 15-21 or 7,9,11)", value=str(default_k))
|
| 28 |
+
fdr_alpha = st.sidebar.number_input("FDR α", min_value=0.0, value=0.05, step=0.01)
|
| 29 |
+
|
| 30 |
+
run = st.sidebar.button("▶ Run analysis")
|
| 31 |
+
|
| 32 |
+
if run:
|
| 33 |
+
if not known_file or not unknown_file:
|
| 34 |
+
st.error("Please upload both known and unknown sequences.")
|
| 35 |
+
st.stop()
|
| 36 |
+
|
| 37 |
+
with st.spinner("Reading uploads..."):
|
| 38 |
+
known_records = read_uploaded_fasta_or_zip(known_file) # list of (src, header, seq)
|
| 39 |
+
unknown_records = read_uploaded_fasta_or_zip(unknown_file)
|
| 40 |
+
|
| 41 |
+
if not known_records:
|
| 42 |
+
st.error("No records found in the known upload."); st.stop()
|
| 43 |
+
if not unknown_records:
|
| 44 |
+
st.error("No records found in the unknown upload."); st.stop()
|
| 45 |
+
|
| 46 |
+
# Map headers to serotype names
|
| 47 |
+
name_map = derive_serotype_names_from_sources(known_records)
|
| 48 |
+
serotype_to_seq = {}
|
| 49 |
+
for src, header, seq in known_records:
|
| 50 |
+
sero = name_map.get(header, header.split()[0])
|
| 51 |
+
if sero not in serotype_to_seq:
|
| 52 |
+
serotype_to_seq[sero] = seq
|
| 53 |
+
|
| 54 |
+
k_values = parse_k_input(k_input, default_single=default_k)
|
| 55 |
+
k_values = sorted({k for k in k_values if k >= 3})
|
| 56 |
+
if not k_values:
|
| 57 |
+
st.error("No valid k values (>=3)."); st.stop()
|
| 58 |
+
|
| 59 |
+
st.info(f"Detected serotypes: {list(serotype_to_seq.keys())}")
|
| 60 |
+
st.info(f"k values: {k_values}")
|
| 61 |
+
|
| 62 |
+
with st.spinner("Computing strict-unique k-mers per serotype..."):
|
| 63 |
+
uniques = compute_unique_kmers_per_serotype(serotype_to_seq, is_protein=is_protein, k_values=k_values)
|
| 64 |
+
|
| 65 |
+
with st.spinner("Classifying unknown sequences..."):
|
| 66 |
+
df_full = classify_unknown_sequences(unknown_records, uniques, is_protein=is_protein, fdr_alpha=fdr_alpha)
|
| 67 |
+
|
| 68 |
+
def best_score(row):
|
| 69 |
+
g = row["Predicted_serotype"]
|
| 70 |
+
if g == "NoMatch":
|
| 71 |
+
return 0.0
|
| 72 |
+
q = row.get(f"FDR_{g}", 1.0)
|
| 73 |
+
return 0.0 if (q is None or q <= 0) else -math.log10(max(q, 1e-300))
|
| 74 |
+
|
| 75 |
+
df_full["Score_-log10FDR"] = df_full.apply(best_score, axis=1)
|
| 76 |
+
|
| 77 |
+
show_cols = ["Source","Sequence","Predicted_serotype","Matches_total","Confidence_by_present","Confidence_by_serotype_vocab","Score_-log10FDR"]
|
| 78 |
+
st.subheader("Predictions")
|
| 79 |
+
st.dataframe(df_full[show_cols].sort_values("Score_-log10FDR", ascending=False), use_container_width=True)
|
| 80 |
+
|
| 81 |
+
fig = plot_counts_by_serotype(df_full)
|
| 82 |
+
st.subheader("Predicted serotype counts")
|
| 83 |
+
st.pyplot(fig)
|
| 84 |
+
|
| 85 |
+
st.subheader("Downloads")
|
| 86 |
+
csv = df_full.to_csv(index=False).encode("utf-8")
|
| 87 |
+
st.download_button("Download predictions_by_serotype.csv", data=csv, file_name="predictions_by_serotype.csv", mime="text/csv")
|
| 88 |
+
else:
|
| 89 |
+
st.info("Upload the two files on the left, set parameters, then click **Run analysis**.")
|
requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
streamlit
|
| 2 |
+
pandas
|
| 3 |
+
numpy
|
| 4 |
+
matplotlib
|
| 5 |
+
biopython
|
| 6 |
+
statsmodels
|
| 7 |
+
scipy
|
runtime.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
streamlit
|
user_script.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
import io, os, re, math, zipfile
|
| 3 |
+
from typing import Dict, List, Tuple, Set, Optional
|
| 4 |
+
import pandas as pd
|
| 5 |
+
from Bio import SeqIO
|
| 6 |
+
from statsmodels.stats.multitest import multipletests
|
| 7 |
+
from scipy.stats import fisher_exact
|
| 8 |
+
import matplotlib.pyplot as plt
|
| 9 |
+
|
| 10 |
+
FA_EXT = (".fasta", ".fa", ".fas", ".fna")
|
| 11 |
+
|
| 12 |
+
def _read_fasta_bytes(name: str, data: bytes) -> List[Tuple[str, str, str]]:
|
| 13 |
+
recs = []
|
| 14 |
+
with io.BytesIO(data) as bio:
|
| 15 |
+
for rec in SeqIO.parse(io.TextIOWrapper(bio, encoding="utf-8"), "fasta"):
|
| 16 |
+
header = str(rec.id)
|
| 17 |
+
seq = str(rec.seq).upper().replace("\n", "").replace("\r", "")
|
| 18 |
+
recs.append((name, header, seq))
|
| 19 |
+
return recs
|
| 20 |
+
|
| 21 |
+
def read_uploaded_fasta_or_zip(uploaded_file) -> List[Tuple[str, str, str]]:
|
| 22 |
+
if uploaded_file is None:
|
| 23 |
+
return []
|
| 24 |
+
name = uploaded_file.name
|
| 25 |
+
data = uploaded_file.read()
|
| 26 |
+
if name.lower().endswith(".zip"):
|
| 27 |
+
results = []
|
| 28 |
+
with zipfile.ZipFile(io.BytesIO(data)) as z:
|
| 29 |
+
for zi in z.infolist():
|
| 30 |
+
if zi.is_dir(): continue
|
| 31 |
+
if not any(zi.filename.lower().endswith(ext) for ext in FA_EXT):
|
| 32 |
+
continue
|
| 33 |
+
file_bytes = z.read(zi.filename)
|
| 34 |
+
results.extend(_read_fasta_bytes(os.path.basename(zi.filename), file_bytes))
|
| 35 |
+
return results
|
| 36 |
+
else:
|
| 37 |
+
return _read_fasta_bytes(os.path.basename(name), data)
|
| 38 |
+
|
| 39 |
+
def clean_protein(seq: str) -> str:
|
| 40 |
+
return re.sub(r"[^ACDEFGHIKLMNPQRSTVWY]", "", seq.upper())
|
| 41 |
+
|
| 42 |
+
def clean_dna(seq: str) -> str:
|
| 43 |
+
return re.sub(r"[^ACGTUN]", "", seq.upper())
|
| 44 |
+
|
| 45 |
+
def get_kmers_noN(sequence: str, k: int) -> List[str]:
|
| 46 |
+
s = sequence
|
| 47 |
+
out = []
|
| 48 |
+
L = len(s)
|
| 49 |
+
for i in range(L - k + 1):
|
| 50 |
+
kmer = s[i:i+k]
|
| 51 |
+
if "N" not in kmer:
|
| 52 |
+
out.append(kmer)
|
| 53 |
+
return out
|
| 54 |
+
|
| 55 |
+
def parse_k_input(k_input: str, default_single: int) -> List[int]:
|
| 56 |
+
k_input = (k_input or "").strip()
|
| 57 |
+
if not k_input:
|
| 58 |
+
return [default_single]
|
| 59 |
+
if "-" in k_input:
|
| 60 |
+
a, b = k_input.split("-", 1)
|
| 61 |
+
a = int(a.strip()); b = int(b.strip())
|
| 62 |
+
if a > b: a, b = b, a
|
| 63 |
+
return list(range(a, b+1))
|
| 64 |
+
if "," in k_input:
|
| 65 |
+
return [int(x.strip()) for x in k_input.split(",") if x.strip()]
|
| 66 |
+
return [int(k_input)]
|
| 67 |
+
|
| 68 |
+
def derive_serotype_names_from_sources(known_records: List[Tuple[str, str, str]]) -> Dict[str, str]:
|
| 69 |
+
counts: Dict[str, int] = {}
|
| 70 |
+
for src, header, _ in known_records:
|
| 71 |
+
counts[src] = counts.get(src, 0) + 1
|
| 72 |
+
name_map: Dict[str, str] = {}
|
| 73 |
+
for src, header, _ in known_records:
|
| 74 |
+
if counts.get(src, 0) == 1:
|
| 75 |
+
sero = os.path.splitext(os.path.basename(src))[0]
|
| 76 |
+
else:
|
| 77 |
+
sero = header.split()[0]
|
| 78 |
+
name_map[header] = sero
|
| 79 |
+
return name_map
|
| 80 |
+
|
| 81 |
+
def compute_unique_kmers_per_serotype(serotype_to_seq: Dict[str, str], is_protein: bool, k_values: List[int]) -> Dict[str, Dict[int, Set[str]]]:
|
| 82 |
+
all_sets: Dict[str, Dict[int, Set[str]]] = {g: {} for g in serotype_to_seq}
|
| 83 |
+
for g, seq in serotype_to_seq.items():
|
| 84 |
+
seq = clean_protein(seq) if is_protein else clean_dna(seq)
|
| 85 |
+
for k in k_values:
|
| 86 |
+
all_sets[g][k] = set(get_kmers_noN(seq, k))
|
| 87 |
+
unique: Dict[str, Dict[int, Set[str]]] = {g: {k: set() for k in k_values} for g in serotype_to_seq}
|
| 88 |
+
for k in k_values:
|
| 89 |
+
union_all = set().union(*(all_sets[g][k] for g in all_sets))
|
| 90 |
+
for g in all_sets:
|
| 91 |
+
others_union = union_all - all_sets[g][k]
|
| 92 |
+
unique[g][k] = all_sets[g][k] - others_union
|
| 93 |
+
return unique
|
| 94 |
+
|
| 95 |
+
def classify_unknown_sequences(unknown_records: List[Tuple[str, str, str]], unique_kmers: Dict[str, Dict[int, Set[str]]], is_protein: bool, fdr_alpha: float = 0.05) -> pd.DataFrame:
|
| 96 |
+
vocab_by_sero: Dict[str, int] = {}
|
| 97 |
+
k_values = sorted({k for g in unique_kmers for k in unique_kmers[g]})
|
| 98 |
+
for g in unique_kmers:
|
| 99 |
+
vocab_by_sero[g] = sum(len(unique_kmers[g][k]) for k in k_values)
|
| 100 |
+
|
| 101 |
+
results = []
|
| 102 |
+
for src, header, seq in unknown_records:
|
| 103 |
+
seq2 = clean_protein(seq) if is_protein else clean_dna(seq)
|
| 104 |
+
unk_kmers: Dict[int, Set[str]] = {}
|
| 105 |
+
for k in k_values:
|
| 106 |
+
unk_kmers[k] = set(get_kmers_noN(seq2, k))
|
| 107 |
+
|
| 108 |
+
match_counts: Dict[str, int] = {}
|
| 109 |
+
total_matches = 0
|
| 110 |
+
for g in unique_kmers:
|
| 111 |
+
mg = 0
|
| 112 |
+
for k in k_values:
|
| 113 |
+
mg += len(unique_kmers[g][k].intersection(unk_kmers[k]))
|
| 114 |
+
match_counts[g] = mg
|
| 115 |
+
total_matches += mg
|
| 116 |
+
|
| 117 |
+
if total_matches == 0:
|
| 118 |
+
predicted = "NoMatch"; conf_present = 0.0; conf_vocab = 0.0
|
| 119 |
+
else:
|
| 120 |
+
predicted = max(match_counts, key=match_counts.get)
|
| 121 |
+
conf_present = match_counts[predicted] / total_matches
|
| 122 |
+
conf_vocab = match_counts[predicted] / max(1, vocab_by_sero[predicted])
|
| 123 |
+
|
| 124 |
+
fisher_p = {}
|
| 125 |
+
if total_matches > 0:
|
| 126 |
+
sum_vocab_all = sum(vocab_by_sero.values())
|
| 127 |
+
for g in unique_kmers:
|
| 128 |
+
a = match_counts[g]
|
| 129 |
+
b = vocab_by_sero[g] - a
|
| 130 |
+
c = total_matches - a
|
| 131 |
+
d = (sum_vocab_all - vocab_by_sero[g]) - c
|
| 132 |
+
a = max(0, a); b = max(0, b); c = max(0, c); d = max(0, d)
|
| 133 |
+
_, p = fisher_exact([[a, b], [c, d]], alternative="greater")
|
| 134 |
+
fisher_p[g] = p
|
| 135 |
+
groups = list(unique_kmers.keys())
|
| 136 |
+
pvals = [fisher_p[g] for g in groups]
|
| 137 |
+
_, qvals, _, _ = multipletests(pvals, alpha=fdr_alpha, method="fdr_bh")
|
| 138 |
+
fdr_map = {g: q for g, q in zip(groups, qvals)}
|
| 139 |
+
else:
|
| 140 |
+
fisher_p = {g: 1.0 for g in unique_kmers}
|
| 141 |
+
fdr_map = {g: 1.0 for g in unique_kmers}
|
| 142 |
+
|
| 143 |
+
row = {"Source": src, "Sequence": header, "Predicted_serotype": predicted, "Matches_total": total_matches, "Confidence_by_present": conf_present, "Confidence_by_serotype_vocab": conf_vocab}
|
| 144 |
+
for g in unique_kmers:
|
| 145 |
+
row[f"Matches_{g}"] = match_counts[g]
|
| 146 |
+
row[f"FisherP_{g}"] = fisher_p[g]
|
| 147 |
+
row[f"FDR_{g}"] = fdr_map[g]
|
| 148 |
+
results.append(row)
|
| 149 |
+
|
| 150 |
+
return pd.DataFrame(results)
|
| 151 |
+
|
| 152 |
+
def plot_counts_by_serotype(simple_df: pd.DataFrame):
|
| 153 |
+
fig = plt.figure(figsize=(8,5))
|
| 154 |
+
ax = fig.add_subplot(111)
|
| 155 |
+
counts = simple_df["Predicted_serotype"].value_counts()
|
| 156 |
+
ax.bar(counts.index.astype(str), counts.values)
|
| 157 |
+
ax.set_xlabel("Predicted serotype")
|
| 158 |
+
ax.set_ylabel("Number of sequences")
|
| 159 |
+
ax.set_title("Predicted serotype counts")
|
| 160 |
+
fig.tight_layout()
|
| 161 |
+
return fig
|