[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M76F0545G5V4RP10VPJVA3F4":3,"skill-same:01M76F0545G5V4RP10VPJVA3F4":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M76F0545G5V4RP10VPJVA3F4","trajectory-inference",null,"Trajectory inference and cell fate mapping for single-cell and spatial transcriptomics: PAGA graph + diffusion pseudotime (no velocity needed), scVelo RNA velocity (stochastic \u002F dynamical, from spliced\u002Funspliced counts), CellRank 2 terminal states, fate probabilities and lineage drivers, then pseudotime and fates mapped on tissue with a spatial autocorrelation check. Outputs pseudotime, velocity streams, fate probability tables. Imaging panels (Xenium, MERFISH) have no unspliced counts: use PAGA\u002FDPT or the CellRank pseudotime kernel. For a basic PAGA recipe inside a standard scRNA-seq workflow see scanpy-scrna-seq.","bg-szy\u002FTOP-SKILLS","bg-szy","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F106576190?v=4","01M73A4E8KPV67SFXRY8XZGNBX","ShuZhiyong","01M73A4E96MQ294MHM74TZBVQD",6,"CC-BY-4.0","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fawesome-skills\u002Ftrajectory-inference\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: \"trajectory-inference\"\ndescription: \"Trajectory inference and cell fate mapping for single-cell and spatial transcriptomics: PAGA graph + diffusion pseudotime (no velocity needed), scVelo RNA velocity (stochastic \u002F dynamical, from spliced\u002Funspliced counts), CellRank 2 terminal states, fate probabilities and lineage drivers, then pseudotime and fates mapped on tissue with a spatial autocorrelation check. Outputs pseudotime, velocity streams, fate probability tables. Imaging panels (Xenium, MERFISH) have no unspliced counts: use PAGA\u002FDPT or the CellRank pseudotime kernel. For a basic PAGA recipe inside a standard scRNA-seq workflow see scanpy-scrna-seq.\"\nlicense: \"CC-BY-4.0\"\n---\n\n# Trajectory Inference\n\n## Overview\n\nOrder cells along differentiation or activation paths and estimate where each\ncell is heading. Output: pseudotime, velocity streams, terminal states and\nfate probabilities, and on spatial data their maps on the tissue with a check\nof whether the ordering follows space. Three layers, each optional on top of\nthe previous one:\n\n| Method | Needs | Gives |\n|---|---|---|\n| PAGA + DPT | Clusters, neighbour graph, a chosen root cluster | Cluster connectivity graph, pseudotime |\n| scVelo | `layers[\"spliced\"]` and `layers[\"unspliced\"]` | Direction of change per cell (velocity) |\n| CellRank 2 | A transition kernel (velocity or pseudotime) | Terminal states, fate probabilities, driver genes |\n\nSpliced\u002Funspliced counts come from velocyto, STARsolo (`--soloFeatures Gene\nVelocyto`) or kallisto|bustools run on the reads; for Visium and Slide-seq\nrun them on the Space Ranger \u002F pipeline BAM. Imaging platforms (Xenium,\nMERFISH, CosMx) count probes, not introns, so velocity is not available there.\n\n## When to Use\n\n- Ordering cells along a differentiation or activation path from a chosen start\n- Estimating where cells are heading from spliced\u002Funspliced counts (RNA velocity)\n- Finding terminal states, fate probabilities and the genes driving each fate\n- Checking whether a developmental or activation ordering is laid out in tissue space\n- Finding genes that change along the inferred path\n- Use `scanpy-scrna-seq` instead when you only need a quick PAGA graph inside a standard scRNA-seq workflow\n- For tissue regions rather than cell-state paths, use `spatial-domain-detection`\n\n## Prerequisites\n\n- **Input**: raw counts plus a cluster or cell type column; for velocity, the two layers above\n- **Spatial data**: coordinates in `obsm[\"spatial\"]` for Step 6\n- **Python packages**: `scvelo`, `cellrank` (CellRank 2.x needs Python >= 3.12; CPU is fine)\n\n```bash\n# Install only what `import` reports missing. `--pypi` keeps the env's scanpy\u002Fnumba\n# stack; a conda add can swap it and bare pip can shadow it.\npixi add --pypi scvelo cellrank scanpy\n```\n\n## Workflow\n\n1. Load data and check layers\n2. Preprocess and build the neighbour graph\n3. PAGA and diffusion pseudotime\n4. RNA velocity (scVelo)\n5. Terminal states and fate probabilities (CellRank)\n6. Map pseudotime and fates on the tissue\n\n### Step 1: Load Data\n\n```python\nimport numpy as np\nimport pandas as pd\nimport scanpy as sc\n\nadata = sc.read_h5ad(\"path\u002Fto\u002Fdata.h5ad\")        # your data\n# Demo with spliced\u002Funspliced layers (mouse pancreas endocrinogenesis, downloaded to .\u002Fdata on first use):\n# import scvelo as scv; adata = scv.datasets.pancreas()\nCLUSTER_KEY = \"clusters\"                          # cell type \u002F cluster column\n\nhas_velocity_layers = {\"spliced\", \"unspliced\"} \u003C= set(adata.layers)\nprint(adata)\nprint(f\"velocity layers: {has_velocity_layers}; spatial: {'spatial' in adata.obsm}\")\nprint(adata.obs[CLUSTER_KEY].value_counts())\n```\n\n### Step 2: Preprocess and Neighbour Graph\n\nUses the scVelo order (filter on spliced+unspliced, normalise all layers, then\nlog `X`). Without velocity layers, the scanpy lines alone apply.\n\n```python\nimport scvelo as scv\n\nif has_velocity_layers:\n    scv.pp.filter_genes(adata, min_shared_counts=20)\n    scv.pp.normalize_per_cell(adata)              # normalises X, spliced, unspliced\nelse:\n    adata.layers[\"counts\"] = adata.X.copy()\n    sc.pp.normalize_total(adata)\nsc.pp.log1p(adata)\nsc.pp.highly_variable_genes(adata, n_top_genes=2000)     # imaging panels: skip, use all genes\nsc.pp.pca(adata, n_comps=30)\nsc.pp.neighbors(adata, n_pcs=30, n_neighbors=30, random_state=0)\nif \"X_umap\" not in adata.obsm:\n    sc.tl.umap(adata)\nadata.obs[CLUSTER_KEY] = adata.obs[CLUSTER_KEY].astype(\"category\")\n```\n\n### Step 3: PAGA and Diffusion Pseudotime\n\nThe root cluster is a biological choice (progenitor, naive state); ask the user\nwhen it is not obvious from markers.\n\n```python\nROOT_GROUP = \"Ngn3 low EP\"                        # root cluster name\n\nsc.tl.paga(adata, groups=CLUSTER_KEY)\nsc.pl.paga(adata, threshold=0.05, show=False, save=\"_graph.png\")\ngroups = adata.obs[CLUSTER_KEY].cat.categories\npaga_adj = pd.DataFrame(adata.uns[\"paga\"][\"connectivities\"].toarray(), index=groups, columns=groups)\npaga_adj.to_csv(\"paga_adjacency.csv\")\n\n# Root = the root-cluster cell at the extreme of diffusion component 1\n# (the first cell of the cluster is arbitrary and shifts the whole pseudotime)\nsc.tl.diffmap(adata)\ndc1 = adata.obsm[\"X_diffmap\"][:, 1]\nin_root = (adata.obs[CLUSTER_KEY] == ROOT_GROUP).to_numpy()\nassert in_root.any(), f\"{ROOT_GROUP} not in {list(groups)}\"\nside = np.sign(dc1[in_root].mean() - dc1.mean()) or 1.0\nadata.uns[\"iroot\"] = int(np.flatnonzero(in_root)[np.argmax(side * dc1[in_root])])\nsc.tl.dpt(adata)\nprint(adata.obs.groupby(CLUSTER_KEY, observed=True)[\"dpt_pseudotime\"].median().sort_values())\nsc.pl.umap(adata, color=[CLUSTER_KEY, \"dpt_pseudotime\"], show=False, save=\"_pseudotime.png\")\n```\n\nIf the median pseudotime per cluster does not follow the expected order, the\nroot or the clustering is wrong; DPT is not a test of the order.\n\n### Step 4: RNA Velocity (scVelo)\n\n```python\nMODE = \"stochastic\"                               # \"dynamical\" is slower but gives latent time\n\nscv.pp.moments(adata, n_pcs=None, n_neighbors=None)      # reuses the Step 2 graph\nif MODE == \"dynamical\":\n    scv.tl.recover_dynamics(adata, n_jobs=8)\nscv.tl.velocity(adata, mode=MODE)\nscv.tl.velocity_graph(adata, n_jobs=8)\nscv.tl.velocity_confidence(adata)\nif MODE == \"dynamical\":\n    scv.tl.latent_time(adata)\n\nprint(f\"velocity genes: {int(adata.var['velocity_genes'].sum())}\")\nprint(adata.obs.groupby(CLUSTER_KEY, observed=True)[\"velocity_confidence\"].median().round(2))\nscv.pl.velocity_embedding_stream(adata, basis=\"umap\", color=CLUSTER_KEY, show=False,\n                                 save=\"velocity_stream_umap.png\")\n```\n\nLow `velocity_confidence` (\u003C ~0.5) in a cluster means its arrows are noise;\nsay so rather than interpreting them. Fewer than ~100 velocity genes usually\nmeans too few unspliced reads.\n\n### Step 5: Terminal States and Fate Probabilities (CellRank 2)\n\n```python\nimport cellrank as cr\n\nN_STATES = 8                                      # macrostates; try a few values\nif has_velocity_layers:\n    vk = cr.kernels.VelocityKernel(adata).compute_transition_matrix()\n    ck = cr.kernels.ConnectivityKernel(adata).compute_transition_matrix()\n    kernel = 0.8 * vk + 0.2 * ck                  # connectivity term damps velocity noise\nelse:\n    kernel = cr.kernels.PseudotimeKernel(adata, time_key=\"dpt_pseudotime\").compute_transition_matrix()\n\ng = cr.estimators.GPCCA(kernel)\ng.compute_schur(n_components=20)\ng.compute_macrostates(n_states=N_STATES, cluster_key=CLUSTER_KEY)\ng.predict_terminal_states()                       # or g.set_terminal_states(states=[\"Alpha\", \"Beta\"])\nprint(\"terminal states:\", list(g.terminal_states.cat.categories))\n\ng.compute_fate_probabilities()\nfp = g.fate_probabilities                         # also in adata.obsm[\"lineages_fwd\"]\nfate = pd.DataFrame(np.asarray(fp), index=adata.obs_names, columns=fp.names)\nfate.to_csv(\"fate_probabilities.csv\")\nprint(fate.groupby(adata.obs[CLUSTER_KEY], observed=True).mean().round(2))\n\ndrivers = g.compute_lineage_drivers(cluster_key=CLUSTER_KEY)\ndrivers.to_csv(\"lineage_drivers.csv\")\ng.plot_fate_probabilities(same_plot=False)\nadata.write_h5ad(\"trajectory_result.h5ad\", compression=\"gzip\")\n```\n\nTerminal states (`adata.obs[\"term_states_fwd\"]`) should be clusters the user\nrecognises as end points. If `predict_terminal_states` misses a known end\nstate, change `N_STATES` or set the states by name from `g.macrostates`.\n\n### Step 6: Map Pseudotime and Fates on the Tissue\n\nOn spatial data, check whether the inferred ordering is spatially organised\n(e.g. crypt-to-villus, cortical depth). Moran's I near 0 means the ordering is\nnot reflected in space.\n\n```python\nimport matplotlib.pyplot as plt\nfrom sklearn.neighbors import kneighbors_graph\n\nW = kneighbors_graph(adata.obsm[\"spatial\"], n_neighbors=6, include_self=False)\n\ndef morans_i(v):\n    z = np.asarray(v, float) - np.mean(v)\n    return len(z) \u002F W.sum() * (z @ (W @ z)) \u002F (z @ z)\n\ntracks = {\"dpt_pseudotime\": adata.obs[\"dpt_pseudotime\"].to_numpy()}\nif \"fate\" in globals():\n    tracks.update({f\"fate_{c}\": fate[c].to_numpy() for c in fate.columns})\nfor name, v in tracks.items():\n    adata.obs[name] = v\n    ok = np.isfinite(v)\n    print(f\"{name}: Moran's I = {morans_i(np.where(ok, v, np.nanmean(v[ok]))):.2f}\")\n\naxes = sc.pl.embedding(adata, basis=\"spatial\", color=list(tracks), cmap=\"viridis\", size=1.5, show=False)\nfor ax in np.atleast_1d(axes):\n    ax.invert_yaxis()                             # pixel y grows downwards; drop for micron coordinates\nplt.savefig(\"trajectory_spatial.png\", dpi=150, bbox_inches=\"tight\")\n\nif \"velocity\" in adata.layers:                    # velocity arrows projected onto tissue coordinates\n    adata.obsm[\"X_spatial\"] = adata.obsm[\"spatial\"]\n    scv.pl.velocity_embedding_stream(adata, basis=\"spatial\", color=CLUSTER_KEY, show=False,\n                                     save=\"velocity_stream_spatial.png\")\n```\n\nA velocity stream on tissue coordinates shows transcriptional direction drawn\nin space; it is not physical cell migration.\n\n## Key Parameters\n\n| Parameter | Default | Effect |\n|---|---|---|\n| `ROOT_GROUP` | from the user | Start of pseudotime; flips the whole ordering if wrong |\n| `n_neighbors` (Step 2) | 30 | Graph used by PAGA, DPT, moments and CellRank |\n| `min_shared_counts` | 20 | Gene filter on spliced + unspliced counts |\n| `MODE` | `\"stochastic\"` | `\"dynamical\"` fits per-gene kinetics, adds latent time, ~10x slower |\n| Kernel weights | 0.8 velocity \u002F 0.2 connectivity | More connectivity = smoother, less directional |\n| `N_STATES` | 8 | Macrostates searched for terminal states |\n| PAGA `threshold` | 0.05 | Edges below this connectivity are hidden in the plot |\n\n## Common Recipes\n\n### Recipe: Genes Changing Along Pseudotime\n\nRank genes by Spearman correlation with pseudotime and plot the top ones in\npseudotime order:\n\n```python\nfrom scipy.stats import spearmanr\n\npt = adata.obs[\"dpt_pseudotime\"].to_numpy()\nok = np.isfinite(pt)\ngenes = adata.var_names[adata.var[\"highly_variable\"]] if \"highly_variable\" in adata.var else adata.var_names\nX = adata[ok, genes].X\nX = X.toarray() if hasattr(X, \"toarray\") else np.asarray(X)\nrho = pd.Series(spearmanr(pt[ok], X, axis=0)[0][0, 1:], index=genes).dropna()\ntrend = pd.concat([rho.nlargest(15), rho.nsmallest(15)])\ntrend.to_csv(\"pseudotime_genes.csv\")\nprint(trend.round(2))\n\norder = np.argsort(pt[ok])\nsc.pl.heatmap(adata[ok][order], var_names=list(trend.index), groupby=CLUSTER_KEY,\n              standard_scale=\"var\", show=False, save=\"_pseudotime_genes.png\")\n```\n\n### Recipe: Trajectory Within One Spatial Domain\n\nA global graph can connect cells from unrelated regions. Restrict to one\ndomain (from `spatial-domain-detection`) and recompute:\n\n```python\nDOMAIN_KEY, DOMAIN = \"spagcn_refined\", \"3\"\nsub = adata[adata.obs[DOMAIN_KEY].astype(str) == DOMAIN].copy()\nsc.pp.neighbors(sub, n_pcs=30, n_neighbors=15, random_state=0)\nsc.tl.diffmap(sub)\nin_root = (sub.obs[CLUSTER_KEY] == ROOT_GROUP).to_numpy()\nassert in_root.any(), \"root cluster absent from this domain\"\nsub.uns[\"iroot\"] = int(np.flatnonzero(in_root)[np.argmax(sub.obsm[\"X_diffmap\"][in_root, 1])])\nsc.tl.dpt(sub)\nprint(sub.obs.groupby(CLUSTER_KEY, observed=True)[\"dpt_pseudotime\"].median().sort_values())\n```\n\nCheck the sign of diffusion component 1 as in Step 3 if the order looks\nreversed.\n\n### Recipe: Does Pseudotime Follow Distance from a Landmark?\n\nFor tissues with a spatial axis (crypt base, vessel, tumour edge), correlate\npseudotime with each cell's distance to the nearest landmark cell:\n\n```python\nfrom scipy.spatial import cKDTree\nfrom scipy.stats import spearmanr\n\nLANDMARK = adata.obs[CLUSTER_KEY] == ROOT_GROUP          # or a domain \u002F cell type marking the landmark\ndist = cKDTree(adata.obsm[\"spatial\"][LANDMARK.to_numpy()]).query(adata.obsm[\"spatial\"])[0]\nadata.obs[\"dist_to_landmark\"] = dist\nok = np.isfinite(adata.obs[\"dpt_pseudotime\"])\nr, p = spearmanr(dist[ok], adata.obs.loc[ok, \"dpt_pseudotime\"])\nprint(f\"pseudotime vs distance to landmark: Spearman r = {r:.2f} (p = {p:.1e})\")\n```\n\nWith thousands of cells p is always tiny; judge by r and by the map.\n\n## Expected Outputs\n\n- `paga_adjacency.csv` - cluster-to-cluster PAGA connectivity\n- `fate_probabilities.csv` - per-cell probability of reaching each terminal state\n- `lineage_drivers.csv` - genes correlated with each fate\n- `trajectory_result.h5ad` - pseudotime, velocity layers, `term_states_fwd`, `lineages_fwd`\n- `figures\u002F` - PAGA graph, pseudotime UMAP, velocity streams\n- `trajectory_spatial.png` - pseudotime and fate maps on the tissue\n- `pseudotime_genes.csv` - genes most correlated with pseudotime (recipe)\n\n## Troubleshooting\n\n| Problem | Cause | Fix |\n|---|---|---|\n| `KeyError: 'spliced'` | No velocity layers | Run velocyto \u002F STARsolo Velocyto on the BAM, or use Steps 3 and 5 with the pseudotime kernel |\n| Arrows point from mature to progenitor cells | Steady-state violated, few unspliced reads, or batch effect | Try `MODE=\"dynamical\"`, check `velocity_confidence`, analyse batches separately |\n| `dpt_pseudotime` is `inf` for some cells | Disconnected graph components | Subset to the connected lineage or raise `n_neighbors` |\n| `predict_terminal_states` returns none or too many | Stability threshold vs `N_STATES` | Change `N_STATES` or call `g.set_terminal_states(states=[...])` |\n| Velocity on Xenium \u002F MERFISH data | Probes do not separate spliced and unspliced RNA | Not possible; use PAGA\u002FDPT |\n| Stream plot on `spatial` fails | scVelo looks up `obsm[\"X_spatial\"]` | Copy `obsm[\"spatial\"]` to `obsm[\"X_spatial\"]` (Step 6 does) |\n\n## Related Skills\n\n- `scanpy-scrna-seq` - preprocessing and a short PAGA recipe for dissociated scRNA-seq\n- `spatial-domain-detection` - restrict trajectories to one tissue domain\n- `spatial-transcriptomics-cell-type-annotation` - cluster labels used as `CLUSTER_KEY`\n- `scvi-tools-single-cell` - batch-corrected latent space to build the neighbour graph on\n\n## References\n\n- Wolf et al. (2019) PAGA, Genome Biology: https:\u002F\u002Fdoi.org\u002F10.1186\u002Fs13059-019-1663-x\n- Haghverdi et al. (2016) Diffusion pseudotime, Nature Methods: https:\u002F\u002Fdoi.org\u002F10.1038\u002Fnmeth.3971\n- Bergen et al. (2020) scVelo, Nature Biotechnology: https:\u002F\u002Fdoi.org\u002F10.1038\u002Fs41587-020-0591-3\n- Weiler et al. (2024) CellRank 2, Nature Methods: https:\u002F\u002Fdoi.org\u002F10.1038\u002Fs41592-024-02303-9\n- scVelo documentation: https:\u002F\u002Fscvelo.readthedocs.io\u002Fen\u002Fstable\u002F\n- CellRank documentation: https:\u002F\u002Fcellrank.readthedocs.io\u002Fen\u002Flatest\u002F\n","# Trajectory Inference\n\n## Overview\n\nOrder cells along differentiation or activation paths and estimate where each\ncell is heading. Output: pseudotime, velocity streams, terminal states and\nfate probabilities, and on spatial data their maps on the tissue with a check\nof whether the ordering follows space. Three layers, each optional on top of\nthe previous one:\n\n| Method | Needs | Gives |\n|---|---|---|\n| PAGA + DPT | Clusters, neighbour graph, a chosen root cluster | Cluster connectivity graph, pseudotime |\n| scVelo | `layers[\"spliced\"]` and `layers[\"unspliced\"]` | Direction of change per cell (velocity) |\n| CellRank 2 | A transition kernel (velocity or pseudotime) | Terminal states, fate probabilities, driver genes |\n\nSpliced\u002Funspliced counts come from velocyto, STARsolo (`--soloFeatures Gene\nVelocyto`) or kallisto|bustools run on the reads; for Visium and Slide-seq\nrun them on the Space Ranger \u002F pipeline BAM. Imaging platforms (Xenium,\nMERFISH, CosMx) count probes, not introns, so velocity is not available there.\n\n## When to Use\n\n- Ordering cells along a differentiation or activation path from a chosen start\n- Estimating where cells are heading from spliced\u002Funspliced counts (RNA velocity)\n- Finding terminal states, fate probabilities and the genes driving each fate\n- Checking whether a developmental or activation ordering is laid out in tissue space\n- Finding genes that change along the inferred path\n- Use `scanpy-scrna-seq` instead when you only need a quick PAGA graph inside a standard scRNA-seq workflow\n- For tissue regions rather than cell-state paths, use `spatial-domain-detection`\n\n## Prerequisites\n\n- **Input**: raw counts plus a cluster or cell type column; for velocity, the two layers above\n- **Spatial data**: coordinates in `obsm[\"spatial\"]` for Step 6\n- **Python packages**: `scvelo`, `cellrank` (CellRank 2.x needs Python >= 3.12; CPU is fine)\n\n```bash\n# Install only what `import` reports missing. `--pypi` keeps the env's scanpy\u002Fnumba\n# stack; a conda add can swap it and bare pip can shadow it.\npixi add --pypi scvelo cellrank scanpy\n```\n\n## Workflow\n\n1. Load data and check layers\n2. Preprocess and build the neighbour graph\n3. PAGA and diffusion pseudotime\n4. RNA velocity (scVelo)\n5. Terminal states and fate probabilities (CellRank)\n6. Map pseudotime and fates on the tissue\n\n### Step 1: Load Data\n\n```python\nimport numpy as np\nimport pandas as pd\nimport scanpy as sc\n\nadata = sc.read_h5ad(\"path\u002Fto\u002Fdata.h5ad\")        # your data\n# Demo with spliced\u002Funspliced layers (mouse pancreas endocrinogenesis, downloaded to .\u002Fdata on first use):\n# import scvelo as scv; adata = scv.datasets.pancreas()\nCLUSTER_KEY = \"clusters\"                          # cell type \u002F cluster column\n\nhas_velocity_layers = {\"spliced\", \"unspliced\"} \u003C= set(adata.layers)\nprint(adata)\nprint(f\"velocity layers: {has_velocity_layers}; spatial: {'spatial' in adata.obsm}\")\nprint(adata.obs[CLUSTER_KEY].value_counts())\n```\n\n### Step 2: Preprocess and Neighbour Graph\n\nUses the scVelo order (filter on spliced+unspliced, normalise all layers, then\nlog `X`). Without velocity layers, the scanpy lines alone apply.\n\n```python\nimport scvelo as scv\n\nif has_velocity_layers:\n    scv.pp.filter_genes(adata, min_shared_counts=20)\n    scv.pp.normalize_per_cell(adata)              # normalises X, spliced, unspliced\nelse:\n    adata.layers[\"counts\"] = adata.X.copy()\n    sc.pp.normalize_total(adata)\nsc.pp.log1p(adata)\nsc.pp.highly_variable_genes(adata, n_top_genes=2000)     # imaging panels: skip, use all genes\nsc.pp.pca(adata, n_comps=30)\nsc.pp.neighbors(adata, n_pcs=30, n_neighbors=30, random_state=0)\nif \"X_umap\" not in adata.obsm:\n    sc.tl.umap(adata)\nadata.obs[CLUSTER_KEY] = adata.obs[CLUSTER_KEY].astype(\"category\")\n```\n\n### Step 3: PAGA and Diffusion Pseudotime\n\nThe root cluster is a biological choice (progenitor, naive state); ask the user\nwhen it is not obvious from markers.\n\n```python\nROOT_GROUP = \"Ngn3 low EP\"                        # root cluster name\n\nsc.tl.paga(adata, groups=CLUSTER_KEY)\nsc.pl.paga(adata, threshold=0.05, show=False, save=\"_graph.png\")\ngroups = adata.obs[CLUSTER_KEY].cat.categories\npaga_adj = pd.DataFrame(adata.uns[\"paga\"][\"connectivities\"].toarray(), index=groups, columns=groups)\npaga_adj.to_csv(\"paga_adjacency.csv\")\n\n# Root = the root-cluster cell at the extreme of diffusion component 1\n# (the first cell of the cluster is arbitrary and shifts the whole pseudotime)\nsc.tl.diffmap(adata)\ndc1 = adata.obsm[\"X_diffmap\"][:, 1]\nin_root = (adata.obs[CLUSTER_KEY] == ROOT_GROUP).to_numpy()\nassert in_root.any(), f\"{ROOT_GROUP} not in {list(groups)}\"\nside = np.sign(dc1[in_root].mean() - dc1.mean()) or 1.0\nadata.uns[\"iroot\"] = int(np.flatnonzero(in_root)[np.argmax(side * dc1[in_root])])\nsc.tl.dpt(adata)\nprint(adata.obs.groupby(CLUSTER_KEY, observed=True)[\"dpt_pseudotime\"].median().sort_values())\nsc.pl.umap(adata, color=[CLUSTER_KEY, \"dpt_pseudotime\"], show=False, save=\"_pseudotime.png\")\n```\n\nIf the median pseudotime per cluster does not follow the expected order, the\nroot or the clustering is wrong; DPT is not a test of the order.\n\n### Step 4: RNA Velocity (scVelo)\n\n```python\nMODE = \"stochastic\"                               # \"dynamical\" is slower but gives latent time\n\nscv.pp.moments(adata, n_pcs=None, n_neighbors=None)      # reuses the Step 2 graph\nif MODE == \"dynamical\":\n    scv.tl.recover_dynamics(adata, n_jobs=8)\nscv.tl.velocity(adata, mode=MODE)\nscv.tl.velocity_graph(adata, n_jobs=8)\nscv.tl.velocity_confidence(adata)\nif MODE == \"dynamical\":\n    scv.tl.latent_time(adata)\n\nprint(f\"velocity genes: {int(adata.var['velocity_genes'].sum())}\")\nprint(adata.obs.groupby(CLUSTER_KEY, observed=True)[\"velocity_confidence\"].median().round(2))\nscv.pl.velocity_embedding_stream(adata, basis=\"umap\", color=CLUSTER_KEY, show=False,\n                                 save=\"velocity_stream_umap.png\")\n```\n\nLow `velocity_confidence` (\u003C ~0.5) in a cluster means its arrows are noise;\nsay so rather than interpreting them. Fewer than ~100 velocity genes usually\nmeans too few unspliced reads.\n\n### Step 5: Terminal States and Fate Probabilities (CellRank 2)\n\n```python\nimport cellrank as cr\n\nN_STATES = 8                                      # macrostates; try a few values\nif has_velocity_layers:\n    vk = cr.kernels.VelocityKernel(adata).compute_transition_matrix()\n    ck = cr.kernels.ConnectivityKernel(adata).compute_transition_matrix()\n    kernel = 0.8 * vk + 0.2 * ck                  # connectivity term damps velocity noise\nelse:\n    kernel = cr.kernels.PseudotimeKernel(adata, time_key=\"dpt_pseudotime\").compute_transition_matrix()\n\ng = cr.estimators.GPCCA(kernel)\ng.compute_schur(n_components=20)\ng.compute_macrostates(n_states=N_STATES, cluster_key=CLUSTER_KEY)\ng.predict_terminal_states()                       # or g.set_terminal_states(states=[\"Alpha\", \"Beta\"])\nprint(\"terminal states:\", list(g.terminal_states.cat.categories))\n\ng.compute_fate_probabilities()\nfp = g.fate_probabilities                         # also in adata.obsm[\"lineages_fwd\"]\nfate = pd.DataFrame(np.asarray(fp), index=adata.obs_names, columns=fp.names)\nfate.to_csv(\"fate_probabilities.csv\")\nprint(fate.groupby(adata.obs[CLUSTER_KEY], observed=True).mean().round(2))\n\ndrivers = g.compute_lineage_drivers(cluster_key=CLUSTER_KEY)\ndrivers.to_csv(\"lineage_drivers.csv\")\ng.plot_fate_probabilities(same_plot=False)\nadata.write_h5ad(\"trajectory_result.h5ad\", compression=\"gzip\")\n```\n\nTerminal states (`adata.obs[\"term_states_fwd\"]`) should be clusters the user\nrecognises as end points. If `predict_terminal_states` misses a known end\nstate, change `N_STATES` or set the states by name from `g.macrostates`.\n\n### Step 6: Map Pseudotime and Fates on the Tissue\n\nOn spatial data, check whether the inferred ordering is spatially organised\n(e.g. crypt-to-villus, cortical depth). Moran's I near 0 means the ordering is\nnot reflected in space.\n\n```python\nimport matplotlib.pyplot as plt\nfrom sklearn.neighbors import kneighbors_graph\n\nW = kneighbors_graph(adata.obsm[\"spatial\"], n_neighbors=6, include_self=False)\n\ndef morans_i(v):\n    z = np.asarray(v, float) - np.mean(v)\n    return len(z) \u002F W.sum() * (z @ (W @ z)) \u002F (z @ z)\n\ntracks = {\"dpt_pseudotime\": adata.obs[\"dpt_pseudotime\"].to_numpy()}\nif \"fate\" in globals():\n    tracks.update({f\"fate_{c}\": fate[c].to_numpy() for c in fate.columns})\nfor name, v in tracks.items():\n    adata.obs[name] = v\n    ok = np.isfinite(v)\n    print(f\"{name}: Moran's I = {morans_i(np.where(ok, v, np.nanmean(v[ok]))):.2f}\")\n\naxes = sc.pl.embedding(adata, basis=\"spatial\", color=list(tracks), cmap=\"viridis\", size=1.5, show=False)\nfor ax in np.atleast_1d(axes):\n    ax.invert_yaxis()                             # pixel y grows downwards; drop for micron coordinates\nplt.savefig(\"trajectory_spatial.png\", dpi=150, bbox_inches=\"tight\")\n\nif \"velocity\" in adata.layers:                    # velocity arrows projected onto tissue coordinates\n    adata.obsm[\"X_spatial\"] = adata.obsm[\"spatial\"]\n    scv.pl.velocity_embedding_stream(adata, basis=\"spatial\", color=CLUSTER_KEY, show=False,\n                                     save=\"velocity_stream_spatial.png\")\n```\n\nA velocity stream on tissue coordinates shows transcriptional direction drawn\nin space; it is not physical cell migration.\n\n## Key Parameters\n\n| Parameter | Default | Effect |\n|---|---|---|\n| `ROOT_GROUP` | from the user | Start of pseudotime; flips the whole ordering if wrong |\n| `n_neighbors` (Step 2) | 30 | Graph used by PAGA, DPT, moments and CellRank |\n| `min_shared_counts` | 20 | Gene filter on spliced + unspliced counts |\n| `MODE` | `\"stochastic\"` | `\"dynamical\"` fits per-gene kinetics, adds latent time, ~10x slower |\n| Kernel weights | 0.8 velocity \u002F 0.2 connectivity | More connectivity = smoother, less directional |\n| `N_STATES` | 8 | Macrostates searched for terminal states |\n| PAGA `threshold` | 0.05 | Edges below this connectivity are hidden in the plot |\n\n## Common Recipes\n\n### Recipe: Genes Changing Along Pseudotime\n\nRank genes by Spearman correlation with pseudotime and plot the top ones in\npseudotime order:\n\n```python\nfrom scipy.stats import spearmanr\n\npt = adata.obs[\"dpt_pseudotime\"].to_numpy()\nok = np.isfinite(pt)\ngenes = adata.var_names[adata.var[\"highly_variable\"]] if \"highly_variable\" in adata.var else adata.var_names\nX = adata[ok, genes].X\nX = X.toarray() if hasattr(X, \"toarray\") else np.asarray(X)\nrho = pd.Series(spearmanr(pt[ok], X, axis=0)[0][0, 1:], index=genes).dropna()\ntrend = pd.concat([rho.nlargest(15), rho.nsmallest(15)])\ntrend.to_csv(\"pseudotime_genes.csv\")\nprint(trend.round(2))\n\norder = np.argsort(pt[ok])\nsc.pl.heatmap(adata[ok][order], var_names=list(trend.index), groupby=CLUSTER_KEY,\n              standard_scale=\"var\", show=False, save=\"_pseudotime_genes.png\")\n```\n\n### Recipe: Trajectory Within One Spatial Domain\n\nA global graph can connect cells from unrelated regions. Restrict to one\ndomain (from `spatial-domain-detection`) and recompute:\n\n```python\nDOMAIN_KEY, DOMAIN = \"spagcn_refined\", \"3\"\nsub = adata[adata.obs[DOMAIN_KEY].astype(str) == DOMAIN].copy()\nsc.pp.neighbors(sub, n_pcs=30, n_neighbors=15, random_state=0)\nsc.tl.diffmap(sub)\nin_root = (sub.obs[CLUSTER_KEY] == ROOT_GROUP).to_numpy()\nassert in_root.any(), \"root cluster absent from this domain\"\nsub.uns[\"iroot\"] = int(np.flatnonzero(in_root)[np.argmax(sub.obsm[\"X_diffmap\"][in_root, 1])])\nsc.tl.dpt(sub)\nprint(sub.obs.groupby(CLUSTER_KEY, observed=True)[\"dpt_pseudotime\"].median().sort_values())\n```\n\nCheck the sign of diffusion component 1 as in Step 3 if the order looks\nreversed.\n\n### Recipe: Does Pseudotime Follow Distance from a Landmark?\n\nFor tissues with a spatial axis (crypt base, vessel, tumour edge), correlate\npseudotime with each cell's distance to the nearest landmark cell:\n\n```python\nfrom scipy.spatial import cKDTree\nfrom scipy.stats import spearmanr\n\nLANDMARK = adata.obs[CLUSTER_KEY] == ROOT_GROUP          # or a domain \u002F cell type marking the landmark\ndist = cKDTree(adata.obsm[\"spatial\"][LANDMARK.to_numpy()]).query(adata.obsm[\"spatial\"])[0]\nadata.obs[\"dist_to_landmark\"] = dist\nok = np.isfinite(adata.obs[\"dpt_pseudotime\"])\nr, p = spearmanr(dist[ok], adata.obs.loc[ok, \"dpt_pseudotime\"])\nprint(f\"pseudotime vs distance to landmark: Spearman r = {r:.2f} (p = {p:.1e})\")\n```\n\nWith thousands of cells p is always tiny; judge by r and by the map.\n\n## Expected Outputs\n\n- `paga_adjacency.csv` - cluster-to-cluster PAGA connectivity\n- `fate_probabilities.csv` - per-cell probability of reaching each terminal state\n- `lineage_drivers.csv` - genes correlated with each fate\n- `trajectory_result.h5ad` - pseudotime, velocity layers, `term_states_fwd`, `lineages_fwd`\n- `figures\u002F` - PAGA graph, pseudotime UMAP, velocity streams\n- `trajectory_spatial.png` - pseudotime and fate maps on the tissue\n- `pseudotime_genes.csv` - genes most correlated with pseudotime (recipe)\n\n## Troubleshooting\n\n| Problem | Cause | Fix |\n|---|---|---|\n| `KeyError: 'spliced'` | No velocity layers | Run velocyto \u002F STARsolo Velocyto on the BAM, or use Steps 3 and 5 with the pseudotime kernel |\n| Arrows point from mature to progenitor cells | Steady-state violated, few unspliced reads, or batch effect | Try `MODE=\"dynamical\"`, check `velocity_confidence`, analyse batches separately |\n| `dpt_pseudotime` is `inf` for some cells | Disconnected graph components | Subset to the connected lineage or raise `n_neighbors` |\n| `predict_terminal_states` returns none or too many | Stability threshold vs `N_STATES` | Change `N_STATES` or call `g.set_terminal_states(states=[...])` |\n| Velocity on Xenium \u002F MERFISH data | Probes do not separate spliced and unspliced RNA | Not possible; use PAGA\u002FDPT |\n| Stream plot on `spatial` fails | scVelo looks up `obsm[\"X_spatial\"]` | Copy `obsm[\"spatial\"]` to `obsm[\"X_spatial\"]` (Step 6 does) |\n\n## Related Skills\n\n- `scanpy-scrna-seq` - preprocessing and a short PAGA recipe for dissociated scRNA-seq\n- `spatial-domain-detection` - restrict trajectories to one tissue domain\n- `spatial-transcriptomics-cell-type-annotation` - cluster labels used as `CLUSTER_KEY`\n- `scvi-tools-single-cell` - batch-corrected latent space to build the neighbour graph on\n\n## References\n\n- Wolf et al. (2019) PAGA, Genome Biology: https:\u002F\u002Fdoi.org\u002F10.1186\u002Fs13059-019-1663-x\n- Haghverdi et al. (2016) Diffusion pseudotime, Nature Methods: https:\u002F\u002Fdoi.org\u002F10.1038\u002Fnmeth.3971\n- Bergen et al. (2020) scVelo, Nature Biotechnology: https:\u002F\u002Fdoi.org\u002F10.1038\u002Fs41587-020-0591-3\n- Weiler et al. (2024) CellRank 2, Nature Methods: https:\u002F\u002Fdoi.org\u002F10.1038\u002Fs41592-024-02303-9\n- scVelo documentation: https:\u002F\u002Fscvelo.readthedocs.io\u002Fen\u002Fstable\u002F\n- CellRank documentation: https:\u002F\u002Fcellrank.readthedocs.io\u002Fen\u002Flatest\u002F\n",{"name":5,"license":15,"description":7},"master","fd76f882a04e445e899d5cfb2732f2105ea054ee","skills\u002Fawesome-skills\u002Ftrajectory-inference",0,"https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS","https:\u002F\u002Fbg-szy.github.io\u002FTOP-SKILLS\u002F","https:\u002F\u002Fgithub.com\u002Fbg-szy","https:\u002F\u002Fwww.ecust.edu.cn\u002F","a student of East China University of Science and Technology","2026-11-15 03:38:02",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add bg-szy\u002FTOP-SKILLS --skill trajectory-inference",{"tool":40,"command":41},"bunx","bunx skills add bg-szy\u002FTOP-SKILLS --skill trajectory-inference",{"tool":43,"command":44},"pnpm","pnpm dlx skills add bg-szy\u002FTOP-SKILLS --skill trajectory-inference","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fawesome-skills\u002Ftrajectory-inference\u002FSKILL.md",true,[],[49,58,65,72,79,86],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":54,"categories":55,"keywords":56,"publishedAt":57},"01M7DXW9N826PKXK174PVW3038","serpmaven","Scrape Google search results (SERP) to JSON with SERP Maven (serpmaven) - a real Chrome browser on a residential proxy with sticky sessions. Run it as a CLI, a Python library, a local HTTP search API (`serve`), an MCP server or a Docker image; set the proxy login, workers, pages and cost tracking. Use when the user wants Google results, rank tracking, a self-hosted SERP API, or live Google search for an AI agent.","MIT","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fserpmaven\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":59,"name":60,"nameZh":6,"description":61,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":62,"categories":63,"keywords":64,"publishedAt":57},"01M7DXVHSTWDV65475QEQ915M7","revnu-landing-page-audit","Find out why a landing page isn't turning visitors into signups, demos or sales. Audits one page against what the ad, post or search that sends people there promised, then checks the first screen, proof, call to action, friction and mobile. Returns at most 7 prioritized fixes, plus what is fine and what could not be checked; rewrites specific lines and fixes the page in the repo when asked. Never promises a conversion lift. Works without a Revnu account. Use when the user says or asks: \"audit my landing page\", \"why isn't this page converting\", \"review my homepage\", \"my ads get clicks but no signups\", \"people bounce from the pricing page\", \"CRO review\", \"improve conversion rate\", \"is my hero section clear\", \"roast my landing page\", \"rewrite my headline\", \"what's wrong with this page\", \"landing page feedback\", \"make the signup page convert better\". Not for SEO or AI-search audits, page speed engineering on its own, or building a new page from scratch.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-landing-page-audit\u002FSKILL.md",[],[],{"skillNo":66,"name":67,"nameZh":6,"description":68,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":69,"categories":70,"keywords":71,"publishedAt":57},"01M7DXV8X2D7B3VTD4HHYYHTGR","revnu-growth-context","Write down once who buys, what they're stuck on, what it costs, what proof you have and what you've already tried, so every growth task starts from facts instead of a questionnaire. Creates or updates .agents\u002Frevnu-growth.md from the repo, the live site and the user, and imports an existing product-marketing.md. Use when the user says \"set up our marketing context\", \"who is our ideal customer\", \"write our ICP\", \"describe the product for marketing\", \"positioning doc\", \"what's our brand voice\", \"remember this about our customers\", \"log what we tried\", \"what have we learned from marketing\", \"we changed pricing, update the context\", \"update our growth notes\", \"summarize the business for the agent\", \"import my product-marketing.md\", \"start a growth doc\", or before a first marketing, SEO, outreach or launch task when no context file exists. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-growth-context\u002FSKILL.md",[],[],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"publishedAt":57},"01M7DXV0DGJ1G0A60PAHC6J3C5","revnu-get-listed","Get onto the third-party pages AI answers and search cite when buyers ask for the best tool in your category: \"best X\" roundups, directories, review sites, GitHub awesome lists, community threads and comparison pages. Finds which ones are cited, ranks them by fit and effort, and drafts each submission, PR or pitch by the target's own rules. Use when the user says \"get us listed\", \"which directories should we submit to\", \"how do we get into best-of lists\", \"why does ChatGPT recommend competitors and not us\", \"get mentioned in AI answers\", \"submit to awesome lists\", \"get on G2\", \"where are our competitors listed\", \"pitch listicle authors\", \"find backlink opportunities\", \"launch directories\", \"get into roundups\", \"Product Hunt alternatives\", \"where should we be listed\", \"get cited by Perplexity\". Never submits, pays or posts without a yes. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-get-listed\u002FSKILL.md",[],[],{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":57},"01M7DXTSPMGT9D6DSS0HP9BSTA","revnu-ai-readiness-audit","Audit whether your website gives ChatGPT, Perplexity, Claude, Gemini and Google's AI Overviews something worth quoting, and fix the pages that don't. Use when the user says or asks \"is my site ready for AI search\", \"audit my site for AI answers\", \"AEO audit\", \"GEO audit\", \"why doesn't ChatGPT quote our pricing\", \"make our pages citable by AI\", \"do I need llms.txt\", \"does schema help with ChatGPT\", \"check our structured data\", \"is our content visible without JavaScript\", \"AI SEO audit\", \"optimize our homepage for AI answers\", \"LLM SEO check\", \"why does AI get our product wrong\", \"fix our site for AI Overviews\". Checks fetchability and indexability, answers in the raw HTML, entity facts, schema (including JS-injected markup), headings, dates and llms.txt, then gives at most 10 prioritised fixes and edits the repo when asked. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-ai-readiness-audit\u002FSKILL.md",[],[],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":57},"01M7DXSZHCVTRS620GC3S97JZV","proxy-troubleshooting","Diagnose residential proxy failures, with NodeMaven's gateway as the reference - 407 with correct credentials, 406, 410, 500, a connection that hangs, ERR_TUNNEL_CONNECTION_FAILED in a browser, Playwright or Puppeteer ignoring proxy credentials, a sticky session that changes IP, geo-targeting that is silently ignored, passwords with special characters, and unexpected traffic from headless Chrome. Use when a proxy connection fails, returns the wrong location, or costs more traffic than expected.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fproxy-troubleshooting\u002FSKILL.md",[],[]]