Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
st.Page(Path("content", "results_pca.py"), title="PCA", icon="📊"),
st.Page(Path("content", "results_heatmap.py"), title="Heatmap", icon="🔥"),
st.Page(Path("content", "results_library.py"), title="Spectral Library", icon="📚"),
st.Page(Path("content", "results_proteomicslfq.py"), title="GO Terms", icon="🧪"),
],
}

Expand Down
141 changes: 141 additions & 0 deletions content/results_proteomicslfq.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
from pathlib import Path
import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
import mygene
from collections import defaultdict
from scipy.stats import ttest_ind, fisher_exact

from src.common.common import page_setup
from src.common.results_helpers import get_abundance_data, get_workflow_dir

params = page_setup()
st.title("ProteomicsLFQ Results")

if "workspace" not in st.session_state:
st.warning("Please initialize your workspace first.")
st.stop()

res = get_abundance_data(st.session_state["workspace"])
if res is None:
st.info("Abundance data not available or incomplete. Please run the workflow and configure sample groups first.")
st.stop()

pivot_df, expr_df, group_map = res

protein_tab, = st.tabs(["🧬 Protein Table"])

# Protein-level tab
with protein_tab:
st.markdown("### 🧬 Protein-Level Abundance Table")
st.info(
"This protein-level table is generated by grouping all PSMs that map to the "
"same protein and aggregating their intensities across samples.\n\n"
"Additionally, log2 fold change and p-values are calculated between sample groups."
)

if pivot_df.empty:
st.info("No protein-level data available.")
else:
st.session_state["pivot_df"] = pivot_df
st.dataframe(pivot_df.sort_values("p-value"), use_container_width=True)

st.markdown("---")
st.subheader("🧬 GO Enrichment Analysis")

p_cutoff = st.slider("Select p-value threshold for Foreground Proteins", 0.01, 0.50, 0.05)
fc_cutoff = st.slider("Select |log2FC| threshold for Foreground Proteins", 0.0, 5.0, 1.0, step=0.1)

if st.button("Run GO Enrichment"):
analysis_df = pivot_df.dropna(subset=["p-value", "log2FC"]).copy()
if analysis_df.empty:
st.error("No valid statistical data found.")
else:
with st.spinner("Fetching GO terms from MyGene.info API..."):
try:
mg = mygene.MyGeneInfo()

def get_clean_uniprot(name):
try:
parts = str(name).split("|")
return parts[1] if len(parts) >= 2 else parts[0]
except Exception:
return None

analysis_df["UniProt"] = analysis_df["ProteinName"].apply(get_clean_uniprot)

bg_ids = analysis_df["UniProt"].dropna().unique().tolist()
fg_ids = analysis_df[
(analysis_df["p-value"] < p_cutoff) &
(analysis_df["log2FC"].abs() >= fc_cutoff)
]["UniProt"].dropna().unique().tolist()

if len(fg_ids) < 3:
st.warning(f"Not enough significant proteins (p < {p_cutoff}, |log2FC| ≥ {fc_cutoff}). Found: {len(fg_ids)}")
else:
res_list = mg.querymany(bg_ids, scopes="uniprot", fields="go", as_dataframe=False)
res = pd.DataFrame(res_list)
if "notfound" in res.columns:
res = res[res["notfound"] != True]

def extract_go_terms(go_data, go_type):
if not isinstance(go_data, dict) or go_type not in go_data:
return []
terms = go_data[go_type]
if isinstance(terms, dict):
terms = [terms]
return list({t.get("term") for t in terms if "term" in t})

for go_type in ["BP", "CC", "MF"]:
res[f"{go_type}_terms"] = res["go"].apply(lambda x: extract_go_terms(x, go_type))

fg_set = set(fg_ids)
bg_set = set(bg_ids)

def run_go_enrichment(go_type):
go2fg = defaultdict(set)
go2bg = defaultdict(set)
for _, row in res.iterrows():
uid = str(row["query"])
for term in row[f"{go_type}_terms"]:
go2bg[term].add(uid)
if uid in fg_set:
go2fg[term].add(uid)

records = []
N_fg = len(fg_set)
N_bg = len(bg_set)
for term, fg_genes in go2fg.items():
a = len(fg_genes)
if a == 0:
continue
b = N_fg - a
c = len(go2bg[term]) - a
d = N_bg - (a + b + c)
_, p = fisher_exact([[a, b], [c, d]], alternative="greater")
records.append({"GO_Term": term, "Count": a, "GeneRatio": f"{a}/{N_fg}", "p_value": p})
Comment on lines +68 to +117
Copy link

@coderabbitai coderabbitai bot Feb 4, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Foreground/background counts include unannotated proteins, biasing Fisher p-values.

N_bg/N_fg are computed from all proteins, even those without GO annotations. This inflates the background and can understate enrichment. Restrict both sets to annotated proteins returned by MyGene before computing Fisher’s exact test.

Proposed fix
-                    bg_ids = analysis_df["UniProt"].dropna().unique().tolist()
+                    bg_ids = analysis_df["UniProt"].dropna().unique().tolist()
                     fg_ids = analysis_df[
                         (analysis_df["p-value"] < p_cutoff) &
                         (analysis_df["log2FC"].abs() >= fc_cutoff)
                     ]["UniProt"].dropna().unique().tolist()
 ...
-                        fg_set = set(fg_ids)
-                        bg_set = set(bg_ids)
+                        annotated_ids = set(res["query"].astype(str))
+                        bg_set = annotated_ids
+                        fg_set = annotated_ids.intersection(map(str, fg_ids))
🧰 Tools
🪛 Ruff (0.14.14)

[error] 80-80: Avoid inequality comparisons to True; use not res["notfound"]: for false checks

Replace with not res["notfound"]

(E712)


[warning] 91-91: Function definition does not bind loop variable go_type

(B023)

🤖 Prompt for AI Agents
In `@content/results_proteomicslfq.py` around lines 68 - 117, The
foreground/background counts are using all proteins (bg_ids/fg_ids) even if
MyGene returned no annotation, so update run_go_enrichment to first compute
annotated_ids = set(res["query"].astype(str)) (or otherwise derive the set of
IDs present in the filtered res) and then replace bg_set and fg_set with their
intersections with annotated_ids before computing N_bg/N_fg and running the
Fisher tests; keep building go2bg/go2fg from res rows as-is so counts and
p-values reflect only annotated proteins.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@hjn0415a Could you check this?

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!


df_go = pd.DataFrame(records)
if not df_go.empty:
df_go["-log10(p)"] = -np.log10(df_go["p_value"].replace(0, 1e-10))
df_go = df_go.sort_values("p_value")
return df_go

enrich_results = {go: run_go_enrichment(go) for go in ["BP", "CC", "MF"]}

bp_tab, cc_tab, mf_tab = st.tabs(["🧬 Biological Process", "🏠 Cellular Component", "⚙️ Molecular Function"])
for tab, go_type in zip([bp_tab, cc_tab, mf_tab], ["BP", "CC", "MF"]):
with tab:
df_go = enrich_results[go_type]
if df_go.empty:
st.warning(f"No enriched {go_type} terms found.")
continue
fig = px.bar(df_go.head(15), x="-log10(p)", y="GO_Term", orientation="h", text="GeneRatio", color="-log10(p)", color_continuous_scale="Viridis")
fig.update_layout(yaxis={"categoryorder": "total ascending"}, margin=dict(l=300))
st.plotly_chart(fig, use_container_width=True)
st.dataframe(df_go, use_container_width=True)

st.success("GO Enrichment analysis completed successfully.")
except Exception as e:
st.error(f"GO enrichment failed: {e}")
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -149,3 +149,4 @@ pyprophet>=2.2.0
# Redis Queue dependencies (for online mode)
redis>=5.0.0
rq>=1.16.0
mygene