kozo2's picture
Upload scripts/umap_app.py with huggingface_hub
864b758 verified
Raw History Blame Contribute Delete
9.53 kB
"""Interactive explorer for the species-coloured UMAP of the Node2Vec embeddings.
uv run streamlit run umap_app.py
Reads the cached UMAP coordinates, the node properties from DuckDB and the
trained embeddings, all through paths.py — the same files the static figure uses.
The loaders and `build_figure` are importable without starting Streamlit, so the
chart can be rendered and inspected outside the app (see verify_app.py).
"""
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import streamlit as st
from paths import DB_PATH, EMB_PATH, UMAP_NPY_PATH
# Categorical slots 1-3 of the dataviz reference palette, validated all-pairs in
# both modes. A scatter shows every pair of colours at once, so three is the cap;
# further categories fold into a muted "Other" or are highlighted one at a time.
THEMES = {
"light": dict(series=["#2a78d6", "#eb6834", "#1baf7a"], other="#c3c2b7",
surface="#fcfcfb", ink="#0b0b0b", muted="#52514e", grid="#e1e0d9"),
"dark": dict(series=["#3987e5", "#d95926", "#199e70"], other="#55554f",
surface="#1a1a19", ink="#ffffff", muted="#c3c2b7", grid="#2c2c2a"),
}
GROUPINGS = ["species", "Study", "color_group", "tissue1", "Analytics"]
TOP3 = "— top 3 —"
HOVER_COLS = ["idx", "node_id", "species", "Study", "tissue1"]
HOVER = ("<b>%{customdata[1]}</b><br>"
"species: %{customdata[2]}<br>study: %{customdata[3]}<br>"
"tissue: %{customdata[4]}<extra></extra>")
@st.cache_data(show_spinner="Loading nodes…")
def load_nodes() -> pd.DataFrame:
import duckdb
con = duckdb.connect(DB_PATH, read_only=True)
df = con.execute("""
SELECT g.idx, g.id AS node_id, n.species, n.Study, n.Analytics,
n.color_group, n.factor,
split_part(trim(n.factor1, '()'), '|', 2) AS tissue1,
split_part(trim(n.factor2, '()'), '|', 2) AS tissue2
FROM graph_nodes g JOIN nodes_ML n ON n.id = g.id
ORDER BY g.idx
""").df()
xy = np.load(UMAP_NPY_PATH)
if len(xy) != len(df):
raise ValueError(f"{len(xy)} coordinates for {len(df)} nodes")
df["x"], df["y"] = xy[:, 0], xy[:, 1]
return df
@st.cache_data(show_spinner="Loading degrees…")
def load_degrees() -> pd.Series:
import duckdb
con = duckdb.connect(DB_PATH, read_only=True)
return con.execute("""
SELECT id, count(*) AS degree FROM (
SELECT start_id AS id FROM edge_ML_expected_ge5
UNION ALL SELECT end_id FROM edge_ML_expected_ge5)
GROUP BY id
""").df().set_index("id")["degree"]
@st.cache_resource(show_spinner="Loading embeddings…")
def load_embeddings() -> np.ndarray:
import torch
z = torch.load(EMB_PATH, weights_only=False)["embedding"]
z = torch.nn.functional.normalize(z, dim=1) # cosine via dot product
return z.numpy()
@st.cache_data(show_spinner=False)
def graph_neighbours(node_id: str) -> set:
import duckdb
con = duckdb.connect(DB_PATH, read_only=True)
rows = con.execute("""
SELECT end_id AS nb FROM edge_ML_expected_ge5 WHERE start_id = ?
UNION
SELECT start_id FROM edge_ML_expected_ge5 WHERE end_id = ?
""", [node_id, node_id]).fetchall()
return {r[0] for r in rows}
def build_figure(df, group_by="species", highlight=TOP3, shown=(), size=3.0,
opacity=0.7, show_backdrop=True, mode="light"):
"""The scatter, plus the subset of rows it draws in colour."""
theme = THEMES[mode]
# Rank within the restriction, so restricting to two categories colours both
# rather than leaving one grey because it is not in the global top three.
ranked = df[df[group_by].isin(list(shown))] if len(shown) else df
counts = ranked[group_by].value_counts()
if highlight != TOP3:
groups = np.where(df[group_by] == highlight, highlight, "Other")
order = [highlight]
palette = {highlight: theme["series"][0]}
else:
top3 = list(counts.index[:3])
groups = np.where(df[group_by].isin(top3), df[group_by], "Other")
order = top3
palette = dict(zip(top3, theme["series"]))
palette["Other"] = theme["other"]
df = df.assign(_group=groups)
in_view = df[group_by].isin(list(shown)) if len(shown) else pd.Series(
True, index=df.index)
visible = df[in_view]
fig = go.Figure()
if show_backdrop and len(shown):
out = df[~in_view]
fig.add_scattergl(
x=out["x"], y=out["y"], mode="markers", name="not shown",
marker=dict(size=size * 0.7, color=theme["grid"]), opacity=0.5,
customdata=out[HOVER_COLS].to_numpy(), hovertemplate=HOVER,
showlegend=False)
n_other = int((visible["_group"] == "Other").sum())
for name in ["Other"] + order: # Other first so it sits underneath
part = visible[visible["_group"] == name]
if part.empty:
continue
label = f"Other ({n_other:,})" if name == "Other" else f"{name} ({len(part):,})"
fig.add_scattergl(
x=part["x"], y=part["y"], mode="markers", name=label,
marker=dict(size=size, color=palette[name]), opacity=opacity,
customdata=part[HOVER_COLS].to_numpy(), hovertemplate=HOVER)
fig.update_layout(
height=680, margin=dict(l=8, r=8, t=8, b=8),
paper_bgcolor=theme["surface"], plot_bgcolor=theme["surface"],
font=dict(color=theme["muted"], size=12),
legend=dict(bgcolor=theme["surface"], bordercolor=theme["grid"],
borderwidth=1, itemsizing="constant", y=0.01, x=0.99,
xanchor="right"),
dragmode="pan", hovermode="closest",
)
# UMAP axes carry no units; distances between clusters are not meaningful
fig.update_xaxes(visible=False, scaleanchor="y", scaleratio=1)
fig.update_yaxes(visible=False)
return fig, visible
def selection_panel(picked, df, group_by):
if not picked:
st.subheader("No selection")
st.write("Click a point, or box-select a region, to inspect nodes here.")
return
if len(picked) == 1:
idx, node_id, species, study, tissue = picked[0]
st.subheader(node_id)
degree = int(load_degrees().get(node_id, 0))
st.write(f"*{species}* · study `{study}` · tissue {tissue} · "
f"degree {degree:,}")
z = load_embeddings()
sims = z @ z[int(idx)]
sims[int(idx)] = -2.0
nb = np.argsort(-sims)[:10]
gnb = graph_neighbours(node_id)
near = df.iloc[nb][["node_id", "species", "Study", "tissue1"]].copy()
near["cosine"] = sims[nb].round(3)
near["graph edge"] = [n in gnb for n in near["node_id"]]
near["same species"] = near["species"] == species
st.write("**10 nearest embeddings**")
st.dataframe(near.set_index("node_id"), width="stretch")
st.caption(f"{int(near['same species'].sum())}/10 share the species · "
f"{int(near['graph edge'].sum())}/10 are true graph neighbours")
return
st.subheader(f"{len(picked):,} nodes selected")
sel = pd.DataFrame(picked, columns=HOVER_COLS)
field = group_by if group_by in sel.columns else "species"
st.dataframe(sel[field].value_counts().rename("nodes").to_frame(),
width="stretch", height=300)
def main():
st.set_page_config(page_title="UMAP explorer", layout="wide")
df = load_nodes()
mode = st.get_option("theme.base") or "light"
with st.sidebar:
st.subheader("View")
group_by = st.selectbox("Colour by", GROUPINGS, index=0)
categories = list(df[group_by].value_counts().index)
highlight = st.selectbox(
f"Highlight one {group_by}", [TOP3] + categories,
help="Any single category can be highlighted; only three hues stay "
"colourblind-safe when every pair is on screen at once.")
shown = st.multiselect(
f"Restrict to {group_by}", categories, default=[],
help="Leave empty for all. Excluded nodes stay as a faint backdrop.")
st.divider()
st.subheader("Marks")
size = st.slider("Point size", 1.0, 8.0, 3.0, 0.5)
opacity = st.slider("Opacity", 0.1, 1.0, 0.7, 0.05)
backdrop = st.checkbox("Keep excluded nodes as backdrop", value=True)
fig, visible = build_figure(df, group_by, highlight, shown, size, opacity,
backdrop, mode)
st.title("Node2Vec embeddings by species")
st.caption(
f"UMAP of 128-d embeddings for {len(df):,} MetaboLights comparison nodes · "
"cosine metric · axes are arbitrary · drag to pan, scroll to zoom, "
"click or box-select points to inspect them")
event = st.plotly_chart(fig, width="stretch", on_select="rerun",
selection_mode=("points", "box", "lasso"), key="umap")
left, right = st.columns([2, 3], gap="large")
with left:
st.subheader(f"{group_by} in view")
table = (visible[group_by].value_counts().rename("nodes").to_frame()
.assign(share=lambda t: (t["nodes"] / len(visible))
.map("{:.1%}".format)))
st.dataframe(table, width="stretch", height=260)
with right:
points = event.selection.get("points", []) if event and event.selection else []
selection_panel([p["customdata"] for p in points], df, group_by)
if __name__ == "__main__":
main()