Single-cell trajectory inference for detecting transient events in biological processes.
The 10 matches
- [1] § Methods › Cell cycle ↔ cellcycle.ipynb, lines 112–186 · score 0.90 · n_neighbors, n_pcs, score_genes_cell_cycle, Scanpy, ARPACK, PCA
- [2] § Methods › Comparison against other methods › tradeSeq ↔ method_evaluations/method_eval.py, lines 138–188 · score 0.83 · associationTest, cellWeights, evaluateK, tradeSeq, eigen, Signal genes
- [3] § Results › Induced neuron dataset ↔ sctransient_ineuron.ipynb, lines 775–886 · score 0.72 · cumulative recovery, TES ranked, pathway leading, diagonal, GSEA, fraction
- [4] § Results › Cell cycle dataset ↔ cellcycle.ipynb, lines 724–798 · score 0.69 · Leiden clustering, cell cycle phase, Scanpy, 1–3, G2, G1
- [5] § Methods › Synthetic data parameters ↔ method_evaluations/method_execution.py, lines 27–116 · score 0.61 · noise genes, Signal genes, Autocorrelation, uniform, amplitude, density
- [6] § Methods › Synthetic data parameters ↔ method_evaluations/params.py, lines 10–28 · score 0.61 · noise genes, Signal genes, Autocorrelation, uniform, amplitude, density
- [7] § Methods › Transient-event score ↔ cellcycle.ipynb, lines 112–186 · score 0.60 · wavelet transform, scoring genes, pseudotime signal, modified, Gene expression, transient
- [8] § Results › Comparison with other methods ↔ method_evaluations/method_exectime_plot.ipynb, lines 93–111 · score 0.53 · GPfates, tradeSeq, scTransient, execution, log
- [9] § Methods › Comparison against other methods ↔ method_evaluations/method_execution.py, lines 27–116 · score 0.51 · signal genes, amplitudes, GPfates, widths, noise, Gaussian
- [10] § Results › Cell cycle dataset ↔ cellcycle.ipynb, lines 724–798 · score 0.50 · Cell cycle phase, UMAP, Leiden, G2, G1, Clusters
Paper
Loaded from Europe PMC by your browser, not stored by OSCR: doi.org · Europe PMC
The paper is loaded when this pane is shown.
The authors' code
Jupyter notebook · 878 lines · 30 KB · no license · 4 matches
- # %% [markdown]
- # # Cell cycle dataset
- #
- # This notebook is part of the paper titled, "Single-Cell Trajectory Inference for Detecting Transient Events in Biological Processes" by Hutton and Meyer. The data is from the 2025 Bubis et al. paper titled, "[Challenging the Astral mass analyzer to quantify up to 5,300 proteins per single cell at unseen accuracy to uncover cellular heterogeneity](https://doi.org/10.1038/s41592-024-02559-1)".
- # %%
- import numpy as np
- import pandas as pd
- from importlib import reload
- from matplotlib import pyplot as plt
- import scanpy as sc
- import anndata as ad
- import pypsupertime
- from pypsupertime import Psupertime
- from typing import Union
- from anndata import AnnData
- import os
- import pickle as pkl
- from datetime import datetime
- date_str = datetime.now().strftime("%Y_%m_%d")
- r_dir = f"{date_str}_cellcycle_unsup"
- if not os.path.exists(r_dir):
- os.mkdir(r_dir)
- # %%
- import scTransient
- from scTransient.windowing import Window
- from scTransient.wavelets import get_scored_wavelet_across_sigs, WaveletTransform
- from scTransient.metrics import modified_z_score
- # %%
- def load_astral(filepath: str = "astral-scp-report.pg_matrix.tsv"):
- df = pd.read_csv(filepath, index_col=2, sep='\t')
- df = df.iloc[:, 3:] # Drop the first three columns
- # Check the structure of the AnnData object
- df.fillna(0, inplace=True)
- return sc.AnnData(df.T)
- # %%
- def _normalize_to_endtime(x):
- return (x - np.min(x)) / (np.max(x) - np.min(x))
- def window_trajectory(adata: AnnData,
- trajectory: list,
- normalize_to_endtime: bool = True,
- window: Union[str] = "gaussian",
- window_params: dict = None,
- pseudotime_col: str = "dpt_pseudotime",
- node_col: str = "leiden",
- exclude_minimum: bool = False,
- exclude_ends: int = None):
- # initialize window
- window = _init_window(window, window_params)
- # Get pseudotime positions; limit to nodes in trajectory
- if trajectory is not None:
- retain_idx = adata.obs[node_col].isin(trajectory)
- else:
- retain_idx = np.ones(adata.shape[0], dtype=bool)
- pseudotime = adata.obs.loc[retain_idx, pseudotime_col]
- if normalize_to_endtime:
- pseudotime = _normalize_to_endtime(pseudotime)
- # print(sum(retain_idx))
- if exclude_ends is None:
- return window.apply(positions=pseudotime,
- values=adata.X[retain_idx, :],
- exclude_minimum=exclude_minimum)
- pseudotime_signals = window.apply(positions=pseudotime,
- values=adata.X[retain_idx, :],
- exclude_minimum=exclude_minimum)
- return pseudotime_signals[exclude_ends:-exclude_ends, :]
- def _init_window(window: Union[str, Window],
- window_params: dict = None):
- if issubclass(window.__class__, str):
- if window.lower() == "gaussian":
- if window_params is None:
- window_params = {"n_windows": 25, "sigma": 0.2}
- window = GaussianWindow(**window_params)
- elif window.lower() == "rect":
- if window_params is None:
- window_params = {"n_windows": 25, "width": 0.1}
- window = RectWindow(**window_params)
- else:
- raise ValueError(f"Unrecognized window type: {window}")
- return window
- def std_from_median(coefs):
- """Compute the number of standard deviations from the median of the wavelet coefficients."""
- s = np.std(coefs)
- if s > 0:
- return (coefs - np.median(coefs)) / s
- else:
- return None
- def modified_z_score_with_scaletime(coefs, get_st: bool = False):
- zmod = std_from_median(coefs)
- if zmod is None:
- if not get_st:
- return 0
- else:
- return 0, [None, None]
- else:
- scale, time = np.unravel_index(np.argmax(zmod), zmod.shape)
- if not get_st:
- return np.abs(coefs[scale,time] * zmod[scale,time])
- else:
- return np.abs(coefs[scale,time] * zmod[scale,time]), [scale, time]
- # %%
- def pipeline_astral_cellcycle(data_loader,
- window=None,
- window_params: dict = None,
- trajectory: list = None,
- scoring_threshold: float = 1,
- exclude_pt_ends: tuple = (0.05, 0.95),
- repeat: bool = False,
- save_name: str = None,
- coverage_threshold: float = 0.0,
- ) -> sc.AnnData:
- if save_name is not None:
- if os.path.exists(save_name) and not repeat:
- adata = sc.read_h5ad(save_name)
- else:
- adata = data_loader()
- print("Preprocessing...")
- sc.pp.filter_cells(adata, min_genes=2000, inplace=True)
- sc.pp.filter_genes(adata, min_cells=3, inplace=True)
- sc.pp.normalize_total(adata, inplace=True, target_sum=1e4)
- sc.pp.log1p(adata)
- sc.pp.regress_out(adata, ['n_genes'])
- sc.pp.scale(adata, max_value=10)
- sc.pp.pca(adata, svd_solver="arpack")
- sc.pp.neighbors(adata, n_neighbors=10, n_pcs=40)
- sc.tl.leiden(adata, resolution=1)
- print("Computing pseudotime...")
- f = open("regev_lab_cell_cycle_genes.txt", "r")
- cell_cycle_genes = [x.strip() for x in f]
- f.close()
- s_genes = cell_cycle_genes[:43]
- g2m_genes = cell_cycle_genes[43:]
- cell_cycle_genes = [x for x in cell_cycle_genes if x in adata.var_names]
- sc.tl.score_genes_cell_cycle(adata, s_genes=s_genes, g2m_genes=g2m_genes)
- phase_order = {'G1': 1, 'S': 2, 'G2M': 3}
- # phase_order = {"G1": 1, "S": 3, "G2M": 2}
- adata.obs['phase_ordinal'] = adata.obs['phase'].map(phase_order)
- psuper = Psupertime()
- # Fit the model
- psuper.run(adata, 'phase_ordinal')
- # psuper.plot_labels_over_psupertime(adata, "phase_ordinal")
- psuper.predict_psuper(adata)
- if save_name is not None:
- adata.write_h5ad(save_name)
- print("Computing gene expression along pseudotime...")
- # Do windowing
- if window is None:
- if window_params is None:
- window_params = {"n_windows": 30, "sigma": 0.03, "max_distance": 0.1}
- window = scTransient.windowing.ConfinedGaussianWindow(**window_params)
- n_windows = window.n_windows
- qmin = adata.obs['psupertime'].quantile(exclude_pt_ends[0])
- qmax = adata.obs['psupertime'].quantile(exclude_pt_ends[1])
- adata = adata[(adata.obs["psupertime"] > qmin) & (adata.obs["psupertime"] < qmax), :].copy()
- if trajectory is None: # take all
- node_col = "phase"
- path = list(np.unique(adata.obs[node_col]))
- pseudotime_signals_array = window_trajectory(adata,
- trajectory=path,
- node_col=node_col,
- window=window,
- pseudotime_col='psupertime',
- exclude_minimum=False)
- pseudotime_signals_dict = {}
- for idx, g in enumerate(adata.var_names):
- pseudotime_signals_dict[g] = pseudotime_signals_array[:, idx]
- wt = WaveletTransform(scales=np.arange(1, 5), wavelet="mexh")
- waves, scores = get_scored_wavelet_across_sigs(pseudotime_signals_dict,
- wt,
- modified_z_score_with_scaletime,
- score_threshold=scoring_threshold,
- normalize_signal=False)
- return waves, scores, pseudotime_signals_dict, adata, psuper
- # %%
- # %%
- thresh = 4
- window_params = {"n_windows": 30, "sigma": 0.03, "max_distance": 0.11}
- wr, scoresr, psdr, adata, psuper = pipeline_astral_cellcycle(load_astral,
- window_params=window_params,
- scoring_threshold=thresh,
- coverage_threshold=0.0,
- save_name=None,
- exclude_pt_ends=(0.1,0.9),
- repeat=True)
- # %%
- gene_df = adata.to_df()
- # %%
- wt = scTransient.wavelets.WaveletTransform(scales=np.arange(1, 5), wavelet="mexh")
- # %%
- tes, p, tes_all = scTransient.utils.permutation_dist(gene_df,
- adata.obs["psupertime"],
- wavelet_transform=wt,
- n_permutations=2)
- # %%
- # %%
- tes_np = np.array(tes_all)
- tes_vals = np.where(tes > 10)[0]
- tes_sig = np.where(p < 0.05)[0]
- # %%
- # %%
- olap = set(tes_vals).intersection(tes_sig)
- # %%
- # %%
- g = adata.var_names
- for i in tes_sig:
- print(g[i])
- # %%
- # %%
- # f = open("tes_all.pkl", "wb")
- # pkl.dump(tes_all, f)
- # f.close()
- # %%
- p_vals = np.zeros(adata.shape[1])
- for i in range(adata.shape[1]):
- p_vals[i] = np.sum(tes[i] < tes_np[:,i]) / tes_np.shape[0]
- # %%
- p_vals
- # %%
- # %%
- v, bins, _ = plt.hist(p_vals, bins=100, density=True);
- plt.xlabel("p-value")
- plt.ylabel("Prob dens.")
- plt.title("Distribution of p-values across gene TES")
- # %%
- sig = np.where(p_vals < 0.01)[0]
- # %%
- tes_max = tes.copy()
- ss = np.argsort(tes_max)
- # %%
- olap = set(sig).intersection(ss[-16:])
- # %%
- olap
- # %%
- num_bins = 20
- # Compute bin edges and assign bins
- adata.obs['psupertime_bin'], bin_edges = pd.qcut(adata.obs['psupertime'], q=num_bins, labels=False, retbins=True)
- # compute bin midpoints for correct x-axis scaling
- bin_midpoints = (bin_edges[:-1] + bin_edges[1:]) / 2
- phase_proportions = adata.obs.groupby(['psupertime_bin', 'phase']).size().unstack(fill_value=0)
- phase_proportions = phase_proportions.div(phase_proportions.sum(axis=1), axis=0)
- # for use in large figure at end of notebook
- fig9_x = bin_midpoints
- fig9_y = phase_proportions.T.values
- fig9_labels=phase_proportions.columns
- # Replot with original psupertime values on x-axis
- plt.figure(figsize=(8, 5))
- plt.stackplot(bin_midpoints, phase_proportions.T.values, labels=phase_proportions.columns, alpha=0.8)
- # Formatting
- plt.xlabel("Psupertime") # Change x-axis label
- plt.ylabel("Proportion of Cells")
- plt.title("Stacked Cell Cycle Phase Proportions Across Psupertime")
- plt.legend(title="Phase", bbox_to_anchor=(1.05, 1), loc='upper left')
- plt.grid(False)
- # %%
- phase_proportions
- # %%
- last_g1_idx = np.where(phase_proportions["G1"] <= 0.5)[0][0] # 5
- last_s_idx = np.where(phase_proportions["S"][last_g1_idx+1:] <= 0.5)[0][0] + last_g1_idx # 11
- last_g1_idx /= phase_proportions.shape[0] # get fraction along pt (this is bad variable naming, I know)
- last_s_idx /= phase_proportions.shape[0] # get fraction along pt
- pt_min = 0
- pt_max = 29
- last_g1 = (pt_max - pt_min) * last_g1_idx + pt_min
- last_s = (pt_max-pt_min) * last_s_idx + pt_min
- # %%
- adata.obs["phase"].value_counts()
- # %%
- thresh = 7
- g_above_thresh = [k for k, v in scoresr.items() if v > thresh]
- print(len(g_above_thresh))
- # %%
- thresh = 7
- g_above_thresh = [k for k, v in scoresr.items() if v > thresh]
- print(len(g_above_thresh))
- pt_above_thresh = []
- for g in g_above_thresh:
- pt_above_thresh.append(psdr[g])
- # %%
- all_scores = list(scoresr.values())
- plt.hist(all_scores, bins=500);
- plt.xlabel("Score")
- plt.ylabel("Frequency")
- plt.title("Score distribution for genes in cell cycle dataset")
- # %%
- import matplotlib.pyplot as plt
- from sklearn.cluster import KMeans
- from sklearn.metrics import silhouette_score
- import numpy as np
- from collections import defaultdict as dd
- kmeans = KMeans(n_clusters=5, random_state=0)
- labels = kmeans.fit_predict(pt_above_thresh)
- # %%
- c = dd(list)
- for idx_g, g in enumerate(g_above_thresh):
- c[labels[idx_g]].append(g)
- # %%
- for idx in range(5):
- fig, ax = plt.subplots()
- for g in c[idx]:
- ax.plot(psdr[g])
- ax.axvline(last_g1, linestyle="--")
- ax.axvline(last_s, linestyle="--")
- ax.set_title(f"Cluster {idx}")
- ax.set_xticks([5,15,25])
- ax.set_xticklabels(["G1", "S", "G2M"])
- fig.savefig(f"{r_dir}/cluster_{idx}.png")
- # %%
- # write out genes in each cluster
- # for idx in range(5):
- # f = open(f"{r_dir}/genes_group_{idx}.txt", "w")
- # for g in c[idx]:
- # f.write(f"{g}\n")
- # f.close()
- # %%
- ## For writing out all genes
- # f = open(f"{r_dir}/astral_genes.txt", "w")
- # for g in g_above_thresh:
- # print(g)
- # f.write(f"{g}\n")
- # f.close()
- # %%
- # Compute G1 and S to be in PT instead of by index
- last_g1_idx = np.where(phase_proportions["G1"] <= 0.5)[0][0] # 5
- last_s_idx = np.where(phase_proportions["S"][last_g1_idx+1:] <= 0.5)[0][0] + last_g1_idx # 11
- last_g1_idx /= phase_proportions.shape[0] # get fraction along pt
- last_s_idx /= phase_proportions.shape[0] # get fraction along pt
- pt_min = np.min(adata.obs["psupertime"])
- pt_max = np.max(adata.obs["psupertime"])
- last_g1_pt = (pt_max - pt_min) * last_g1_idx + pt_min
- last_s_pt = (pt_max-pt_min) * last_s_idx + pt_min
- # %%
- g = "AK6"
- x = np.linspace(np.min(adata.obs["psupertime"]), np.max(adata.obs["psupertime"]), len(psdr[g]))
- plt.plot(x, psdr[g])
- plt.plot(adata.obs["psupertime"], adata[:, "AK6"].X[:, 0], ".")
- plt.axvline(last_g1_pt, linestyle=":", label="Transition to S")
- plt.axvline(last_s_pt, linestyle="--", label="Transition to G2/M")
- plt.legend()
- plt.title(f"{g} expression along pseudotime")
- plt.xlabel("Pseudotime")
- plt.ylabel("Gene expression")
- plt.savefig(f"{r_dir}/{g}_expression.png")
- # %%
- g = "ATL2"
- x = np.linspace(np.min(adata.obs["psupertime"]), np.max(adata.obs["psupertime"]), len(psdr[g]))
- plt.plot(x, psdr[g])
- plt.plot(adata.obs["psupertime"], adata[:, g].X[:, 0], ".")
- plt.axvline((pt_max - pt_min)*5/20 + pt_min, linestyle=":", label="Transition to S")
- plt.axvline((pt_max-pt_min)*11/20 + pt_min, linestyle="--", label="Transition to G2/M")
- plt.legend()
- plt.title(f"{g} expression along pseudotime")
- plt.xlabel("Pseudotime")
- plt.ylabel("Gene expression")
- plt.savefig(f"{r_dir}/{g}_expression.png")
- # %% [markdown]
- # # Known cell cycle markers
- # %%
- f = open('regev_lab_cell_cycle_genes.txt', "r")
- cell_cycle_genes = [x.strip() for x in f]
- f.close()
- s_genes = cell_cycle_genes[:43]
- g2m_genes = cell_cycle_genes[43:]
- cell_cycle_genes = [x for x in cell_cycle_genes if x in adata.var_names]
- # %%
- # %%
- # For some reason, some of the adata.var_names can be NaN
- idx_list = []
- for idx, v in enumerate(adata.var_names):
- if isinstance(v, float):
- idx_list.append(idx)
- if len(idx_list) > 0:
- buf = list(adata.var_names)
- for idx in idx_list:
- buf[idx] = ""
- adata.var_names = buf
- # %%
- # which S genes are in our data?
- s_in_data = set([s.lower() for s in s_genes]).intersection(set([v.lower() for v in adata.var_names]))
- s_in_data = [s.upper() for s in s_in_data]
- s_in_data.sort()
- # which g2 genes are in our data?
- g2_in_data = set([s.lower() for s in g2m_genes]).intersection(set([v.lower() for v in adata.var_names]))
- g2_in_data = [s.upper() for s in g2_in_data]
- g2_in_data.sort()
- # %%
- print(f"Number of S-related genes in the dataset: {len(s_in_data)}")
- # %%
- print(f"Number of G2-related genes in the dataset: {len(g2_in_data)}")
- # %%
- fig, axs = plt.subplots(8,3)
- fig.set_figheight(12)
- fig.set_figwidth(8)
- for idx, g in enumerate(s_in_data):
- i, j = np.unravel_index(idx, axs.shape)
- ax = axs[i,j]
- x = np.linspace(np.min(adata.obs["psupertime"]), np.max(adata.obs["psupertime"]), len(psdr[g]))
- ax.plot(x, psdr[g], label="Windowed signal")
- ax.plot(adata.obs["psupertime"], adata[:, g].X[:, 0], ".", label="Cell data")
- ax.axvline((pt_max - pt_min)*5/20 + pt_min, linestyle=":", label="Transition to S")
- ax.axvline((pt_max-pt_min)*11/20 + pt_min, linestyle="--", label="Transition to G2/M")
- # ax.legend()
- ax.set_title(f"{g}")
- # ax.set_xlabel("Pseudotime")
- # ax.set_ylabel("Gene expression")
- if idx == 11:
- ax.legend(bbox_to_anchor=(1,1))
- fig.tight_layout(rect=[0, 0.03, 1, 0.95])
- fig.suptitle("S genes along pseudotime")
- # plt.savefig(f"{r_dir}/s_gene_expression.png")
- # %%
- num_plots = len(g2_in_data)
- num_columns = 3
- num_rows = num_plots // num_columns
- if num_plots % num_columns != 0:
- num_rows += 1
- fig, axs = plt.subplots(num_rows, num_columns)
- fig.set_figheight(4/3*num_rows)
- fig.set_figwidth(8)
- for idx, g in enumerate(g2_in_data):
- i, j = np.unravel_index(idx, axs.shape)
- ax = axs[i,j]
- x = np.linspace(np.min(adata.obs["psupertime"]), np.max(adata.obs["psupertime"]), len(psdr[g]))
- ax.plot(x, psdr[g], label="Windowed signal")
- ax.plot(adata.obs["psupertime"], adata[:, g].X[:, 0], ".", label="Cell data")
- ax.axvline((pt_max - pt_min)*5/20 + pt_min, linestyle=":", label="Transition to S")
- ax.axvline((pt_max-pt_min)*11/20 + pt_min, linestyle="--", label="Transition to G2/M")
- # ax.legend()
- ax.set_title(f"{g}")
- # ax.set_xlabel("Pseudotime")
- # ax.set_ylabel("Gene expression")
- if idx == 11:
- ax.legend(bbox_to_anchor=(1,1))
- fig.tight_layout(rect=[0, 0.03, 1, 0.95])
- fig.suptitle("G2M genes along pseudotime")
- # plt.savefig(f"{r_dir}/g2m_gene_expression.png")
- # %%
- from gprofiler import GProfiler
- for idx in range(4):
- gp = GProfiler(return_dataframe=True)
- results = gp.profile(organism="hsapiens", query=c[idx], sources=['GO:BP', 'GO:MF', 'GO:CC'])
- results.sort_values(by="p_value", ascending=True)
- sig_res = results[results["p_value"] < 0.05]
- break
- sig_res[["source", "native", "name", "p_value", "intersection_size"]].to_csv(f"{r_dir}/astral_enrichment_cluster{idx}.csv")
- # %%
- def plot_df(df: pd.DataFrame, title: str = None, save=None, ax=None, pmin=None, pmax=None, sources=None, annotated_names: list[str] = None
- ) -> None:
- """
- Plots each row of the DataFrame as a circle grouped by the 'source' column.
- The horizontal axis displays -log10(p_value) and the vertical positions
- are arranged based on the source group with added jitter.
- A legend is added for both the source groups and the circle size scale (intersection_size).
- Parameters:
- df (pd.DataFrame): A DataFrame containing the columns:
- - 'source': categorical column with 3 categories.
- - 'p_value': continuous values.
- - 'intersection_size': integers (will be used to scale circle sizes).
- - 'name': a descriptor for the row (unused in the plot).
- """
- # Compute the horizontal position: -log10(p_value)
- # (Make sure there are no p_value values equal to 0)
- df = df.copy() # Avoid modifying the original DataFrame
- fontsize=16
- if ax is None:
- fig, ax = plt.subplots()
- if (df["p_value"] <= 0).any():
- raise ValueError("All p_value entries must be positive so that -log10 can be computed.")
- df["neg_log10"] = -np.log10(df["p_value"])
- # Create a mapping for each unique source to a base y-position.
- if sources is None:
- unique_sources = sorted(df["source"].unique())
- else:
- unique_sources = sorted(np.unique(sources))
- source_to_index = {source: idx for idx, source in enumerate(unique_sources, start=1)}
- # Map sources to base y positions.
- df["base_y"] = df["source"].map(source_to_index)
- # Add vertical jitter to separate the circles
- np.random.seed(0) # For reproducibility
- jitter = np.random.uniform(-0.2, 0.2, size=len(df))
- df["y_pos"] = df["base_y"] + jitter
- # Create the plot
- # Plot each group with its own color and label.
- for source in unique_sources:
- subset = df[df["source"] == source]
- ax.scatter(
- subset["neg_log10"],
- subset["y_pos"],
- s=subset["intersection_size"] * 10, # Scale circle sizes; adjust factor as needed.
- alpha=0.7,
- label=source, # This will be used in the legend for sources.
- edgecolors="w"
- )
- ax.set_xlabel("-log10(p_value)", fontsize=fontsize)
- ax.set_yticks(list(source_to_index.values()), list(source_to_index.keys()), fontsize=fontsize)
- ax.set_ylim([0,4])
- # plt.ylabel("Source Group")
- if title is None:
- ax.set_title("Function Enrichment Analysis", fontsize=fontsize)
- else:
- ax.set_title(title, fontsize=fontsize)
- # First, add the legend for the source groups.
- # source_legend = plt.legend(title="Source", loc="upper right")
- # plt.gca().add_artist(source_legend)
- # Now, create a legend for the circle sizes corresponding to 'intersection_size'.
- # Use three representative sizes: min, median, and max.
- size_min = df["intersection_size"].min()
- # size_median = int(df["intersection_size"].median())
- size_max = df["intersection_size"].max()
- size_median = int((size_min + size_max)/2) #int(df["intersection_size"].median())
- size_scale = 10 # This is the factor applied to intersection_size for the marker size
- sizes = [size_min, size_median, size_max]
- markers = [
- ax.scatter([], [], s=size * size_scale, color="gray", alpha=0.7, edgecolors="w")
- for size in sizes
- ]
- labels = [f"{size}" for size in sizes]
- if annotated_names:
- # You could adjust the base offsets for arrow text.
- offset_x = 0.5
- offset_y = 0.5
- for i, row in df.iterrows():
- if row["name"] in annotated_names:
- x_point = row["neg_log10"]
- y_point = row["y_pos"]
- x_text = x_point + offset_x
- y_text = y_point + offset_y
- ax.annotate(
- row["name"],
- xy=(x_point, y_point),
- xytext=(x_text, y_text),
- arrowprops=dict(facecolor="black", arrowstyle="->"),
- fontsize=10,
- bbox=dict(boxstyle="round,pad=0.3", fc="yellow", alpha=0.5)
- )
- ax.legend(markers, labels, title="Intersection Size", bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0)
- ax.grid()
- if pmin is not None and pmax is not None:
- ax.set_xlim([pmin, pmax])
- plt.tight_layout()
- if save is not None:
- plt.savefig(save)
- # %%
- results = []
- sources=['GO:BP', 'GO:MF', 'GO:CC']
- for idx in range(5):
- gp = GProfiler(return_dataframe=True)
- results.append(gp.profile(organism="hsapiens", query=c[idx], sources=sources))
- results[-1].sort_values(by="p_value", ascending=True)
- sig_res = results[-1][results[-1]["p_value"] < 0.05]
- # break
- if sig_res.shape[0] == 0:
- continue
- sig_res[["source", "native", "name", "p_value", "intersection_size"]].to_csv(f"paper_figures/astral_enrichment_cluster{idx}.csv")
- # %%
- # %%
- fig, axs = plt.subplots(3)
- fig.set_figheight(8)
- fig_idx = 0
- fontsize=16
- p_min = np.inf
- p_max = -np.inf
- annot_lists = []
- annot_lists.append(["fatty acid catabolic process", "phagocytic vesicle membrane"])
- annot_lists.append(["DNA replication", "nuclear chromosome"])
- annot_lists.append(["N-acylsphingosine amidohydrolase activity", "tertiary granule lumen"])
- for r2 in results:
- r = r2[r2["p_value"] < 0.05]
- if r.shape[0] == 0:
- continue
- mmin = np.min(r["p_value"])
- mmax = np.max(r["p_value"])
- p_min = np.min([mmin, p_min])
- p_max = np.max([mmax, p_max])
- p_min *= 0.8
- p_max *= 1.3
- for idx in range(3):
- # gp = GProfiler(return_dataframe=True)
- # results = gp.profile(organism="hsapiens", query=c[idx], sources=['GO:BP', 'GO:MF', 'GO:CC'])
- # results.sort_values(by="p_value", ascending=True)
- sig_res = results[idx][results[idx]["p_value"] < 0.05]
- # break
- if sig_res.shape[0] == 0:
- continue
- # sig_res[["source", "native", "name", "p_value", "intersection_size"]].to_csv(f"paper_figures/astral_enrichment_cluster{idx}.csv")
- plot_df(sig_res, title=f"Enrichment for Cluster {idx}", ax=axs[fig_idx], pmin = -np.log10(p_max), pmax=-np.log10(p_min), sources=sources, annotated_names=annot_lists[idx])
- # break
- fig_idx += 1
- # print(results)
- plt.savefig(f"{r_dir}/fig9_cellcycle_enrichment.png")
- plt.savefig(f"{r_dir}/fig9_cellcycle_enrichment.svg")
- # %% [markdown]
- # # Figure assembly
- # %%
- import matplotlib.gridspec as gridspec
- from string import ascii_uppercase
- # %%
- adata
- # %%
- sc.tl.umap(adata)
- sc.pl.umap(adata)
- # %%
- from collections import defaultdict as dd
- adata_pscs = sc.read_h5ad("pscs_cellcycle.h5ad")
- cluster_genes = {}
- pt_signals = dd(list)
- var_list = list(adata_pscs.var_names)
- for idx in range(4):
- cluster_genes[idx] = list(adata_pscs.uns["te_cluster"].loc[(adata_pscs.uns["te_cluster"] == idx).values].index)
- print(len(cluster_genes[idx]))
- for g in cluster_genes[idx]:
- g_idx = var_list.index(g)
- pt_signals[idx].append(adata_pscs.uns["pseudotime_signals"][:, g_idx])
- sc.tl.umap(adata_pscs)
- sc.pl.umap(adata_pscs)
- # %%
- fig = plt.figure(figsize=(10, 12))
- gs = gridspec.GridSpec(4, 2, figure=fig)
- fontsize=16
- ax = fig.add_subplot(gs[1,1])
- psupertime_figure = psuper.plot_identified_gene_coefficients(adata, n_top=10, ax=ax)
- ax.set_title("Genes for psupertime", fontsize=fontsize)
- ax.text(0.05, 0.15, ascii_uppercase[3], transform=ax.transAxes,
- fontsize=16, fontweight='bold', va='top', ha='left')
- ax = fig.add_subplot(gs[2, :])
- # Replot with original psupertime values on x-axis
- ax.stackplot(bin_midpoints, phase_proportions.T.values, labels=phase_proportions.columns, alpha=0.8)
- # Formatting
- ax.set_xlabel("Pseudotime", fontsize=fontsize) # Change x-axis label
- ax.set_ylabel("Proportion of Cells", fontsize=fontsize)
- ax.set_title("Cell Cycle Phase Proportions Across Pseudotime", fontsize=fontsize)
- ax.legend(title="Phase", loc='upper right')
- ax.grid(False)
- ax.set_xlim(bin_midpoints[0], bin_midpoints[-1])
- # Remove all margins from both axes.
- ax.margins(x=0, y=0)
- # Adjust subplot parameters to use all the figure area.
- plt.subplots_adjust(left=0, right=1, top=1, bottom=0)
- ax.text(0.025, 0.95, ascii_uppercase[4], transform=ax.transAxes,
- fontsize=16, fontweight='bold', va='top', ha='left')
- for idx in [1,3]:
- if idx == 1:
- plot_idx = 0
- else:
- plot_idx = 1
- ax = fig.add_subplot(gs[3, plot_idx])
- for ii in range(len(pt_signals[idx])):
- ax.plot(pt_signals[idx][ii])
- ax.axvline(last_g1, linestyle="--")
- ax.axvline(last_s, linestyle="--")
- ax.set_title(f"Cluster {idx}", fontsize=fontsize)
- g1_tick = last_g1/2
- s_tick = (last_s + last_g1)/2
- g2_tick = (len(psdr[g]) + last_s)/2
- ax.set_xticks([g1_tick, s_tick, g2_tick])
- ax.set_xticklabels(["G1", "S", "G2M"], fontsize=fontsize-2)
- ax.set_xlabel("Pseudotime", fontsize=fontsize)
- ax.text(0.05, 0.95, ascii_uppercase[plot_idx+5], transform=ax.transAxes,
- fontsize=16, fontweight='bold', va='top', ha='left')
- ax_sc = fig.add_subplot(gs[0,0])
- sc.pl.umap(adata, color=["leiden"], ax=ax_sc, show=False, s=800)
- ax_sc.set_title("Leiden clusters", fontsize=fontsize)
- ax_sc.text(0.05, 0.95, ascii_uppercase[0], transform=ax_sc.transAxes,
- fontsize=16, fontweight='bold', va='top', ha='left')
- ax_sc = fig.add_subplot(gs[1,0])
- sc.pl.umap(adata, color=["phase"], ax=ax_sc, show=False, s=800)
- ax_sc.set_title("Cell cycle phase", fontsize=fontsize)
- ax_sc.text(0.05, 0.95, ascii_uppercase[2], transform=ax_sc.transAxes,
- fontsize=16, fontweight='bold', va='top', ha='left')
- ax_sc = fig.add_subplot(gs[0,1])
- sc.pl.umap(adata, color=["n_genes"], ax=ax_sc, show=False, s=800)
- ax_sc.text(0.05, 0.95, ascii_uppercase[1], transform=ax_sc.transAxes,
- fontsize=16, fontweight='bold', va='top', ha='left')
- fig.tight_layout()
- plt.savefig(f"{r_dir}/fig7.png")
- plt.savefig(f"{r_dir}/fig7.svg")
- plt.savefig(f"{r_dir}/fig7.eps")
- # %%
- fig, axs = plt.subplots(1,2)
- fig.set_figheight(4)
- fig.set_figwidth(8)
- mmin = np.min(adata.obs["psupertime"])
- mmax = np.max(adata.obs["psupertime"])
- pt = np.linspace(mmin, mmax, len(psdr["PCNA"]))
- last_g1_pt = (mmax-mmin)*last_g1/30 + mmin
- last_s_pt = (mmax-mmin)*last_s/30 + mmin
- for idx, g in enumerate(["PCNA", "UNG"]):
- ax = axs[np.unravel_index(idx, axs.shape)]
- ax.plot(pt, psdr[g])
- ax.plot(adata.obs["psupertime"], adata[:, g].X[:,0], ".")
- ax.axvline(last_g1_pt, linestyle="--")
- ax.axvline(last_s_pt, linestyle="--")
- ax.set_title(f"{g}")
- # ax.set_xlabel("Pseudotime")
- g1_tick = (mmin+last_g1_pt)/2
- s_tick = (last_s_pt + last_g1_pt)/2
- g2_tick = (mmax + last_s_pt)/2
- # ax.set_xticks([5,12,25])
- ax.set_xticks([g1_tick, s_tick, g2_tick])
- ax.set_xticklabels(["G1", "S", "G2M"])
- if idx == 0:
- ax.set_ylabel("Protein Quant.")
- # ax.set_title(f"{g} - {adata[:, g].var['coverage'][g]}")
- fig.tight_layout()
- # fig.savefig(f"{r_dir}/pcna_ung_pseudotimecourses.png")
- # fig.savefig(f"{r_dir}/pcna_ung_pseudotimecourses.svg")
- # %% [markdown]
- # ### Cell cycle genes
- #
- # Since we are using supervised pseudotime to determine cell cycle phase, it is possible that the clusters we are identifying are simply groups of those same genes. This section clusters the pseudotimecourses of those genes and shows that they do not exhibit the same behavior as those identified by scTransient.
- # %%
- from sklearn.cluster import KMeans
- # %%
- cell_cycle_genes_in_data = set(cell_cycle_genes).intersection(set(adata.var_names))
- cell_cycle_genes_in_data = list(cell_cycle_genes_in_data)
- # %%
- psdr_mat = np.zeros((len(cell_cycle_genes_in_data), len(psdr["UNG"])))
- regev_gene_to_idx = {}
- idx_to_regev_gene = {}
- for idx, g in enumerate(cell_cycle_genes_in_data):
- psdr_mat[idx, :] = psdr[g]
- regev_gene_to_idx[g] = idx
- idx_to_regev_gene[idx] = g
- # %%
- k=5
- km = KMeans(n_clusters=k, random_state=42, n_init=10)
- clusters = km.fit_predict(psdr_mat)
- # %%
- genes_per_cluster = dd(list)
- pt_range = np.linspace(mmin, mmax, len(psdr["UNG"]))
- fig, axs = plt.subplots(3,2)
- for idx in range(5):
- ax = axs[np.unravel_index(idx, axs.shape)]
- for gidx, c in enumerate(clusters):
- if c == idx:
- ax.plot(pt_range, psdr_mat[gidx, :])
- genes_per_cluster[idx].append(cell_cycle_genes_in_data[gidx])
- ax.set_title(f"Cluster {idx}")
- ax.axvline(last_g1_pt, linestyle="--")
- ax.axvline(last_s_pt, linestyle="--")
- g1_tick = (mmin+last_g1_pt)/2
- s_tick = (last_s_pt + last_g1_pt)/2
- g2_tick = (mmax + last_s_pt)/2
- ax.set_xticks([g1_tick, s_tick, g2_tick])
- ax.set_xticklabels(["G1", "S", "G2M"])
- fig.tight_layout()
- fig.delaxes(axs[2,1])
- # plt.savefig(f"{r_dir}/clustered_cell_cycle_genes.png")
- # plt.savefig(f"{r_dir}/clustered_cell_cycle_genes.svg")
cellcycle.ipynb at commit 92b95ae, no license · at the source
Overview
Abstract
Transient changes in gene or protein expression often mark the key regulatory checkpoints that propel cells from one functional state to the next, yet they are easy to miss in sparse, noisy single-cell omics data. We introduce scTransient, which transforms single-cell expression profiles into continuous pseudotime signals and uses wavelet-based signal processing to isolate short-lived but biologically meaningful bursts of gene activity. After ordering cells with supervised pseudotime, scTransient windows expression values with supervised pseudotime, applies a continuous wavelet transform, and assigns every gene a transient-event score (TES) that rewards sharp, isolated coefficients while penalizing background fluctuations. Synthetic benchmarks demonstrate that TES robustly recovers transient events (TE) across a wide range of parameters, including cell numbers, signal-to-noise ratios, and event widths. Applying scTransient to two real datasets—induced neuron development and single-cell cell cycle—demonstrates scTransient’s ability to detect TEs along pseudotime and identify proteins known to be related to the biological process under study. These include stem cell regulators in induced neuronal development and S-phase DNA replication factors in A549 cells. By extending trajectory inference from descriptive ordering to quantitative detection of fleeting regulatory programs, scTransient offers a practical route to uncover transient molecular events that drive development, differentiation, and disease.
Reproduced under the paper's license (CC BY-NC), from the paper cited above.
Repository
Its files are read in the Code ↔ Paper reader above, with 10 matches between paragraphs and lines of code.
xomicsdatascience/scTransient_notebooks
92b95ae198e621a450e4acec48aaf2171d37f570, 6 February 2026Availability: 1 check, the latest on 28 September 2026: the link answers
- 28 September 2026: the link answers
8 files
- cellcycle.ipynb, Jupyter, 878 lines, 4 matches
- method_evaluations/
SLURMArrayJobScript.sh , Shell, 29 lines - method_evaluations/
method_eval.py , Python, 437 lines, 1 match - method_evaluations/
method_exectime_plot.ipy , Jupyter, 114 lines, 1 matchnb - method_evaluations/
method_execution.py , Python, 119 lines, 2 matches - method_evaluations/
params.py , Python, 28 lines, 1 match - sctransient_ineuron.ipyn
b , Jupyter, 1,182 lines, 1 match - README.md, Text, 9 lines
The paper's code and data availability statement is in the Data section.
Tracing map
Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.
What the map holds:
- 1 repository of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
- 7 scripts, each with its path and the digest of its content;
- 10 matches between paragraphs of the paper and lines of the code (method lexical-v1);
- neither the text of the paper nor the code itself.
Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.
Data
No dataset and no data link were found in the paper.
Data availability
Datasets were downloaded from external sources: the cell cycle dataset [46] is available through the ProteomeXchange Consortium [20] via PRIDE [21] with ID PXD049412. The iNeuron raw and processed data is available on massive under ID MSV000100760 with DOI: https://
The scTransient code is available from Zenodo and the PSCS [19] interface includes scTransient analysis capabilities. The notebooks for data analysis to produce the figures in this paper are on Zenodo.
Reproduced under the paper's license (CC BY-NC), from the paper cited above.
Versions
The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.
Version 1, 28 September 2026: the first record
Recorded: type, language, journal, volume, issue, pages, dates, 3 authors, 10 MeSH terms, 2 funders, 53 references.
Cite
This paper
Hutton, A., Muñoz-Estrada, J., & Meyer, J. G. (2026). Single-cell trajectory inference for detecting transient events in biological processes. Nucleic acids research, 54(8), gkag368. https://
BibTeX
@article{hutton2026singl
author = {Hutton, Alexandre and Muñoz-Estrada, Jesús and Meyer, Jesse G},
title = {{Single-cell trajectory inference for detecting transient events in biological processes}},
journal = {Nucleic acids research},
year = {2026},
month = apr,
volume = {54},
number = {8},
pages = {gkag368},
publisher = {Oxford University Press},
issn = {0305-1048},
doi = {10.1093/
url = {https://
pmid = {42033223},
pmcid = {PMC13109726}
}
RIS
TY - JOUR
AU - Hutton, Alexandre
AU - Muñoz-Estrada, Jesús
AU - Meyer, Jesse G
TI - Single-cell trajectory inference for detecting transient events in biological processes
T2 - Nucleic acids research
J2 - Nucleic Acids Res
PY - 2026
DA - 2026/
VL - 54
IS - 8
SP - gkag368
SN - 0305-1048
PB - Oxford University Press
DO - 10.1093/
UR - https://
LA - en
ER -
CSL-JSON
{
"id": "10.1093/
"type": "article-journal",
"title": "Single-cell trajectory inference for detecting transient events in biological processes",
"container-title": "Nucleic acids research",
"author": [
{
"family": "Hutton",
"given": "Alexandre"
},
{
"family": "Muñoz-Estrada",
"given": "Jesús"
},
{
"family": "Meyer",
"given": "Jesse G"
}
],
"container-title-short":
"volume": "54",
"issue": "8",
"page": "gkag368",
"DOI": "10.1093/
"PMID": "42033223",
"PMCID": "PMC13109726",
"ISSN": "0305-1048",
"publisher": "Oxford University Press",
"URL": "https://
"language": "en",
"issued": {
"date-parts": [
[
2026,
4,
1
]
]
}
}
The tracing map gets a citation of its own once an author has validated it and it has a DOI.
Similar papers
The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.
- [1] doi:10.1016/j.mcpro.2026.101604 [code]
- Optimizing NGN2 Dosage Enhances the Neuronal Enrichment of iPSC-Derived Neuronal Cultures.Journal: Molecular & cellular proteomics : MCPIn common: anndata, Scanpy, scikit-learn, 4 other tools, genetics / omics, cellular / molecular, 3 references, author Jesse G Meyer
- [2] doi:10.21203/rs.3.rs-9676637/v1 [code]
- A Comprehensive Benchmarking of Spatial Deconvolution and Domain Detection Methods across Diverse Tissues and Spatial Transcriptomic TechnologiesJournal: Research Square (preprint)In common: rpy2, anndata, Scanpy, 5 other tools, genetics / omics, 2 references
- [3] doi:10.1016/j.xcrm.2026.102766 [code]
- A longitudinal single-cell and spatial multiomic atlas of pediatric high-grade glioma.Journal: Cell reports. MedicineIn common: rpy2, anndata, Scanpy, 5 other tools, genetics / omics, cellular / molecular, 1 reference
- [4] doi:10.1038/s41467-026-75722-1 [code]
- Single-nucleus analysis of the adult human olfactory epithelium uncovers shared neurogenesis programs with the brain.Journal: Nature communicationsIn common: anndata, Scanpy, scikit-learn, 4 other tools, genetics / omics, 3 references
- [5] doi:10.1371/journal.pcbi.1014346 [code]
- StPedf: Cell trajectory inference of spatial transcriptomics via spatial proximity embedding and spatial density-adaptive fusion.Journal: PLoS computational biologyIn common: rpy2, anndata, Scanpy, 5 other tools, genetics / omics, 1 reference
- [6] doi:10.1093/bib/bbag298 [code]
- Empowering multifaceted analysis of spatial transcriptomics data with RGAST.Journal: Briefings in bioinformaticsIn common: rpy2, anndata, Scanpy, 5 other tools, genetics / omics, 1 reference
- [7] doi:10.1016/j.stem.2026.05.005 [code]
- Generation of human appetite-regulating neurons and tanycytes from pluripotent stem cells.Journal: Cell stem cellIn common: rpy2, anndata, Scanpy, 5 other tools, cellular / molecular, 1 reference
- [8] doi:10.1002/advs.77003 [code]
- SemanticST: A Scalable Multi-Contextual Graph Learning Framework for Uncovering Spatial Niches and Robust Multi-Sample Integration in Spatial Transcriptomics.Journal: Advanced science (Weinheim, Baden-Wurttemberg, Germany)In common: rpy2, anndata, Scanpy, 5 other tools, genetics / omics, 1 reference
- [9] doi:10.3390/ijms27167275 [code]
- Integrative Multi-Omics Analysis of Multiple Sclerosis Reveals Cell-Type-Specific Regulatory Landscapes and Discordant Methylation-Expression Coupling.Journal: International journal of molecular sciencesIn common: anndata, Scanpy, scikit-learn, 4 other tools, genetics / omics, cellular / molecular, 2 references
- [10] doi:10.1016/j.xgen.2026.101217 [code]
- ProtoCloud: A prototypical self-explaining model for single-cell analysis.Journal: Cell genomicsIn common: anndata, Scanpy, scikit-learn, 4 other tools, genetics / omics, cellular / molecular, 2 references
Contribute
The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.
Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.
Claim this paper
Correct its record
Say what each link of this record is, remove the ones that are not the paper's, add the ones that are missing. The correction becomes a new version of the record, in its Versions section.
Validate its tracing map
You validate the map as this page shows it: 1 repository of the authors' code, each at its verified commit and with its license, 7 scripts, and 10 matches between paragraphs and code (see the Code and Map sections). It then receives a DOI on Zenodo, with you (your ORCID iD) and OSCR as its creators; the code itself is not deposited.
The map's fingerprint: sha256:11fbe9dc0227a6d4…
Add the badge to its README
The badge links the code to this page. Copy one of these into the README of the paper's code: only you decide where it goes, and nothing is changed for you.
Markdown
[, paste the snippet at the top, then “Commit changes…” and, to review it first, “Create a new branch and start a pull request”. You open the pull request; OSCR asks for no permission.
Request its removal
To ask OSCR to remove this record, the copies of its authors' scripts or its tracing map, use the removal request page: signed in, you say who you are, what to remove and why, then review and confirm the request. Published rules decide every request (how).
Discussion, reproductions, activity
Discussion: questions and error reports about this paper and its code, from signed-in readers and its authors. It opens with sign-in.
Reproductions: reports from readers who ran the authors' code: what they reproduced, with which environment, commit and data. It opens with sign-in.
Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.
