"""scPTR — Single-Cell Post-Transcriptional Regulatory Decomposition."""
from __future__ import annotations
import io
import os
import tempfile
import traceback
import warnings
import matplotlib
matplotlib.use("Agg")
import json
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scanpy as sc
import streamlit as st
warnings.filterwarnings("ignore")
import scptr # noqa: E402 — imported after matplotlib backend set
st.set_page_config(
page_title="scPTR",
page_icon=None,
layout="wide",
initial_sidebar_state="expanded",
)
# ── CSS ───────────────────────────────────────────────────────────────────────
st.markdown("""
""", unsafe_allow_html=True)
# ── session state ─────────────────────────────────────────────────────────────
for k, v in {
"page": "home",
"step": 1,
"adata": None,
"dataset_name": None,
"preprocessed": False,
"estimated": False,
"states_done": False,
"velocity_done": False,
"network_done": False,
"_tmps": [],
}.items():
if k not in st.session_state:
st.session_state[k] = v
# ── helpers ───────────────────────────────────────────────────────────────────
def go(step: int) -> None:
st.session_state.step = step
def nav(page: str) -> None:
st.session_state.page = page
def fig_png(fig: plt.Figure, dpi: int = 150) -> bytes:
buf = io.BytesIO()
fig.savefig(buf, format="png", dpi=dpi, bbox_inches="tight", facecolor="white")
buf.seek(0)
return buf.read()
def make_tmp(suffix: str = ".h5ad") -> str:
fd, path = tempfile.mkstemp(suffix=suffix)
os.close(fd)
st.session_state._tmps.append(path)
return path
def clean_tmps() -> None:
for p in st.session_state._tmps:
try:
os.unlink(p)
except Exception:
pass
st.session_state._tmps = []
def mg(*metrics) -> str:
"""metric_grid(*[(label, value, sub, cls?), ...])"""
cells = []
for m in metrics:
lbl, val, sub = m[0], m[1], m[2]
cls = m[3] if len(m) > 3 else ""
cells.append(
f'
'
f'
{lbl}
'
f'
{val}
'
f'
{sub}
'
f'
'
)
return f'{"".join(cells)}
'
def reset_downstream(from_step: int) -> None:
if from_step <= 1:
st.session_state.preprocessed = False
st.session_state.estimated = False
st.session_state.states_done = False
st.session_state.velocity_done = False
st.session_state.network_done = False
elif from_step <= 2:
st.session_state.estimated = False
st.session_state.states_done = False
st.session_state.velocity_done = False
st.session_state.network_done = False
elif from_step <= 3:
st.session_state.states_done = False
st.session_state.velocity_done = False
st.session_state.network_done = False
# ── sidebar ───────────────────────────────────────────────────────────────────
STEPS = ["Load Data", "Preprocess", "Estimate Rates", "Discover PT States", "Results"]
with st.sidebar:
st.markdown(
''
'
scPTR
'
'
Single-Cell Post-Transcriptional
Regulatory Decomposition
'
'
',
unsafe_allow_html=True,
)
_page_map = {"Home": "home", "Analysis": "analysis", "Docs": "docs"}
_page_rev = {v: k for k, v in _page_map.items()}
_nav_choice = st.radio(
"nav",
list(_page_map.keys()),
index=list(_page_map.keys()).index(_page_rev.get(st.session_state.page, "Home")),
horizontal=True,
label_visibility="collapsed",
key="sidebar_nav",
)
if _page_map[_nav_choice] != st.session_state.page:
st.session_state.page = _page_map[_nav_choice]
st.rerun()
# Show data summary on home/docs pages too
if st.session_state.page != "analysis" and st.session_state.adata is not None:
_a = st.session_state.adata
_done_count = sum([
st.session_state.preprocessed,
st.session_state.estimated,
st.session_state.states_done,
])
st.markdown(
f''
f'{st.session_state.dataset_name}
'
f'{_a.n_obs:,} cells · {_a.n_vars:,} genes
'
f'{_done_count}/3 steps complete'
f'
',
unsafe_allow_html=True,
)
if st.button("Resume Analysis →", use_container_width=True):
nav("analysis"); st.rerun()
if st.session_state.page == "analysis":
st.markdown('
', unsafe_allow_html=True)
st.markdown('', unsafe_allow_html=True)
step = st.session_state.step
done = {
1: st.session_state.adata is not None,
2: st.session_state.preprocessed,
3: st.session_state.estimated,
4: st.session_state.states_done,
}
for i, label in enumerate(STEPS, 1):
if i == step:
cls = "active"
elif done.get(i, False):
cls = "done"
else:
cls = ""
num = "✓" if (done.get(i, False) and i != step) else str(i)
# Clickable for completed steps and step 5 (always accessible after states)
can_jump = done.get(i, False) and i != step
if can_jump:
# Show step as a compact link button
col_btn, = st.columns([1])
if st.button(f"↩ {label}", key=f"jump_{i}", use_container_width=True):
go(i); st.rerun()
else:
st.markdown(
f'
',
unsafe_allow_html=True,
)
st.markdown('
', unsafe_allow_html=True)
if st.session_state.adata is not None:
adata = st.session_state.adata
lines = [
f"{st.session_state.dataset_name}",
f"{adata.n_obs:,} cells · {adata.n_vars:,} genes",
]
if st.session_state.preprocessed:
lines.append('✓ preprocessed')
if st.session_state.estimated:
lines.append('✓ rates estimated')
if st.session_state.states_done:
n_s = adata.obs["pt_state"].nunique() if "pt_state" in adata.obs else "?"
lines.append(f'✓ {n_s} PT states')
if st.session_state.network_done:
lines.append('✓ network inferred')
st.markdown(
f'{"
".join(lines)}
',
unsafe_allow_html=True,
)
# ── page routing ──────────────────────────────────────────────────────────────
page = st.session_state.page
# ══════════════════════════════════════════════════════════════════════════════
# HOME PAGE
# ══════════════════════════════════════════════════════════════════════════════
if page == "home":
st.markdown(
''
'
Single-cell post-transcriptional
regulatory decomposition
'
'
'
'scPTR estimates per-cell, per-gene mRNA degradation rates from standard scRNA-seq '
'spliced/unspliced counts. It uses the degradation rate γ as a primary analytical '
'axis — complementary to RNA velocity — to discover expression-invisible cell states, '
'compute post-transcriptional velocity, and infer RNA-binding protein networks.'
'
'
'
γig = βg · uig / sig
'
'
',
unsafe_allow_html=True,
)
home_c1, home_c2 = st.columns([1, 2])
with home_c1:
if st.button("Start Analysis →"):
nav("analysis"); st.rerun()
with home_c2:
if st.session_state.adata is not None:
_prog_items = [
("Load Data", True),
("Preprocess", st.session_state.preprocessed),
("Estimate Rates", st.session_state.estimated),
("PT States", st.session_state.states_done),
("Results", st.session_state.states_done),
]
_pct = sum(1 for _, v in _prog_items if v) / len(_prog_items) * 100
bars = "".join(
f''
for _, v in _prog_items
)
st.markdown(
f''
f'Analysis progress · {_pct:.0f}%
'
f'{bars}
'
f''
f'{st.session_state.dataset_name} — '
f'{st.session_state.adata.n_obs:,} cells · {st.session_state.adata.n_vars:,} genes
',
unsafe_allow_html=True,
)
if st.button("Resume →"):
nav("analysis"); st.rerun()
# Pipeline — dynamic done/active state
_s = st.session_state
_pipe_states = [
_s.adata is not None,
_s.preprocessed,
_s.estimated,
_s.states_done,
_s.states_done,
]
_next_step = next((i for i, v in enumerate(_pipe_states) if not v), len(_pipe_states))
def _pipe_cls(i):
if _pipe_states[i]: return "done"
if i == _next_step: return "active-step"
return ""
def _pipe_icon(i):
return "✓ " if _pipe_states[i] else ""
st.markdown('Analysis pipeline
', unsafe_allow_html=True)
st.markdown(
''
f'
{_pipe_icon(0)}01
Load Data
'
'
Upload .h5ad or use built-in pancreas / dentate gyrus datasets
'
f'
{_pipe_icon(1)}02
Preprocess
'
'
Filter genes, normalize counts, kNN graph, Gaussian smoothing
'
f'
{_pipe_icon(2)}03
Estimate Rates
'
'
β via quantile regression on u/s portraits; γ = β · u / s per cell
'
f'
{_pipe_icon(3)}04
PT States
'
'
Leiden clustering in γ-space; PT velocity; RBP–target networks
'
f'
{_pipe_icon(4)}05
Results
'
'
UMAP visualization, gene rankings, download outputs
'
'
',
unsafe_allow_html=True,
)
col1, col2 = st.columns(2, gap="large")
with col1:
st.markdown('Validation
', unsafe_allow_html=True)
_g = 'background:#eaf5ef'
st.markdown(
''
'| Validation | Result |
'
''
f'| sci-fate metabolic labeling | ρ = −0.81 |
'
f'| 10x developmental half-lives | ρ = −0.33 to −0.40 |
'
f'| vs. scVelo steady-state | −0.37 (scPTR: −0.40) |
'
f'| vs. velVI | −0.28 (scPTR: −0.40) |
'
f'| miRNA target enrichment | 59% of 215 families, p = 4.7×10⁻⁶⁵ |
'
f'| DepMap CRISPR essentiality | hub RBPs, p = 6.4×10⁻⁵ |
'
f'| Subsampling robustness | r > 0.97 at 20% |
'
'
',
unsafe_allow_html=True,
)
with col2:
st.markdown('Key findings
', unsafe_allow_html=True)
st.markdown(
''
'
Expression-invisible states
'
'
'
'3/8 pancreatic and 6/11 hippocampal cell types harbor post-transcriptional '
'subpopulations undetectable by expression analysis. Confirmed by zero-permutation '
'control (ARI ≈ 0).'
'
'
''
'
Temporal precedence
'
'
'
'Degradation-rate changes precede expression changes for 54% of pancreas '
'transition genes (p < 10⁻⁵⁷) and 78% in dentate gyrus (p = 9.9×10⁻¹³).'
'
'
''
'
RBP networks
'
'
'
'Library-size-corrected inference identifies essential hub regulators '
'(HNRNPA1, YBX1, ELAVL1/HuR). Neuroblastoma shows 66% stabilizing edges.'
'
',
unsafe_allow_html=True,
)
st.markdown('Input requirements
', unsafe_allow_html=True)
st.markdown(
''
'scPTR requires an AnnData file (.h5ad) with two count matrix layers: '
'spliced and unspliced. These can be generated with '
'STARsolo, Alevin-fry, kallisto|bustools, '
'or velocyto. Raw (un-normalized) counts are expected.'
'
',
unsafe_allow_html=True,
)
st.markdown(
''
'Session data lives in browser memory. Keep this tab open while running analysis. '
'Refreshing the page will reset all results. Download your AnnData file in step 5 to save progress.'
'
',
unsafe_allow_html=True,
)
# ══════════════════════════════════════════════════════════════════════════════
# ANALYSIS — STEP 1: LOAD DATA
# ══════════════════════════════════════════════════════════════════════════════
elif page == "analysis" and st.session_state.step == 1:
st.markdown('Load Data — step 1 of 5
', unsafe_allow_html=True)
st.markdown(
'Upload an AnnData file (.h5ad) containing spliced and '
'unspliced count layers, or start with a built-in example dataset.
',
unsafe_allow_html=True,
)
st.markdown('Quick start
', unsafe_allow_html=True)
qs_c1, qs_c2, qs_c3 = st.columns(3, gap="large")
with qs_c1:
st.markdown(
''
'
Pancreas
'
'
'
'Mouse endocrinogenesis · 3,696 cells
'
'Bastidas-Ponce et al. 2019'
'
'
'
',
unsafe_allow_html=True,
)
if st.button("Load Pancreas", key="qs_pancreas", use_container_width=True):
with st.spinner("Downloading pancreas dataset…"):
try:
_adata = scptr.datasets.pancreas()
st.session_state.adata = _adata
st.session_state.dataset_name = "Pancreas"
reset_downstream(1)
go(2); st.rerun()
except Exception as e:
st.markdown(f'Error: {e}
', unsafe_allow_html=True)
with qs_c2:
st.markdown(
''
'
Dentate Gyrus
'
'
'
'Mouse hippocampal neurogenesis · 2,930 cells
'
'Hochgerner et al. 2018'
'
'
'
',
unsafe_allow_html=True,
)
if st.button("Load Dentate Gyrus", key="qs_dg", use_container_width=True):
with st.spinner("Downloading dentate gyrus dataset…"):
try:
_adata = scptr.datasets.dentate_gyrus()
st.session_state.adata = _adata
st.session_state.dataset_name = "Dentate Gyrus"
reset_downstream(1)
go(2); st.rerun()
except Exception as e:
st.markdown(f'Error: {e}
', unsafe_allow_html=True)
with qs_c3:
st.markdown(
''
'
Upload
'
'
'
'Your own .h5ad file
'
'Requires spliced + unspliced layers'
'
'
'
',
unsafe_allow_html=True,
)
if st.button("Upload File →", key="qs_upload", use_container_width=True):
st.session_state["_show_upload"] = True
st.rerun()
st.markdown('
', unsafe_allow_html=True)
col1, col2 = st.columns(2, gap="large")
with col1:
st.markdown('Example datasets
', unsafe_allow_html=True)
example = st.selectbox(
"Dataset",
["— select —",
"Pancreas (mouse endocrinogenesis, 3,696 cells)",
"Dentate Gyrus (mouse hippocampal neurogenesis, 2,930 cells)"],
label_visibility="collapsed",
)
st.markdown(
''
'Both datasets include spliced/unspliced counts from scVelo. '
'Requires pooch — datasets are downloaded on first use (~30 MB each).'
'
',
unsafe_allow_html=True,
)
if st.button("Load Example Dataset", disabled=(example == "— select —")):
with st.spinner("Downloading and loading dataset…"):
try:
if "Pancreas" in example:
adata = scptr.datasets.pancreas()
name = "Pancreas"
else:
adata = scptr.datasets.dentate_gyrus()
name = "Dentate Gyrus"
st.session_state.adata = adata
st.session_state.dataset_name = name
reset_downstream(1)
go(2)
st.rerun()
except Exception as e:
st.markdown(
f'Error loading dataset: {e}
'
f'Ensure pip install "scptr[datasets]" is installed.
',
unsafe_allow_html=True,
)
with col2:
if st.session_state.pop("_show_upload", False):
st.markdown('Use the file uploader below to load your .h5ad file.
', unsafe_allow_html=True)
st.markdown('Upload your own
', unsafe_allow_html=True)
uploaded = st.file_uploader(
"H5AD file",
type=["h5ad"],
label_visibility="collapsed",
help="AnnData file with 'spliced' and 'unspliced' layers",
)
if uploaded is not None:
st.markdown(
f''
f'File: {uploaded.name} ({uploaded.size / 1e6:.1f} MB)
',
unsafe_allow_html=True,
)
if st.button("Load File"):
tmp = make_tmp(".h5ad")
try:
with open(tmp, "wb") as f:
f.write(uploaded.read())
with st.spinner("Reading file…"):
adata = sc.read_h5ad(tmp)
missing = [l for l in ["spliced", "unspliced"] if l not in adata.layers]
if missing:
st.markdown(
f'Missing layers: {", ".join(missing)}
'
f'The file must contain spliced and unspliced '
f'count matrix layers. Use velocyto, STARsolo, or Alevin-fry to generate them.
',
unsafe_allow_html=True,
)
else:
st.session_state.adata = adata
st.session_state.dataset_name = uploaded.name.removesuffix(".h5ad")
reset_downstream(1)
go(2)
st.rerun()
except Exception as e:
st.markdown(
f'Could not read file: {e}
',
unsafe_allow_html=True,
)
st.markdown('
', unsafe_allow_html=True)
st.markdown(
''
'
What scPTR needs
'
'
'
'| Slot | Content | Required |
'
''
'| adata.layers["spliced"] | Spliced (mature) mRNA counts per cell × gene | ✓ |
'
'| adata.layers["unspliced"] | Unspliced (nascent) mRNA counts per cell × gene | ✓ |
'
'| adata.obs columns | Cell metadata (cell type, cluster, etc.) for visualization | optional |
'
'| adata.obsm["X_umap"] | UMAP embedding (scPTR will compute one if absent) | optional |
'
'
'
'
',
unsafe_allow_html=True,
)
# ══════════════════════════════════════════════════════════════════════════════
# ANALYSIS — STEP 2: PREPROCESS
# ══════════════════════════════════════════════════════════════════════════════
elif page == "analysis" and st.session_state.step == 2:
adata = st.session_state.adata
st.markdown('Preprocess — step 2 of 5
', unsafe_allow_html=True)
st.markdown(
'Filter low-quality genes, normalize counts to library size, '
'build a cell neighborhood graph (kNN in PCA space), and apply Gaussian kernel '
'smoothing to the spliced and unspliced layers.
',
unsafe_allow_html=True,
)
# Data quality summary
_s_layer = adata.layers["spliced"]
_u_layer = adata.layers["unspliced"]
_s_sparsity = 1.0 - float(np.count_nonzero(_s_layer)) / _s_layer.size
_u_sparsity = 1.0 - float(np.count_nonzero(_u_layer)) / _u_layer.size
_has_obs = list(adata.obs.columns)[:5]
st.markdown(
mg(
("Cells", f"{adata.n_obs:,}", ""),
("Genes", f"{adata.n_vars:,}", "before filtering"),
("Spliced sparsity", f"{_s_sparsity:.1%}", "zeros in matrix"),
("Unspliced sparsity", f"{_u_sparsity:.1%}", "zeros in matrix"),
),
unsafe_allow_html=True,
)
_layer_ok = all(l in adata.layers for l in ["spliced", "unspliced"])
_extra_layers = [l for l in adata.layers if l not in ["spliced", "unspliced"]]
_layer_info = (
'✓ spliced '
'✓ unspliced'
)
if _extra_layers:
_layer_info += f' · also: {", ".join(_extra_layers[:4])}'
if _has_obs:
_layer_info += f'
obs columns: {", ".join(_has_obs)}'
st.markdown(
f''
f'Layers detected: {_layer_info}'
f'
',
unsafe_allow_html=True,
)
_rn = st.session_state.get("pp_reset_n", 0) # reset counter — changes keys to force re-init
col1, col2, col3 = st.columns(3, gap="large")
with col1:
st.markdown('Gene filtering
', unsafe_allow_html=True)
min_unspliced = st.number_input(
"Min total unspliced counts per gene",
value=10, min_value=1, step=1,
key=f"pp_mu_{_rn}",
help="Genes with fewer total unspliced counts across all cells are removed.",
)
min_cells = st.number_input(
"Min cells with nonzero unspliced",
value=5, min_value=1, step=1,
key=f"pp_mc_{_rn}",
help="Genes expressed in fewer cells are removed.",
)
with col2:
st.markdown('Cell filtering
', unsafe_allow_html=True)
min_cell_unspliced = st.number_input(
"Min unspliced counts per cell",
value=0, min_value=0, step=100,
key=f"pp_mcu_{_rn}",
help="Cells with fewer total unspliced counts are removed. 0 = no filter.",
)
min_cell_spliced = st.number_input(
"Min spliced counts per cell",
value=0, min_value=0, step=100,
key=f"pp_mcs_{_rn}",
help="Cells with fewer total spliced counts are removed. 0 = no filter.",
)
with col3:
st.markdown('Neighborhood graph
', unsafe_allow_html=True)
n_neighbors = st.number_input(
"Neighbors (kNN graph)",
value=30, min_value=5, max_value=100, step=5,
key=f"pp_nn_{_rn}",
help="Number of nearest neighbors for the cell graph. Larger = smoother.",
)
n_pcs = st.number_input(
"PCA components",
value=30, min_value=10, max_value=100, step=5,
key=f"pp_np_{_rn}",
help="PCA dimensions used for neighbor search.",
)
with st.expander("Advanced: Smoothing options"):
bw_mode = st.radio(
"Smoothing bandwidth",
["Adaptive (median distance)", "Fixed value"],
horizontal=True,
)
fixed_bw = None
if bw_mode == "Fixed value":
fixed_bw = st.number_input("Bandwidth", value=1.0, min_value=0.05, step=0.05)
st.markdown(
''
'Gaussian kernel smoothing reduces noise in spliced/unspliced counts by averaging '
'over cell neighbors. Adaptive bandwidth uses the median distance to the k-th neighbor.'
'
',
unsafe_allow_html=True,
)
if st.session_state.preprocessed:
st.markdown(
'Preprocessing already complete. '
'Click below to re-run with new parameters.
',
unsafe_allow_html=True,
)
run_col, reset_col = st.columns([2, 1])
if "pp_reset_n" not in st.session_state:
st.session_state.pp_reset_n = 0
with reset_col:
if st.button("↻ Reset to defaults", help="Restore all preprocessing parameters to defaults"):
st.session_state.pp_reset_n += 1
st.rerun()
with run_col:
_run_pp = st.button("Run Preprocessing", use_container_width=True)
if _run_pp:
adata_work = st.session_state.adata.copy()
try:
prog = st.progress(0, text="Filtering genes…")
scptr.pp.filter_genes(
adata_work,
min_unspliced_counts=min_unspliced,
min_unspliced_cells=min_cells,
)
if min_cell_unspliced > 0 or min_cell_spliced > 0:
prog.progress(15, text="Filtering cells…")
scptr.pp.filter_cells(
adata_work,
min_unspliced_counts=min_cell_unspliced,
min_spliced_counts=min_cell_spliced,
)
prog.progress(25, text="Normalizing layers…")
scptr.pp.normalize_layers(adata_work)
prog.progress(50, text="Building neighborhood graph…")
scptr.pp.neighbors(adata_work, n_neighbors=n_neighbors, n_pcs=n_pcs)
prog.progress(75, text="Smoothing spliced/unspliced…")
if fixed_bw is not None:
scptr.pp.smooth_layers(adata_work, bandwidth=fixed_bw)
else:
scptr.pp.smooth_layers(adata_work)
prog.progress(100, text="Done.")
st.session_state.adata = adata_work
st.session_state.preprocessed = True
reset_downstream(2)
_cells_removed = adata.n_obs - adata_work.n_obs
_genes_removed = adata.n_vars - adata_work.n_vars
st.markdown(
mg(
("Cells retained", f"{adata_work.n_obs:,}", f"−{_cells_removed:,} filtered" if _cells_removed else "all kept", "green"),
("Genes retained", f"{adata_work.n_vars:,}", f"−{_genes_removed:,} filtered"),
("Neighbors", str(n_neighbors), "kNN graph"),
("PCA dims", str(n_pcs), "for graph"),
),
unsafe_allow_html=True,
)
st.markdown(
''
'Preprocessing complete — genes filtered, layers normalized, kNN graph built, counts smoothed. '
'Next: estimate β (splicing rate) and γ (degradation rate). '
'Variance decomposition runs automatically with rate estimation.'
'
',
unsafe_allow_html=True,
)
except Exception as e:
st.markdown(
f'Preprocessing failed: {e}
'
f'Common causes: '
f'too few genes after filtering (lower thresholds in step 2) · '
f'missing spliced/unspliced layers · '
f'dataset too small for PCA (n_pcs may exceed n_cells or n_genes)'
f'
',
unsafe_allow_html=True,
)
with st.expander("Traceback"):
st.code(traceback.format_exc())
st.markdown('
', unsafe_allow_html=True)
c1, c2 = st.columns([1, 6])
with c1:
if st.button("← Back"):
go(1); st.rerun()
with c2:
if st.button("Next: Estimate Rates →", disabled=not st.session_state.preprocessed):
go(3); st.rerun()
# ══════════════════════════════════════════════════════════════════════════════
# ANALYSIS — STEP 3: ESTIMATE RATES
# ══════════════════════════════════════════════════════════════════════════════
elif page == "analysis" and st.session_state.step == 3:
adata = st.session_state.adata
st.markdown('Estimate Rates — step 3 of 5
', unsafe_allow_html=True)
st.markdown(
'Estimate gene-specific splicing rates (β) from unspliced/spliced phase '
'portraits using quantile regression. Then compute per-cell, per-gene degradation rates '
'γig = βg · uig / sig using the '
'kinetic steady-state model.
',
unsafe_allow_html=True,
)
col1, col2 = st.columns(2, gap="large")
with col1:
st.markdown('Beta estimation (β)
', unsafe_allow_html=True)
quantile = st.slider(
"Phase portrait quantile",
0.80, 0.99, 0.95, 0.01,
help="Upper quantile of the u/s ratio distribution used to estimate β. "
"Typical: 0.95 for 10x Chromium; 0.90–0.92 for Smart-seq (denser coverage). "
"Lower values = more conservative boundary.",
)
min_r2 = st.slider(
"Min R² for beta fit",
0.0, 0.90, 0.0, 0.05,
help="Genes with a phase portrait R² below this threshold are excluded.",
)
with col2:
st.markdown('Gamma estimation (γ)
', unsafe_allow_html=True)
min_spliced_thr = st.number_input(
"Min smoothed spliced (Ms) for γ",
value=0.01, min_value=0.001, step=0.005, format="%.3f",
help="Cells with Ms < threshold for a given gene receive γ = 0 (prevents division by near-zero).",
)
clip_q = st.slider(
"Gamma clip quantile",
0.90, 1.00, 0.99, 0.01,
help="Per-gene clipping at this quantile to remove extreme outliers before analysis.",
)
if st.session_state.estimated:
st.markdown(
'Rate estimation already complete. Re-run to update with new parameters.
',
unsafe_allow_html=True,
)
if st.button("Estimate β and γ"):
adata_work = st.session_state.adata
try:
prog = st.progress(0, text="Estimating splicing rates (β)…")
scptr.tl.estimate_beta(adata_work, quantile=quantile)
prog.progress(40, text="Estimating degradation rates (γ)…")
scptr.tl.estimate_gamma(
adata_work,
clip_quantile=clip_q,
min_spliced=min_spliced_thr,
)
prog.progress(80, text="Variance decomposition…")
scptr.tl.variance_decomposition(adata_work)
prog.progress(100, text="Done.")
st.session_state.adata = adata_work
st.session_state.estimated = True
reset_downstream(3)
beta = adata_work.var["beta"]
gamma = adata_work.layers["gamma"]
gamma_pos = gamma[gamma > 0]
inf_genes = int((np.median(gamma, axis=0) > 0).sum())
st.markdown(
mg(
("Median β", f"{np.median(beta):.3f}", "splicing rate"),
("Median γ", f"{np.median(gamma_pos):.4f}", "positive cells", "blue"),
("Max γ", f"{np.max(gamma):.2f}", "clipped"),
("Informative genes", f"{inf_genes:,}", "median γ > 0", "green"),
),
unsafe_allow_html=True,
)
# Phase portrait for highest-β gene
top_gene = beta.idxmax()
fig, axes = plt.subplots(1, 2, figsize=(9, 3.8))
# Phase portrait
ax = axes[0]
Ms = adata_work.layers["Ms"][:, adata_work.var_names.get_loc(top_gene)]
Mu = adata_work.layers["Mu"][:, adata_work.var_names.get_loc(top_gene)]
ax.scatter(Ms, Mu, s=5, alpha=0.35, color="#2b5797", linewidths=0)
bv = adata_work.var.loc[top_gene, "beta"]
x = np.linspace(0, np.percentile(Ms, 99), 100)
ax.plot(x, bv * x, color="#c0392b", lw=1.5, label=f"β = {bv:.3f}")
ax.set_xlabel("Ms (smoothed spliced)", fontsize=10)
ax.set_ylabel("Mu (smoothed unspliced)", fontsize=10)
ax.set_title(f"Phase portrait: {top_gene}", fontsize=10, fontweight="bold")
ax.legend(fontsize=9, frameon=False)
ax.spines[["top", "right"]].set_visible(False)
# Beta distribution
ax2 = axes[1]
ax2.hist(beta, bins=50, color="#2b5797", alpha=0.7, linewidth=0)
ax2.axvline(np.median(beta), color="#c0392b", lw=1.5,
label=f"median = {np.median(beta):.3f}")
ax2.set_xlabel("β (splicing rate)", fontsize=10)
ax2.set_ylabel("Gene count", fontsize=10)
ax2.set_title("Distribution of β across genes", fontsize=10, fontweight="bold")
ax2.legend(fontsize=9, frameon=False)
ax2.spines[["top", "right"]].set_visible(False)
plt.tight_layout()
st.image(fig_png(fig), use_container_width=True)
plt.close(fig)
# β quality summary
_beta_pos_pct = (beta > 0).mean() * 100
_gamma_pos_pct = (np.median(adata_work.layers["gamma"], axis=0) > 0).mean() * 100
_quality = "good" if _beta_pos_pct > 60 else "low"
_quality_color = "#2d7d4b" if _quality == "good" else "#d4860a"
st.markdown(
f''
f'Data quality: '
f'{_beta_pos_pct:.0f}% of genes have estimable β · '
f'{_gamma_pos_pct:.0f}% have estimable γ · '
f'{_quality.upper()}'
f'
',
unsafe_allow_html=True,
)
st.markdown(
''
'β and γ estimated, variance decomposition complete. '
'Next: cluster cells in γ-space to discover PT states. '
'Or explore the phase portrait below for individual genes.'
'
',
unsafe_allow_html=True,
)
except Exception as e:
st.markdown(
f'Rate estimation failed: {e}
',
unsafe_allow_html=True,
)
with st.expander("Traceback"):
st.code(traceback.format_exc())
# Phase portrait explorer (available once rates are estimated)
if st.session_state.estimated:
st.markdown('Phase portrait explorer
', unsafe_allow_html=True)
st.markdown(
''
'Inspect the unspliced vs spliced phase portrait for any gene, colored by γ. '
'The diagonal line shows the estimated β slope. Cells above = accelerating; below = decelerating.'
'
',
unsafe_allow_html=True,
)
adata_est = st.session_state.adata
pp_col1, pp_col2 = st.columns([3, 1])
with pp_col1:
pp_gene = st.selectbox(
"Gene",
sorted(adata_est.var_names.tolist()),
key="pp_gene_select",
help="Select a gene to visualize its unspliced vs spliced phase portrait.",
)
with pp_col2:
pp_cmap = st.selectbox("Color", ["viridis", "plasma", "RdBu_r", "coolwarm"], key="pp_cmap",
help="Colormap for γ values in the phase portrait scatter.")
if st.button("Plot Phase Portrait", key="pp_btn"):
try:
fig = scptr.pl.phase_portrait(
adata_est, genes=pp_gene, color_by="gamma",
cmap=pp_cmap, show=False,
)
if fig is not None:
st.image(fig_png(fig), use_container_width=True)
plt.close(fig)
except Exception as e:
st.markdown(f'Phase portrait failed: {e}
', unsafe_allow_html=True)
st.markdown('
', unsafe_allow_html=True)
c1, c2 = st.columns([1, 6])
with c1:
if st.button("← Back"):
go(2); st.rerun()
with c2:
if st.button("Next: Discover PT States →", disabled=not st.session_state.estimated):
go(4); st.rerun()
# ══════════════════════════════════════════════════════════════════════════════
# ANALYSIS — STEP 4: DISCOVER PT STATES
# ══════════════════════════════════════════════════════════════════════════════
elif page == "analysis" and st.session_state.step == 4:
adata = st.session_state.adata
st.markdown('Discover PT States — step 4 of 5
', unsafe_allow_html=True)
st.markdown(
'Cluster cells in γ-space (PCA → kNN → Leiden) to reveal '
'post-transcriptional states invisible to expression analysis. '
'Optionally compute PT velocity and infer RBP–target regulatory networks.
',
unsafe_allow_html=True,
)
tab1, tab2, tab3 = st.tabs(["PT STATES", "PT VELOCITY", "RBP NETWORKS"])
# ── Tab 1: PT States ──────────────────────────────────────────────────────
with tab1:
col1, col2 = st.columns(2, gap="large")
with col1:
st.markdown('Dimensionality reduction
', unsafe_allow_html=True)
n_pcs_g = st.number_input(
"PCA dims (γ-space)",
value=20, min_value=5, max_value=50,
help="PCA components computed from the γ matrix before clustering.",
)
n_nbrs_g = st.number_input(
"Neighbors (γ-space kNN)",
value=15, min_value=5, max_value=50,
help="Number of nearest neighbors in γ-PCA space.",
)
with col2:
st.markdown('Leiden clustering
', unsafe_allow_html=True)
resolution = st.slider(
"Resolution",
0.1, 2.0, 0.5, 0.05,
help="Higher resolution → more, smaller clusters. "
"Typical range: 0.3–0.8. Start at 0.5 and increase if clusters are too coarse.",
)
rand_seed = st.number_input("Random seed", value=42, step=1,
help="Random seed for reproducible clustering and UMAP.")
st.markdown(
''
'PT state discovery performs PCA on the γ matrix, builds a kNN graph in γ-PCA space, '
'then runs Leiden community detection. The resulting clusters represent groups of cells '
'with similar post-transcriptional programs — which may differ from their expression-based identity.'
'
',
unsafe_allow_html=True,
)
if st.session_state.states_done:
n_s = adata.obs["pt_state"].nunique() if "pt_state" in adata.obs else "?"
st.markdown(
f'PT states already computed ({n_s} states). '
f'Re-run to update with new parameters.
',
unsafe_allow_html=True,
)
if st.button("Find PT States"):
try:
with st.spinner("Clustering cells in γ-space…"):
scptr.tl.pt_states(
adata,
n_pcs=n_pcs_g,
n_neighbors=n_nbrs_g,
resolution=resolution,
random_state=rand_seed,
)
st.session_state.adata = adata
st.session_state.states_done = True
st.session_state.velocity_done = False
st.session_state.network_done = False
n_states = adata.obs["pt_state"].nunique()
state_sizes = adata.obs["pt_state"].value_counts().sort_index()
st.markdown(
mg(
("PT States", str(n_states), "Leiden clusters in γ-space", "blue"),
("Largest state", f"{state_sizes.max():,}", "cells"),
("Smallest state", f"{state_sizes.min():,}", "cells"),
),
unsafe_allow_html=True,
)
# Side-by-side UMAP: γ-space vs expression
fig, axes = plt.subplots(1, 2, figsize=(10, 4.2))
# γ-space UMAP
coords_g = adata.obsm["X_gamma_umap"]
labels = adata.obs["pt_state"].values
unique_labels = sorted(set(labels), key=lambda x: int(x) if str(x).isdigit() else x)
cmap = plt.colormaps["tab20"].resampled(len(unique_labels))
label_map = {l: i for i, l in enumerate(unique_labels)}
c = [label_map[l] for l in labels]
sc_plot = axes[0].scatter(
coords_g[:, 0], coords_g[:, 1],
c=c, cmap=cmap, s=8, alpha=0.6, linewidths=0,
)
axes[0].set_title("PT states (γ-space UMAP)", fontsize=10, fontweight="bold")
axes[0].axis("off")
# legend
for l in unique_labels:
axes[0].scatter([], [], color=cmap(label_map[l]), label=str(l), s=20)
axes[0].legend(fontsize=8, frameon=False, ncol=2, loc="upper right")
# Expression UMAP (if available)
if "X_umap" in adata.obsm:
coords_e = adata.obsm["X_umap"]
axes[1].scatter(
coords_e[:, 0], coords_e[:, 1],
c=c, cmap=cmap, s=8, alpha=0.6, linewidths=0,
)
axes[1].set_title("PT states (expression UMAP)", fontsize=10, fontweight="bold")
axes[1].axis("off")
else:
axes[1].text(0.5, 0.5, "No expression UMAP\n(add X_umap to adata.obsm)",
ha="center", va="center", transform=axes[1].transAxes,
fontsize=10, color="#888")
axes[1].axis("off")
plt.tight_layout()
st.image(fig_png(fig), use_container_width=True)
plt.close(fig)
# State size table
rows = "".join(
f"| State {s} | {n:,} | "
f'{n / len(adata.obs) * 100:.1f}% |
'
for s, n in state_sizes.items()
)
st.markdown(
f''
f'| PT State | Cells | % |
'
f'{rows}
',
unsafe_allow_html=True,
)
st.markdown(
'PT state discovery complete. '
'Proceed to Results or explore PT Velocity and RBP Networks.
',
unsafe_allow_html=True,
)
except Exception as e:
st.markdown(
f'PT state discovery failed: {e}
',
unsafe_allow_html=True,
)
with st.expander("Traceback"):
st.code(traceback.format_exc())
# ── Tab 2: PT Velocity ────────────────────────────────────────────────────
with tab2:
if not st.session_state.states_done:
st.markdown(
'Run PT state discovery (Tab 1) before computing velocity.
',
unsafe_allow_html=True,
)
else:
st.markdown(
''
'Post-transcriptional velocity computes, for each cell, the weighted mean '
'difference in γ from its neighbors: v[i,g] = Σ w_ij · (γ[j,g] − γ[i,g]). '
'This captures the direction and magnitude of post-transcriptional change, '
'orthogonal to RNA velocity.'
'
',
unsafe_allow_html=True,
)
vel_c1, vel_c2 = st.columns(2, gap="large")
with vel_c1:
graph_choice = st.radio(
"Neighbor graph",
["γ-space graph (from PT states)", "Expression-space graph"],
horizontal=False,
help="Which kNN graph to use when averaging neighbor γ values.",
)
use_graph = "gamma" if "γ-space" in graph_choice else "expression"
with vel_c2:
viz_style = st.radio(
"Visualization style",
["Arrows (embedding)", "Streamlines"],
horizontal=False,
help="Arrows show per-cell velocity; streamlines show flow patterns.",
)
arrow_size = st.slider("Arrow size", 1.0, 8.0, 3.0, 0.5, key="vel_arrow",
help="Scale of velocity arrows on the embedding plot.")
if st.session_state.velocity_done:
st.markdown(
'PT velocity already computed. Re-run to update.
',
unsafe_allow_html=True,
)
if st.button("Compute PT Velocity"):
try:
with st.spinner("Computing PT velocity…"):
scptr.tl.pt_velocity(adata, use_graph=use_graph)
st.session_state.adata = adata
st.session_state.velocity_done = True
fig, ax = plt.subplots(figsize=(6, 5))
try:
if "Stream" in viz_style:
scptr.pl.pt_velocity_stream(adata, ax=ax, show=False)
else:
scptr.pl.pt_velocity_embedding(adata, ax=ax, arrow_size=arrow_size, show=False)
except Exception:
coords = adata.obsm.get("X_gamma_umap", adata.obsm.get("X_umap"))
if coords is not None:
ax.scatter(coords[:, 0], coords[:, 1], s=6, alpha=0.4,
color="#2b5797", linewidths=0)
ax.set_title(f"Post-transcriptional velocity ({'streamlines' if 'Stream' in viz_style else 'arrows'})", fontsize=10)
ax.axis("off")
plt.tight_layout()
st.image(fig_png(fig), use_container_width=True)
plt.close(fig)
st.markdown(
'PT velocity computed and stored in '
'adata.layers["pt_velocity"].
',
unsafe_allow_html=True,
)
except Exception as e:
st.markdown(
f'PT velocity failed: {e}
',
unsafe_allow_html=True,
)
with st.expander("Traceback"):
st.code(traceback.format_exc())
# ── Tab 3: RBP Networks ───────────────────────────────────────────────────
with tab3:
if not st.session_state.states_done:
st.markdown(
'Run PT state discovery (Tab 1) before inferring networks.
',
unsafe_allow_html=True,
)
else:
st.markdown(
''
'RBP–target network inference regresses γ of each target gene on the '
'smoothed expression of regulator genes using elastic net regression. '
'Non-zero coefficients indicate putative regulatory relationships. '
'Runtime scales with number of genes — start with defaults for speed.'
'
',
unsafe_allow_html=True,
)
# Core settings
use_known_rbps = st.checkbox(
"Restrict regulators to known RBPs (recommended — faster, more interpretable)",
value=True,
help="Filter regulators to curated RNA-binding proteins only.",
)
rbp_organism = None
if use_known_rbps:
rbp_organism = st.selectbox(
"RBP organism",
["human", "mouse", None],
format_func=lambda x: x if x else "all species",
key="rbp_org",
)
with st.expander("Advanced options"):
net_c1, net_c2 = st.columns(2, gap="large")
with net_c1:
n_top = st.number_input(
"Top edges per target gene",
value=50, min_value=5, max_value=500,
help="Maximum number of regulator–target edges to retain per gene.",
)
alpha = st.slider(
"Elastic net mixing (α)",
0.0, 1.0, 0.5, 0.05,
help="0 = ridge (all regulators retained), 1 = lasso (sparse selection). 0.5 = elastic net.",
)
with net_c2:
custom_regs = st.text_area(
"Additional regulators (optional)",
value="",
height=80,
help="Comma or newline-separated gene names. Appended to known RBPs if that option is checked.",
)
custom_tgts = st.text_area(
"Restrict to these targets (optional)",
value="",
height=80,
help="Leave empty to use all genes as targets.",
)
if st.session_state.network_done:
net = adata.uns.get("pt_network", pd.DataFrame())
st.markdown(
f'Network already inferred ({len(net):,} edges). '
f'Re-run to update.
',
unsafe_allow_html=True,
)
if st.button("Infer RBP–Target Network"):
regs = None
tgts = None
# Build regulator list
if use_known_rbps:
try:
known = scptr.tl.list_known_rbps(organism=rbp_organism if use_known_rbps else None)
# Keep only those present in adata
known = [g for g in known if g in adata.var_names]
regs = known if known else None
except Exception:
regs = None
if custom_regs.strip():
extra = [g.strip() for g in custom_regs.replace(",", "\n").split("\n") if g.strip()]
regs = list(set((regs or []) + extra)) if regs else extra
if custom_tgts.strip():
tgts = [g.strip() for g in custom_tgts.replace(",", "\n").split("\n") if g.strip()]
if regs:
st.markdown(
f'Using {len(regs):,} regulators.
',
unsafe_allow_html=True,
)
try:
with st.spinner("Running elastic net regression… (may take several minutes for large datasets)"):
scptr.tl.infer_network(
adata,
regulators=regs,
targets=tgts,
method="elasticnet",
alpha=alpha,
n_top=n_top,
)
st.session_state.adata = adata
st.session_state.network_done = True
net = adata.uns.get("pt_network", pd.DataFrame())
if len(net) == 0:
st.markdown(
'No significant edges found. '
'Try reducing α or increasing n_top.
',
unsafe_allow_html=True,
)
else:
n_destab = int((net["weight"] > 0).sum())
n_stab = int((net["weight"] < 0).sum())
st.markdown(
mg(
("Total edges", f"{len(net):,}", "regulator–target pairs"),
("Destabilizing", f"{n_destab:,}", "weight > 0", "blue"),
("Stabilizing", f"{n_stab:,}", "weight < 0", "green"),
("Hub regulators", f"{net['regulator'].nunique():,}", "unique"),
),
unsafe_allow_html=True,
)
st.markdown(
''
'Edge weights: positive = regulator destabilizes target (promotes degradation); '
'negative = regulator stabilizes target (protects from degradation).'
'
',
unsafe_allow_html=True,
)
# Hub table with direction
hubs_dest = net[net["weight"] > 0].groupby("regulator").size()
hubs_stab = net[net["weight"] < 0].groupby("regulator").size()
hubs_all = net.groupby("regulator").size().sort_values(ascending=False).head(15)
rows = "".join(
f"| {rbp} | {cnt:,} | "
f"{hubs_dest.get(rbp, 0):,} | "
f"{hubs_stab.get(rbp, 0):,} |
"
for rbp, cnt in hubs_all.items()
)
st.markdown(
f''
f'| Regulator | Total | Destab. | Stab. |
'
f'{rows}
',
unsafe_allow_html=True,
)
# Network plot
try:
fig, ax = plt.subplots(figsize=(7, 6))
scptr.pl.network_graph(adata, n_edges=60, ax=ax, show=False)
ax.set_title("Top regulatory edges", fontsize=10, fontweight="bold")
plt.tight_layout()
st.image(fig_png(fig), use_container_width=True)
plt.close(fig)
except Exception as _ne:
st.markdown(
f'Network plot could not be rendered: {_ne}
',
unsafe_allow_html=True,
)
st.markdown(
'Network inference complete. '
'Results stored in adata.uns["pt_network"].
',
unsafe_allow_html=True,
)
except Exception as e:
st.markdown(
f'Network inference failed: {e}
',
unsafe_allow_html=True,
)
with st.expander("Traceback"):
st.code(traceback.format_exc())
st.markdown('
', unsafe_allow_html=True)
c1, c2 = st.columns([1, 6])
with c1:
if st.button("← Back"):
go(3); st.rerun()
with c2:
if st.button("View Results →", disabled=not st.session_state.states_done):
go(5); st.rerun()
# ══════════════════════════════════════════════════════════════════════════════
# ANALYSIS — STEP 5: RESULTS
# ══════════════════════════════════════════════════════════════════════════════
elif page == "analysis" and st.session_state.step == 5:
adata = st.session_state.adata
st.markdown('Results — step 5 of 5
', unsafe_allow_html=True)
# Summary metrics
gamma = adata.layers.get("gamma")
gamma_pos = gamma[gamma > 0] if gamma is not None else np.array([])
n_states = adata.obs["pt_state"].nunique() if "pt_state" in adata.obs else 0
beta = adata.var.get("beta")
net = adata.uns.get("pt_network", pd.DataFrame())
st.markdown(
mg(
("Cells", f"{adata.n_obs:,}", ""),
("Genes", f"{adata.n_vars:,}", ""),
("PT States", str(n_states), "γ-space Leiden", "blue"),
("Median β", f"{np.median(beta):.3f}" if beta is not None else "—", "splicing rate"),
("Median γ", f"{np.median(gamma_pos):.4f}" if len(gamma_pos) else "—", "positive cells"),
("Network edges", f"{len(net):,}" if len(net) else "—", "RBP–target", "green"),
),
unsafe_allow_html=True,
)
# Analysis completion summary
_done_items = []
if beta is not None: _done_items.append("β estimated")
if gamma is not None: _done_items.append("γ estimated")
if "tf_score" in adata.var.columns: _done_items.append("variance decomposed")
if n_states > 0: _done_items.append(f"{n_states} PT states")
if st.session_state.velocity_done: _done_items.append("PT velocity")
if st.session_state.network_done: _done_items.append(f"{len(net):,} network edges")
if _done_items:
st.markdown(
''
f'Analyses complete: {" · ".join(_done_items)}'
'
',
unsafe_allow_html=True,
)
rtab1, rtab2, rtab3, rtab4, rtab5 = st.tabs(["VISUALIZATION", "VARIANCE DECOMP", "GENE RANKINGS", "GAMMA EXPLORER", "DOWNLOAD"])
# ── Visualization ─────────────────────────────────────────────────────────
with rtab1:
st.markdown(
'Choose a column to color by and click Plot UMAP to visualize cells. '
'Toggle γ-space UMAP to compare expression vs. post-transcriptional organization.
',
unsafe_allow_html=True,
)
col_a, col_b = st.columns([2, 1])
with col_a:
color_opts = []
if "pt_state" in adata.obs.columns:
color_opts.append("pt_state")
color_opts += [c for c in adata.obs.columns if c != "pt_state"][:30]
viz_col = st.selectbox("Color by", color_opts, label_visibility="visible")
with col_b:
use_g_umap = st.checkbox(
"γ-space UMAP",
value=True,
help="Use UMAP computed from γ-space PCA (vs. expression UMAP)",
)
if st.button("Plot UMAP"):
basis = "X_gamma_umap" if (use_g_umap and "X_gamma_umap" in adata.obsm) else "X_umap"
if basis not in adata.obsm and "X_umap" not in adata.obsm:
with st.spinner("Computing expression UMAP…"):
sc.tl.umap(adata)
basis = "X_umap"
elif basis not in adata.obsm:
basis = "X_umap"
fig, ax = plt.subplots(figsize=(6, 5))
sc.pl.embedding(
adata, basis=basis, color=viz_col, ax=ax, show=False,
frameon=False, size=14,
title=f"{viz_col} · {'γ-space' if 'gamma' in basis else 'expression'} UMAP",
)
plt.tight_layout()
st.image(fig_png(fig), use_container_width=True)
plt.close(fig)
# PT state UMAP using native scptr function
if n_states > 0 and "X_gamma_umap" in adata.obsm:
st.markdown('
', unsafe_allow_html=True)
if st.button("PT State UMAP (γ-space)"):
try:
fig = scptr.pl.pt_umap(adata, show=False)
if fig is not None:
st.image(fig_png(fig), use_container_width=True)
plt.close(fig)
except Exception as e:
st.markdown(f'PT UMAP failed: {e}
', unsafe_allow_html=True)
if gamma is not None and n_states > 0:
st.markdown('
', unsafe_allow_html=True)
if st.button("Plot Gamma Heatmap"):
with st.spinner("Building heatmap…"):
try:
fig = scptr.pl.gamma_heatmap(adata, groupby="pt_state", show=False)
if fig is not None:
st.image(fig_png(fig), use_container_width=True)
plt.close(fig)
except Exception as e:
st.markdown(f'Heatmap failed: {e}
', unsafe_allow_html=True)
if "X_gamma_umap" in adata.obsm and "X_umap" in adata.obsm:
st.markdown('
', unsafe_allow_html=True)
if st.button("γ-space vs Expression Comparison"):
with st.spinner("Building side-by-side comparison…"):
try:
fig = scptr.pl.pt_comparison(adata, figsize=(12, 5), show=False)
if fig:
st.image(fig_png(fig), use_container_width=True)
plt.close(fig)
except Exception as e:
# Fallback: manual side-by-side
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
for ax, basis, title in [
(axes[0], "X_umap", "Expression UMAP"),
(axes[1], "X_gamma_umap", "γ-space UMAP"),
]:
coords = adata.obsm[basis]
if "pt_state" in adata.obs.columns:
labels = adata.obs["pt_state"].values
unique = sorted(set(labels), key=lambda x: int(x) if str(x).isdigit() else x)
cmap = plt.colormaps["tab20"].resampled(len(unique))
lmap = {l: i for i, l in enumerate(unique)}
c = [lmap[l] for l in labels]
ax.scatter(coords[:, 0], coords[:, 1], c=c, cmap=cmap,
s=8, alpha=0.6, linewidths=0)
else:
ax.scatter(coords[:, 0], coords[:, 1], s=8, alpha=0.5,
color="#2b5797", linewidths=0)
ax.set_title(title, fontsize=10, fontweight="bold")
ax.axis("off")
plt.tight_layout()
st.image(fig_png(fig), use_container_width=True)
plt.close(fig)
if st.session_state.velocity_done:
st.markdown('
', unsafe_allow_html=True)
if st.button("Plot PT Velocity"):
try:
fig, ax = plt.subplots(figsize=(6, 5))
scptr.pl.pt_velocity_embedding(adata, ax=ax, show=False)
ax.set_title("Post-transcriptional velocity", fontsize=10)
plt.tight_layout()
st.image(fig_png(fig), use_container_width=True)
plt.close(fig)
except Exception as e:
st.markdown(f'Velocity plot failed: {e}
', unsafe_allow_html=True)
# ── Variance decomposition ────────────────────────────────────────────────
with rtab2:
has_vd = "tf_score" in adata.var.columns and "ptf_score" in adata.var.columns
if not has_vd:
st.markdown(
'Variance decomposition not computed. '
'Return to step 3 and run Estimate β and γ (variance decomposition runs automatically).
',
unsafe_allow_html=True,
)
else:
st.markdown(
''
'Each gene\'s variance is decomposed into a transcriptional fraction (TF, driven by changes in '
'unspliced/nascent RNA) and a post-transcriptional fraction (PTF, driven by changes in γ). '
'Genes with high PTF score are primarily regulated post-transcriptionally.'
'
',
unsafe_allow_html=True,
)
tf = adata.var["tf_score"]
ptf = adata.var["ptf_score"]
# Aggregate stats
ptf_dom = (ptf > 0.5).sum()
tf_dom = (tf > 0.5).sum()
st.markdown(
mg(
("PTF-dominant genes", f"{ptf_dom:,}", "PTF score > 0.5", "blue"),
("TF-dominant genes", f"{tf_dom:,}", "TF score > 0.5"),
("Median PTF score", f"{ptf.median():.3f}", "across genes"),
),
unsafe_allow_html=True,
)
n_label = st.slider("Label top N genes", 5, 30, 10, 5, key="vd_label")
if st.button("Plot Variance Decomposition"):
try:
fig = scptr.pl.tf_ptf_scatter(adata, label_top=n_label, show=False)
if fig:
st.image(fig_png(fig), use_container_width=True)
plt.close(fig)
except Exception as e:
# Fallback: manual plot
fig, axes = plt.subplots(1, 2, figsize=(10, 4.5))
axes[0].hist(ptf, bins=50, color="#2b5797", alpha=0.75, linewidth=0)
axes[0].axvline(0.5, color="#c0392b", lw=1.5, ls="--", label="PTF=0.5")
axes[0].set_xlabel("PTF score", fontsize=10)
axes[0].set_ylabel("Gene count", fontsize=10)
axes[0].set_title("Distribution of PTF scores", fontsize=10, fontweight="bold")
axes[0].legend(fontsize=9, frameon=False)
axes[0].spines[["top","right"]].set_visible(False)
rank = np.argsort(ptf.values)
axes[1].scatter(range(len(ptf)), ptf.values[rank], s=4, alpha=0.5,
color="#2b5797", linewidths=0)
axes[1].axhline(0.5, color="#c0392b", lw=1.2, ls="--")
axes[1].set_xlabel("Gene rank", fontsize=10)
axes[1].set_ylabel("PTF score", fontsize=10)
axes[1].set_title("Ranked PTF scores", fontsize=10, fontweight="bold")
axes[1].spines[["top","right"]].set_visible(False)
plt.tight_layout()
st.image(fig_png(fig), use_container_width=True)
plt.close(fig)
# Top PTF genes table
st.markdown('Top post-transcriptionally regulated genes
', unsafe_allow_html=True)
top_ptf = ptf.sort_values(ascending=False).head(30)
ptf_df = pd.DataFrame({
"Gene": top_ptf.index,
"PTF score": top_ptf.values.round(4),
"TF score": tf[top_ptf.index].values.round(4),
})
st.dataframe(ptf_df, use_container_width=True, hide_index=True, height=420)
# ── Gene rankings ─────────────────────────────────────────────────────────
with rtab3:
if n_states == 0:
st.markdown(
'No PT states found. Run Discover PT States → PT STATES tab first, '
'then return here to rank differentially degraded genes.
',
unsafe_allow_html=True,
)
else:
st.markdown(
'Identifies genes with significantly different γ (degradation rate) '
'between PT states — analogous to differential expression but in γ-space.
',
unsafe_allow_html=True,
)
rank_method = st.selectbox(
"Statistical test",
["t-test", "wilcoxon"],
help="t-test is faster; Wilcoxon rank-sum is more robust to outliers.",
)
if st.button("Rank PT-Differential Genes"):
with st.spinner("Running differential γ test…"):
try:
scptr.tl.rank_pt_genes(adata, method=rank_method)
st.session_state.adata = adata
except Exception as e:
st.markdown(f'Ranking failed: {e}
', unsafe_allow_html=True)
if "rank_pt_genes" in adata.uns:
names = adata.uns["rank_pt_genes"].get("names", {})
if names:
groups = list(names.keys())
show_groups = st.multiselect(
"Show states",
groups,
default=groups[:min(4, len(groups))],
)
if show_groups:
top_n_genes = st.slider("Genes per state", 5, 50, 15, 5, key="rank_n")
all_rows = []
for g in show_groups:
gene_list = list(names[g])[:top_n_genes]
for rank, gene in enumerate(gene_list, 1):
all_rows.append({"State": f"PT {g}", "Rank": rank, "Gene": gene})
if all_rows:
rank_df = pd.DataFrame(all_rows)
st.dataframe(rank_df, use_container_width=True, hide_index=True, height=380)
st.download_button(
"Download ranked genes (.csv)",
rank_df.to_csv(index=False).encode(),
file_name=f"ranked_genes_{st.session_state.dataset_name}.csv",
mime="text/csv",
)
if beta is not None:
st.markdown('
', unsafe_allow_html=True)
st.markdown('Genes by splicing rate (β)
', unsafe_allow_html=True)
top_n = st.slider("Show top N genes", 10, 100, 30, 10, key="top_beta_n")
top_beta = beta.sort_values(ascending=False).head(top_n)
beta_df = pd.DataFrame({"Gene": top_beta.index, "β (splicing rate)": top_beta.values.round(5)})
st.dataframe(beta_df, use_container_width=True, hide_index=True, height=350)
# ── Gamma explorer ────────────────────────────────────────────────────────
with rtab4:
if gamma is None:
st.markdown('No γ data available.
', unsafe_allow_html=True)
else:
st.markdown(
'Explore the distribution of degradation rates for individual genes '
'or compare γ across PT states.
',
unsafe_allow_html=True,
)
ge_col1, ge_col2 = st.columns([2, 1])
with ge_col1:
gene_input = st.selectbox(
"Select gene",
sorted(adata.var_names.tolist()),
key="gamma_gene",
)
with ge_col2:
groupby_col = "pt_state" if "pt_state" in adata.obs.columns else None
if groupby_col is None:
st.markdown('No PT states computed yet
', unsafe_allow_html=True)
if gene_input and st.button("Plot γ for selected gene"):
g_idx = adata.var_names.get_loc(gene_input)
g_vals = gamma[:, g_idx]
g_pos = g_vals[g_vals > 0]
# Try scptr.pl.gamma_violin first, fall back to manual
if groupby_col:
try:
fig = scptr.pl.gamma_violin(adata, genes=gene_input, groupby=groupby_col, show=False)
if fig:
st.image(fig_png(fig), use_container_width=True)
plt.close(fig)
raise StopIteration # skip fallback
except StopIteration:
pass
except Exception:
pass # fall through to manual
# Manual histogram + violin fallback
fig, axes = plt.subplots(1, 2 if groupby_col else 1, figsize=(9 if groupby_col else 5, 3.8))
ax0 = axes[0] if groupby_col else axes
ax0.hist(g_pos, bins=40, color="#2b5797", alpha=0.75, linewidth=0)
if len(g_pos):
ax0.axvline(np.median(g_pos), color="#c0392b", lw=1.5,
label=f"median = {np.median(g_pos):.4f}")
ax0.legend(fontsize=9, frameon=False)
ax0.set_xlabel(f"γ ({gene_input})", fontsize=10)
ax0.set_ylabel("Cell count", fontsize=10)
ax0.set_title(f"γ distribution: {gene_input}", fontsize=10, fontweight="bold")
ax0.spines[["top", "right"]].set_visible(False)
if groupby_col:
states = sorted(adata.obs[groupby_col].unique(),
key=lambda x: int(x) if str(x).isdigit() else x)
data_by_state = [g_vals[adata.obs[groupby_col] == s] for s in states]
vp = axes[1].violinplot(data_by_state, positions=range(len(states)),
showmedians=True, showextrema=False)
for body in vp["bodies"]:
body.set_facecolor("#2b5797"); body.set_alpha(0.6)
vp["cmedians"].set_color("#c0392b")
axes[1].set_xticks(range(len(states)))
axes[1].set_xticklabels([str(s) for s in states], fontsize=9)
axes[1].set_xlabel("PT State", fontsize=10)
axes[1].set_ylabel(f"γ ({gene_input})", fontsize=10)
axes[1].set_title("γ by PT state", fontsize=10, fontweight="bold")
axes[1].spines[["top", "right"]].set_visible(False)
plt.tight_layout()
st.image(fig_png(fig), use_container_width=True)
plt.close(fig)
st.markdown(
mg(
("Median γ", f"{np.median(g_pos):.4f}" if len(g_pos) else "—", "positive cells"),
("Max γ", f"{np.max(g_vals):.4f}", ""),
("Cells γ > 0", f"{int((g_vals > 0).sum()):,}", f"of {adata.n_obs:,}"),
),
unsafe_allow_html=True,
)
# ── Download ──────────────────────────────────────────────────────────────
with rtab5:
st.markdown('Export results
', unsafe_allow_html=True)
col1, col2, col3 = st.columns(3)
with col1:
st.markdown("**Full AnnData**")
st.markdown(
''
'All layers (γ, β, Ms, Mu) plus PT state assignments and embeddings.
',
unsafe_allow_html=True,
)
if st.button("Prepare AnnData (.h5ad)"):
tmp = make_tmp(".h5ad")
with st.spinner("Writing…"):
adata.write_h5ad(tmp)
with open(tmp, "rb") as f:
st.download_button(
"Download .h5ad",
f.read(),
file_name=f"scptr_{st.session_state.dataset_name}.h5ad",
mime="application/octet-stream",
)
with col2:
if gamma is not None:
st.markdown("**Gamma matrix**")
st.markdown(
''
'Cells × genes CSV of degradation rates γ.
',
unsafe_allow_html=True,
)
if st.button("Prepare γ matrix (.csv)"):
with st.spinner("Building CSV…"):
gamma_df = pd.DataFrame(
gamma,
index=adata.obs_names,
columns=adata.var_names,
)
csv_bytes = gamma_df.to_csv().encode()
st.download_button(
"Download gamma.csv",
csv_bytes,
file_name=f"gamma_{st.session_state.dataset_name}.csv",
mime="text/csv",
)
with col3:
st.markdown("**Cell metadata**")
st.markdown(
''
'PT state assignments per cell (CSV).
',
unsafe_allow_html=True,
)
obs_cols = [c for c in ["pt_state"] if c in adata.obs.columns]
if obs_cols:
obs_csv = adata.obs[obs_cols].copy().to_csv().encode()
st.download_button(
"Download metadata.csv",
obs_csv,
file_name=f"metadata_{st.session_state.dataset_name}.csv",
mime="text/csv",
)
else:
st.markdown(
'Run Discover PT States first to populate cell metadata.
',
unsafe_allow_html=True,
)
st.markdown('
', unsafe_allow_html=True)
col_d1, col_d2, col_d3 = st.columns(3)
with col_d1:
if beta is not None:
st.markdown("**Gene splicing rates (β)**")
st.markdown(
''
'Per-gene β from phase portrait quantile regression.
',
unsafe_allow_html=True,
)
beta_df = pd.DataFrame({"gene": beta.index, "beta": beta.values})
st.download_button(
"Download beta.csv",
beta_df.to_csv(index=False).encode(),
file_name=f"beta_{st.session_state.dataset_name}.csv",
mime="text/csv",
)
with col_d2:
if "tf_score" in adata.var.columns:
st.markdown("**Variance decomposition**")
st.markdown(
''
'TF and PTF score per gene (0–1).
',
unsafe_allow_html=True,
)
vd_df = pd.DataFrame({
"gene": adata.var_names,
"tf_score": adata.var["tf_score"].values,
"ptf_score": adata.var["ptf_score"].values,
})
st.download_button(
"Download variance_decomp.csv",
vd_df.to_csv(index=False).encode(),
file_name=f"variance_decomp_{st.session_state.dataset_name}.csv",
mime="text/csv",
)
with col_d3:
st.markdown("**Analysis parameters**")
st.markdown(
''
'Reproducibility: parameters logged by scPTR.
',
unsafe_allow_html=True,
)
params_log = adata.uns.get("scptr", {})
if params_log:
st.download_button(
"Download parameters.json",
json.dumps(params_log, indent=2, default=str).encode(),
file_name=f"parameters_{st.session_state.dataset_name}.json",
mime="application/json",
)
else:
st.markdown(
'No logged parameters yet — run the full pipeline to populate.
',
unsafe_allow_html=True,
)
if len(net) > 0:
st.markdown('
', unsafe_allow_html=True)
st.markdown("**RBP–target network**")
st.markdown(
''
'Columns: regulator, target, weight. Positive weight = destabilizing; negative = stabilizing.
',
unsafe_allow_html=True,
)
net_csv = net.to_csv(index=False).encode()
st.download_button(
"Download network.csv",
net_csv,
file_name=f"network_{st.session_state.dataset_name}.csv",
mime="text/csv",
)
st.markdown('
', unsafe_allow_html=True)
if st.button("← Start Over"):
clean_tmps()
for k, v in {
"step": 1,
"adata": None,
"dataset_name": None,
"preprocessed": False,
"estimated": False,
"states_done": False,
"velocity_done": False,
"network_done": False,
}.items():
st.session_state[k] = v
nav("analysis"); st.rerun()
# ══════════════════════════════════════════════════════════════════════════════
# DOCUMENTATION PAGE
# ══════════════════════════════════════════════════════════════════════════════
elif page == "docs":
st.markdown('Documentation
', unsafe_allow_html=True)
st.markdown(
'Method details, parameter reference, and interpretation guide.
',
unsafe_allow_html=True,
)
dtab1, dtab2, dtab3, dtab4, dtab5, dtab6 = st.tabs(["METHOD", "PARAMETERS", "INTERPRETATION", "QUICK START", "TROUBLESHOOTING", "CITATION"])
# ── Method ────────────────────────────────────────────────────────────────
with dtab1:
st.markdown(
''
'
The kinetic model
'
'
'
'scPTR is based on the kinetic model of RNA metabolism where each gene g has a '
'transcription rate α, splicing rate β, and degradation rate γ. At steady state, '
'the rates satisfy:'
'
'
'
'
'du/dt = α − β · u = 0 → u* = α/β\n'
'ds/dt = β · u − γ · s = 0 → s* = α/γ\n\n'
'Therefore: γ_ig = β_g · u_ig / s_ig'
'
'
'
'
'This means γ is directly estimable from observed spliced and unspliced counts, '
'given an estimate of β. Critically, γ can vary per cell because of '
'post-transcriptional regulatory programs (miRNA-mediated repression, RBP binding, '
'codon usage, etc.).'
'
'
'
',
unsafe_allow_html=True,
)
st.markdown(
''
'
Beta estimation
'
'
'
'The splicing rate βg is gene-specific and estimated from the phase portrait '
'(u vs. s plot) using quantile regression on the upper boundary of the u/s ratio. '
'This approach captures the slope of the kinetic upper boundary, which reflects the '
'maximum u/s ratio observed across cells — corresponding to minimal degradation.'
'
'
'
'
'Concretely, β̂g = quantile(uig / sig, q=0.95) '
'clipped at the 99th percentile of positive values.'
'
'
'
',
unsafe_allow_html=True,
)
st.markdown(
''
'
Post-transcriptional state discovery
'
'
'
'To identify cell populations with distinct degradation programs, scPTR:'
'
'
'
'
'- Computes PCA on the γ matrix (cells × genes)
'
'- Builds a kNN graph in γ-PCA space
'
'- Runs Leiden community detection
'
'- Embeds in 2D using UMAP for visualization
'
'
'
'
'
'These clusters can differ from expression-based clusters — a cell may be '
'transcriptionally similar to its neighbors but have a distinct degradation program '
'("expression-invisible" state).'
'
'
'
'
'Zero-permutation control: scPTR validates that PT states are not artifactual '
'by permuting γ values randomly across cells and recomputing clusters. The adjusted '
'Rand index (ARI) between real and permuted PT states should be near 0.'
'
'
'
',
unsafe_allow_html=True,
)
st.markdown(
''
'
RBP–target network inference
'
'
'
'For each target gene, scPTR regresses its γ values across cells on the '
'smoothed expression of regulator genes (putative RBPs) using elastic net regression:'
'
'
'
γ_target ~ Σ_r coef_r · expr_r + ε
'
'
'
'Non-zero coefficients indicate regulatory relationships. Positive coefficients imply '
'the regulator promotes degradation (destabilizing); negative implies protection '
'(stabilizing).'
'
'
'
',
unsafe_allow_html=True,
)
# ── Parameters ────────────────────────────────────────────────────────────
with dtab2:
def param_row(name, type_, default, desc):
return (
f''
f'| {name} | '
f'{type_} | '
f'{default} | '
f'{desc} | '
f'
'
)
tables = [
("pp.filter_genes", [
("min_unspliced_counts", "int", "10", "Minimum total unspliced count across all cells."),
("min_unspliced_cells", "int", "5", "Minimum cells with nonzero unspliced expression."),
("min_spliced_counts", "int", "0", "Minimum total spliced count (rarely changed)."),
]),
("pp.neighbors", [
("n_neighbors", "int", "30", "Number of nearest neighbors for the cell graph."),
("n_pcs", "int", "30", "PCA components used to build the neighbor graph."),
]),
("pp.smooth_layers", [
("bandwidth", "float | None", "None", "Gaussian kernel bandwidth. None = adaptive (median kNN distance)."),
]),
("tl.estimate_beta", [
("quantile", "float", "0.95", "Upper quantile of u/s ratio used as the kinetic boundary."),
]),
("tl.estimate_gamma", [
("clip_quantile", "float", "0.99", "Per-gene clipping quantile to remove extreme γ values."),
("min_spliced", "float", "0.01", "Minimum smoothed spliced (Ms) for reliable γ; below this γ = 0."),
("mode", "str", "'steady_state'", "'steady_state' or 'dynamic' (uses ds/dt from RNA velocity)."),
]),
("tl.pt_states", [
("resolution", "float", "0.5", "Leiden resolution. Higher → more, smaller clusters."),
("n_pcs", "int", "30", "PCA components computed from the γ matrix."),
("n_neighbors", "int", "30", "kNN neighbors in γ-PCA space."),
("random_state", "int", "0", "Random seed for PCA, UMAP, and Leiden."),
]),
("tl.pt_velocity", [
("use_graph", "str", "'gamma'", "'gamma' = γ-space kNN graph; 'expression' = expression kNN graph."),
]),
("tl.infer_network", [
("regulators", "list | None", "None", "Regulator gene names. None = all genes used as regulators."),
("targets", "list | None", "None", "Target gene names. None = all genes used as targets."),
("method", "str", "'elasticnet'", "Regression method. Currently only 'elasticnet'."),
("alpha", "float", "0.5", "Elastic net mixing: 0 = ridge, 1 = lasso, 0.5 = elastic net."),
("n_top", "int", "50", "Maximum edges to retain per target gene."),
]),
]
for fn_name, params in tables:
rows = "".join(param_row(*p) for p in params)
st.markdown(
f''
f'
{fn_name}
'
f'
'
f'| Parameter | Type | Default | Description |
'
f'{rows}'
f'
'
f'
',
unsafe_allow_html=True,
)
# ── Interpretation ────────────────────────────────────────────────────────
with dtab3:
st.markdown(
''
'
Interpreting γ values
'
'
'
'γ (gamma) represents the mRNA degradation rate — higher γ means faster '
'turnover. Key relationships:'
'
'
'
'
'| γ value | Meaning |
'
''
'| γ = 0 | Insufficient spliced counts; rate not estimable |
'
'| γ → small (e.g., 0.001) | Slow degradation; stable mRNA |
'
'| γ → large (e.g., 0.5+) | Rapid degradation; unstable mRNA |
'
'| γ varies across cells | Post-transcriptional regulation; likely RBP or miRNA activity |
'
'
'
'
',
unsafe_allow_html=True,
)
st.markdown(
''
'
Interpreting PT states
'
'
'
'A PT state is a cluster of cells with similar γ profiles. Biologically, this means:'
'
'
'
'
'- Same PT state, same expression cluster: transcriptional and post-transcriptional programs are aligned
'
'- Different PT states within one expression cluster: expression-invisible state — cells look identical transcriptionally but differ in RNA stability
'
'- Same PT state, different expression clusters: convergent post-transcriptional programs across distinct cell types
'
'
'
'
'
'Use the silhouette score to assess separation: higher in γ-space than '
'expression-space indicates a genuine post-transcriptional signature.'
'
'
'
',
unsafe_allow_html=True,
)
st.markdown(
''
'
Interpreting PT velocity
'
'
'
'PT velocity captures the direction and magnitude of change in γ across the '
'γ-space neighborhood graph. Unlike RNA velocity (which reflects nascent → mature RNA '
'flow), PT velocity is orthogonal — it reflects where in γ-space a cell is headed.'
'
'
'
'
'- Arrow direction: predicted future γ profile of the cell
'
'- Arrow length: magnitude of degradation-rate change (longer = faster transition)
'
'- Coherent arrows in a region suggest a shared post-transcriptional program being gained or lost
'
'- Divergent arrows suggest a decision point where cells adopt different degradation programs
'
'
'
'
'
'PT velocity precedes expression changes for 54–78% of transition genes '
'(pancreas p < 10⁻⁵⁷, dentate gyrus p = 9.9×10⁻¹³), making it a leading '
'indicator of cell-fate decisions.'
'
'
'
',
unsafe_allow_html=True,
)
st.markdown(
''
'
Interpreting network edges
'
'
'
'RNA-binding proteins (RBPs) are post-transcriptional regulators that bind mRNA to control '
'stability, splicing, and translation. scPTR infers RBP→target edges where RBP expression '
'predicts γ of the target, using library-size-corrected elastic net regression.'
'
'
'
'
'Each edge has a weight (regression coefficient):'
'
'
'
'
'- Positive weight: RBP expression correlates with higher γ → '
'the RBP destabilizes the target mRNA
'
'- Negative weight: RBP expression correlates with lower γ → '
'the RBP stabilizes the target mRNA
'
'- |weight| magnitude: filter by |weight| > 0.05 to retain high-confidence edges
'
'- Hub regulators (many edges) are likely master regulators '
'— validated hubs include HNRNPA1, YBX1, ELAVL1/HuR, RBFOX1
'
'
'
'
'
'To validate edges, cross-reference with CLIP-seq databases (e.g., ENCODE eCLIP, '
'ATtRACT) or miRNA target databases (TargetScan) for experimental support.'
'
'
'
',
unsafe_allow_html=True,
)
# ── Quick Start ───────────────────────────────────────────────────────────
with dtab4:
st.markdown(
''
'
Python quick start
'
'
'
'import scptr\n\n'
'# Load data (must have spliced + unspliced layers)\n'
'adata = scptr.read_h5ad("your_data.h5ad")\n\n'
'# Preprocessing\n'
'scptr.pp.filter_genes(adata, min_unspliced_counts=10, min_unspliced_cells=5)\n'
'scptr.pp.normalize_layers(adata)\n'
'scptr.pp.neighbors(adata, n_neighbors=30, n_pcs=30)\n'
'scptr.pp.smooth_layers(adata) # Gaussian kernel smoothing\n\n'
'# Rate estimation\n'
'scptr.tl.estimate_beta(adata, quantile=0.95)\n'
'scptr.tl.estimate_gamma(adata, clip_quantile=0.99, min_spliced=0.01)\n'
'scptr.tl.variance_decomposition(adata)\n\n'
'# PT state discovery\n'
'scptr.tl.pt_states(adata, resolution=0.5, n_pcs=20, n_neighbors=15)\n\n'
'# Optional: PT velocity\n'
'scptr.tl.pt_velocity(adata, use_graph="gamma")\n\n'
'# Optional: RBP–target network\n'
'net = scptr.tl.infer_network(adata, alpha=0.5, n_top=50)\n'
'# Results in adata.uns["pt_network"]\n\n'
'# Visualization\n'
'scptr.pl.pt_umap(adata) # γ-space UMAP\n'
'scptr.pl.gamma_heatmap(adata, groupby="pt_state")\n'
'scptr.pl.network_graph(adata, n_edges=50)'
'
'
'
',
unsafe_allow_html=True,
)
st.markdown(
''
'
Installation
'
'
'
'pip install . # core package\n'
'pip install ".[datasets]" # built-in pancreas / dentate gyrus\n'
'pip install ".[deep]" # DeepPTR (PyTorch)\n'
'pip install ".[dev]" # pytest for testing'
'
'
'
Requirements
'
'
'
'Python ≥ 3.9, anndata ≥ 0.8, scanpy ≥ 1.9, numpy ≥ 1.21, scipy ≥ 1.7, '
'scikit-learn ≥ 1.0, numba ≥ 0.55, matplotlib ≥ 3.5'
'
'
'
',
unsafe_allow_html=True,
)
st.markdown(
''
'
Data preparation
'
'
'
'scPTR requires raw, un-normalized spliced and unspliced counts '
'in an AnnData .h5ad file. Tools for generating these:'
'
'
'
'
'| Tool | Notes |
'
''
'| STARsolo | Produces spliced/unspliced with --soloFeatures SJ Gene Velocyto |
'
'| Alevin-fry | Use splici index; outputs spliced + unspliced per cell |
'
'| velocyto | Run on BAM files post-alignment; outputs loom → convert to h5ad |
'
'| kallisto|bustools | Use kb-python with --workflow lamanno |
'
'
'
'
Input data requirements
'
'
'
'scPTR requires raw (un-normalized) counts in both layers. '
'Do not pre-normalize with Seurat, Scanpy, or other pipelines — '
'scPTR performs its own library-size normalization internally. '
'STARsolo and Alevin-fry output is already raw; velocyto loom files are also raw.'
'
'
'
Verify your data has required layers
'
'
'
'import anndata as ad\n'
'adata = ad.read_h5ad("your_data.h5ad")\n'
'print(list(adata.layers.keys())) # must include "spliced" and "unspliced"\n'
'print(adata.shape) # (n_cells, n_genes)\n'
'# Check counts are raw (integers)\n'
'import numpy as np\n'
'print(np.allclose(adata.layers["spliced"] % 1, 0)) # True = raw counts'
'
'
'
',
unsafe_allow_html=True,
)
# ── Troubleshooting ───────────────────────────────────────────────────────
with dtab5:
issues = [
("Missing spliced/unspliced layers",
"Error: 'spliced' not in adata.layers",
"Your file lacks the required layers. Re-run alignment with STARsolo "
"(--soloFeatures Velocyto), velocyto, or Alevin-fry with a splici index."),
("All γ values are zero",
"Gamma layer exists but all values are 0",
"This happens when Ms (smoothed spliced) is below the min_spliced threshold everywhere. "
"Try reducing Min smoothed spliced (Ms) to 0.001 in step 3, or check that normalization ran correctly."),
("Very few genes after filtering",
"n_vars drops to < 100 after preprocessing",
"Lower Min total unspliced counts or Min cells with nonzero unspliced in step 2. "
"Some datasets have sparse unspliced counts — try 5 and 3 respectively."),
("PT states = 1 (all cells in one cluster)",
"Only 1 Leiden cluster found",
"Increase the Leiden resolution (try 1.0–2.0). Also check that the γ matrix has variance — "
"if most values are 0, the clustering will be uninformative."),
("Network inference is slow",
"Elastic net taking > 10 minutes",
"Check 'Restrict regulators to known RBPs' to reduce the feature matrix from all genes "
"to ~200 curated RBPs. Also reduce Top edges per target to 20–30."),
("Dataset download fails",
"pooch.HTTPError or FileNotFoundError for example datasets",
"Ensure pip install \"scptr[datasets]\" is installed and you have an internet connection. "
"The pancreas dataset is ~30 MB and dentate gyrus ~25 MB."),
("Memory error on large dataset",
"MemoryError or kernel crash",
"The γ matrix (cells × genes) can be large. Try filtering more aggressively in step 2 "
"(higher min counts). For >20,000 cells, consider subsetting to highly variable genes first."),
("Phase portrait shows no clear line",
"β estimates are noisy / R² is very low",
"This is normal for some genes. Raise the Phase portrait quantile to 0.97–0.99 "
"to better capture the kinetic upper boundary. Genes with very low counts will always have noisy portraits."),
]
for title, symptom, fix in issues:
st.markdown(
f''
f'
{title}
'
f'
Symptom
'
f'
{symptom}
'
f'
Fix
'
f'
{fix}
'
f'
',
unsafe_allow_html=True,
)
# ── Citation ──────────────────────────────────────────────────────────────
with dtab6:
st.markdown(
''
'
Citing scPTR
'
'
'
'If you use scPTR in your research, please cite:'
'
'
'
'
'Bryan Cheng*, Austin Jin*\n'
'scPTR: Decomposing Post-Transcriptional Regulation at Single-Cell Resolution\n'
'(2026)'
'
'
'
BibTeX
'
'
'
'@article{cheng2026scptr,\n'
' title = {scPTR: Decomposing Post-Transcriptional Regulation\n'
' at Single-Cell Resolution},\n'
' author = {Cheng, Bryan and Jin, Austin},\n'
' year = {2026},\n'
'}'
'
'
'
',
unsafe_allow_html=True,
)
st.markdown(
''
'
Dependencies to cite
'
'
'
'scPTR builds on these foundational tools — please also cite them as appropriate:'
'
'
'
'
'| Tool | Use in scPTR | Reference |
'
''
'| scanpy | PCA, neighbors, UMAP, Leiden clustering | '
'Wolf et al., Genome Biology 2018 |
'
'| anndata | Core data structure | '
'Virshup et al., Nat Methods 2024 |
'
'| scikit-learn | Elastic net regression (network inference) | '
'Pedregosa et al., JMLR 2011 |
'
'| scVelo | Steady-state kinetic model inspiration | '
'Bergen et al., Nat Biotechnol 2020 |
'
'
'
'
',
unsafe_allow_html=True,
)