{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Pegasus Tutorial\n", "\n", "Author: [Yiming Yang](https://github.com/yihming), [Rimte Rocher](https://github.com/rocherr)
\n", "Date: 2022-03-09
\n", "Notebook Source: [pegasus_analysis.ipynb](https://raw.githubusercontent.com/lilab-bcb/pegasus-tutorials/main/notebooks/pegasus_analysis.ipynb)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import pegasus as pg" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Count Matrix File\n", "\n", "For this tutorial, we provide a count matrix dataset on Human Bone Marrow with 8 donors stored in zarr format (with file extension \".zarr.zip\").\n", "\n", "You can download the data at https://storage.googleapis.com/terra-featured-workspaces/Cumulus/MantonBM_nonmix_subset.zarr.zip.\n", "\n", "This file is achieved by aggregating gene-count matrices of the 8 10X channels using PegasusIO, and further filtering out cells with fewer than $100$ genes expressed. Please see [here](https://pegasusio.readthedocs.io/en/latest/_static/tutorials/pegasusio_tutorial.html#Case-5:-Data-aggregation-with-filtering) for how to do it interactively. \n", "\n", "Now load the file using pegasus `read_input` function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data = pg.read_input(\"MantonBM_nonmix_subset.zarr.zip\")\n", "data" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The count matrix is managed as a UnimodalData object defined in [PegasusIO](https://pegasusio.readthedocs.io) module, and users can manipulate the data from top level via MultimodalData structure, which can contain multiple UnimodalData objects as members.\n", "\n", "For this example, as show above, `data` is a MultimodalData object, with only one UnimodalData member of key `\"GRCh38-rna\"`, which is its default UnimodalData. Any operation on `data` will be applied to this default UnimodalData object.\n", "\n", "UnimodalData has the following structure:\n", "\n", "\n", "\n", "It has 6 major parts:\n", "* Raw count matrix: `data.X`, a [Scipy sparse matrix](https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html) (sometimes can be a dense matrix), with rows the cell barcodes, columns the genes/features:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data.X" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This dataset contains $48,219$ barcodes and $36,601$ genes.\n", "\n", "* Cell barcode attributes: `data.obs`, a [Pandas data frame](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html) with barcode as the index. For now, there is only one attribute `\"Channel\"` referring to the donor from which the cell comes from:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data.obs.head()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data.obs['Channel'].value_counts()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* Gene attributes: `data.var`, also a Pandas data frame, with gene name as the index. For now, it only has one attribute `\"gene_ids\"` referring to the unique gene ID in the experiment:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data.var.head()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* Unstructured information: `data.uns`, a Python [hashed dictionary](https://docs.python.org/3/library/collections.html#collections.OrderedDict). It usually stores information not restricted to barcodes or features, but about the whole dataset, such as its genome reference and modality type:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data.uns['genome']" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data.uns['modality']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* Finally, embedding attributes on cell barcodes: `data.obsm`; as well as on genes, `data.varm`. We'll see it in later sections." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Preprocessing\n", "\n", "### Filtration\n", "\n", "The first step in preprocessing is to perform the quality control analysis, and remove cells and genes of low quality.\n", "\n", "We can generate QC metrics using the following method with default settings:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pg.qc_metrics(data, min_genes=500, max_genes=6000, mito_prefix='MT-', percent_mito=10)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The metrics considered are:\n", "* **Number of genes**: Keep cells with $500 \\leq \\text{# Genes} < 6000$. (Notice that starting from v1.4.0, Pegasus doesn't filter cells by number of genes threshold by default.)\n", "* **Number of UMIs**: Don't filter cells due to UMI bounds *(Default)*;\n", "* **Percent of Mitochondrial genes**: Look for mitochondrial genes with name prefix `MT-` (Notice that starting from v1.4.0, you'll need to manually specify this prefix.), and keep cells with percent $< 10\\%$.\n", "\n", "For details on customizing your own thresholds, see [documentation](https://pegasus.readthedocs.io/en/stable/api/pegasus.qc_metrics.html).\n", "\n", "Numeric summaries on filtration on cell barcodes and genes can be achieved by `get_filter_stats` method:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df_qc = pg.get_filter_stats(data)\n", "df_qc" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The results is a Pandas data frame on samples.\n", "\n", "You can also check the QC stats via plots. Below is on number of genes:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pg.qcviolin(data, plot_type='gene', dpi=100)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Then on number of UMIs:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pg.qcviolin(data, plot_type='count', dpi=100)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "On number of percentage of mitochondrial genes:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pg.qcviolin(data, plot_type='mito', dpi=100)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now filter cells based on QC metrics set in `qc_metrics`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pg.filter_data(data)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can see that $35,465$ cells ($73.55\\%$) are kept.\n", "\n", "Moreover, for genes, only those with no cell expression are removed. After that, we identify **robust** genes for downstream analysis:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pg.identify_robust_genes(data)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The metric is the following:\n", "* Gene is expressed in at least $0.05\\%$ of cells, i.e. among every 6000 cells, there are at least 3 cells expressing this gene.\n", "\n", "Please see [its documentation](https://pegasus.readthedocs.io/en/stable/api/pegasus.identify_robust_genes.html) for details.\n", "\n", "As a result, $25,653$ ($70.09\\%$) genes are kept. Among them, $17,516$ are robust.\n", "\n", "We can now view the cells of each sample after filtration:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data.obs['Channel'].value_counts()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Normalization and Logarithmic Transformation\n", "\n", "After filtration, we need to first normalize the distribution of counts w.r.t. each cell to have the same sum (default is $10^5$, see [documentation](https://pegasus.readthedocs.io/en/stable/api/pegasus.log_norm.html)), and then transform into logarithmic space by $log(x + 1)$ to avoid number explosion:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pg.log_norm(data)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For the downstream analysis, we may need to make a copy of the count matrix, in case of coming back to this step and redo the analysis:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data_trial = data.copy()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Highly Variable Gene Selection\n", "\n", "**Highly Variable Genes (HVG)** are more likely to convey information discriminating different cell types and states.\n", "Thus, rather than considering all genes, people usually focus on selected HVGs for downstream analyses.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pg.highly_variable_features(data_trial)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "By default, we select 2000 HVGs using the pegasus selection method. Alternative, you can also choose the traditional method that both *Seurat* and *SCANPY* use, by setting `flavor='Seurat'`. See [documentation](https://pegasus.readthedocs.io/en/stable/api/pegasus.highly_variable_features.html) for details.\n", "\n", "We can view HVGs by ranking them from top:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data_trial.var.loc[data_trial.var['highly_variable_features']].sort_values(by='hvf_rank')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can also view HVGs in a scatterplot:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pg.hvfplot(data_trial, dpi=200)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this plot, each point stands for one gene. Blue points are selected to be HVGs, which account for the majority of variation of the dataset." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Principal Component Analysis\n", "\n", "To reduce the dimension of data, Principal Component Analysis (PCA) is widely used. Briefly speaking, PCA transforms the data from original dimensions into a new set of Principal Components (PC) of a much smaller size. In the transformed data, dimension is reduced, while PCs still cover a majority of the variation of data. Moreover, the new dimensions (i.e. PCs) are independent with each other.\n", "\n", "`pegasus` uses the following method to perform PCA:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pg.pca(data_trial)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "By default, `pca` uses:\n", "* Before PCA, scale the data to standard Normal distribution $N(0, 1)$, and truncate them with max value $10$;\n", "* Number of PCs to compute: 50;\n", "* Apply PCA only to highly variable features.\n", "\n", "See [its documentation](https://pegasus.readthedocs.io/en/stable/api/pegasus.pca.html) for customization.\n", "\n", "To explain the meaning of PCs, let's look at the first PC (denoted as $PC_1$), which covers the most of variation:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "coord_pc1 = data_trial.uns['PCs'][:, 0]\n", "coord_pc1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is an array of 2000 elements, each of which is a coefficient corresponding to one HVG.\n", "\n", "With the HVGs as the following:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data_trial.var.loc[data_trial.var['highly_variable_features']].index.values" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$PC_1$ is computed by\n", "\n", "\\begin{equation*}\n", "PC_1 = \\text{coord_pc1}[0] \\cdot \\text{HES4} + \\text{coord_pc1}[1] \\cdot \\text{ISG15} + \\text{coord_pc1}[2] \\cdot \\text{TNFRSF18} + \\cdots + \\text{coord_pc1}[1997] \\cdot \\text{RPS4Y2} + \\text{coord_pc1}[1998] \\cdot \\text{MT-CO1} + \\text{coord_pc1}[1999] \\cdot \\text{MT-CO3}\n", "\\end{equation*}\n", "\n", "Therefore, all the 50 PCs are the linear combinations of the 2000 HVGs.\n", "\n", "The calculated PCA count matrix is stored in the `obsm` field, which is the first embedding object we have " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data_trial.obsm['X_pca'].shape" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For each of the $35,465$ cells, its count is now w.r.t. 50 PCs, instead of 2000 HVGs." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Nearest Neighbors\n", "\n", "All the downstream analysis, including clustering and visualization, needs to construct a k-Nearest-Neighbor (kNN) graph on cells. We can build such a graph using `neighbors` method:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pg.neighbors(data_trial)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It uses the default setting:\n", "* For each cell, calculate its 100 nearest neighbors;\n", "* Use PCA matrix for calculation;\n", "* Use L2 distance as the metric;\n", "* Use [hnswlib](https://github.com/nmslib/hnswlib) search algorithm to calculate the approximated nearest neighbors in a really short time.\n", "\n", "See [its documentation](https://pegasus.readthedocs.io/en/stable/api/pegasus.neighbors.html) for customization.\n", "\n", "Below is the result:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(f\"Get {data_trial.obsm['pca_knn_indices'].shape[1]} nearest neighbors (excluding itself) for each cell.\")\n", "data_trial.obsm['pca_knn_indices']" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data_trial.obsm['pca_knn_distances']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Each row corresponds to one cell, listing its neighbors (not including itself) from nearest to farthest. `data_trial.obsm['pca_knn_indices']` stores their indices, and `data_trial.obsm['pca_knn_distances']` stores distances." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Clustering and Visualization\n", "\n", "Now we are ready to cluster the data for cell type detection. `pegasus` provides 4 clustering algorithms to use:\n", "* `louvain`: Louvain algorithm, using [louvain](https://github.com/vtraag/louvain-igraph) package.\n", "* `leiden`: Leiden algorithm, using [leidenalg](https://github.com/vtraag/leidenalg) package.\n", "* `spectral_louvain`: Spectral Louvain algorithm, which requires Diffusion Map.\n", "* `spectral_leiden`: Spectral Leiden algorithm, which requires Diffusion Map.\n", "\n", "See [this documentation](https://pegasus.readthedocs.io/en/stable/api/index.html#cluster-algorithms) for details.\n", "\n", "In this tutorial, we use the Louvain algorithm:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pg.louvain(data_trial)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As a result, Louvain algorithm finds 19 clusters:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data_trial.obs['louvain_labels'].value_counts()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can check each cluster's composition regarding donors via a composition plot:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pg.compo_plot(data_trial, 'louvain_labels', 'Channel')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "However, we can see a clear batch effect in the plot: e.g. Cluster 11 and 14 have most cells from Donor 3.\n", "\n", "We can see it more clearly in its FIt-SNE plot (a visualization algorithm which we will talk about later):" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pg.tsne(data_trial)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pg.scatter(data_trial, attrs=['louvain_labels', 'Channel'], basis='tsne')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Batch Correction\n", "\n", "Batch effect occurs when data samples are generated in different conditions, such as date, weather, lab setting, equipment, etc. Unless informed that all the samples were generated under the similar condition, people may suspect presumable batch effects if they see a visualization graph with samples kind-of isolated from each other.\n", "\n", "For this dataset, we need the batch correction step to reduce such a batch effect, which is observed in the plot above.\n", "\n", "In this tutorial, we use [Harmony](https://www.nature.com/articles/s41592-019-0619-0) algorithm for batch correction. It requires redo HVG selection, calculate new PCA coordinates, and apply the correction:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pg.highly_variable_features(data, batch='Channel') \n", "pg.pca(data)\n", "pca_key = pg.run_harmony(data)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The corrected PCA coordinates are stored in `data.obsm`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data.obsm['X_pca_harmony'].shape" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`pca_key` is the representation key returned by `run_harmony` function, which is equivalent to string `\"pca_harmony\"`. In the following sections, you can use either `pca_key` or `\"pca_harmony\"` to specify `rep` parameter in Pegasus functions whenever applicable." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Repeat Previous Steps on the Corrected Data\n", "\n", "As the count matrix is changed by batch correction, we need to recalculate nearest neighbors and perform clustering. Don't forget to use the corrected PCA coordinates as the representation:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pg.neighbors(data, rep=pca_key)\n", "pg.louvain(data, rep=pca_key)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's check the composition plot now:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pg.compo_plot(data, 'louvain_labels', 'Channel')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If everything goes properly, you should be able to see that no cluster has a dominant donor cells. Also notice that Louvain algorithm on the corrected data finds 16 clusters, instead of the original 19 ones.\n", "\n", "Also, FIt-SNE plot is different:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pg.tsne(data, rep=pca_key)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pg.scatter(data, attrs=['louvain_labels', 'Channel'], basis='tsne')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can see that the right-hand-side plot has a much better mixture of cells from different donors." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Visualization" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### tSNE Plot\n", "\n", "In previous sections, we have seen data visualization using FIt-SNE. FIt-SNE is a fast implementation on tSNE algorithm, and Pegasus uses it for the tSNE embedding calculation. [See details](https://pegasus.readthedocs.io/en/stable/api/pegasus.tsne.html)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### UMAP Plot\n", "\n", "Besides tSNE, `pegasus` also provides UMAP plotting methods:\n", "\n", "* `umap`: UMAP plot, using [umap-learn](https://github.com/lmcinnes/umap) package. [See details](https://pegasus.readthedocs.io/en/stable/api/pegasus.umap.html)\n", "* `net_umap`: Approximated UMAP plot with DNN model based speed up. [See details](https://pegasus.readthedocs.io/en/stable/api/pegasus.net_umap.html)\n", "\n", "Below is the UMAP plot of the data using `umap` method:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pg.umap(data, rep=pca_key)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pg.scatter(data, attrs=['louvain_labels', 'Channel'], basis='umap')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Differential Expression Analysis\n", "\n", "With the clusters ready, we can now perform Differential Expression (DE) Analysis. DE analysis is to discover cluster-specific marker genes. For each cluster, it compares cells within the cluster with all the others, then finds genes significantly highly expressed (up-regulated) and lowly expressed (down-regulated) for the cluster." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now use `de_analysis` method to run DE analysis. We use Louvain result here. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pg.de_analysis(data, cluster='louvain_labels')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "By default, DE analysis runs Mann-Whitney U (MWU) test.\n", "\n", "Alternatively, you can also run the follow tests by setting their corresponding parameters to be `True`:\n", "* `fisher`: Fisher’s exact test.\n", "* `t`: Welch’s T test.\n", "\n", "DE analysis result is stored with key `\"de_res\"` (by default) in `varm` field of data. See [documentation](https://pegasus.readthedocs.io/en/stable/api/pegasus.de_analysis.html) for more details. \n", "\n", "To load the result in a human-readable format, use `markers` method:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "marker_dict = pg.markers(data)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "By default, `markers`:\n", "* Sort genes by Area under ROC curve (AUROC) in descending order;\n", "* Use $\\alpha = 0.05$ significance level on q-values for inference.\n", "\n", "See [documentation](https://pegasus.readthedocs.io/en/stable/api/pegasus.markers.html) for customizing these parameters.\n", "\n", "Let's see the up-regulated genes for Cluster 1, and rank them in descending order with respect to log fold change:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "marker_dict['1']['up'].sort_values(by='log2FC', ascending=False)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Among them, **TRAC** worth notification. It is a critical marker for T cells." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can also use Volcano plot to see the DE result. Below is such a plot w.r.t. Cluster 1 with MWU test results (by default):" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pg.volcano(data, cluster_id = '1', dpi=200)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The plot above uses the default thresholds: log fold change at $1$ (i.e. fold change at $2$), and q-value at $0.05$. Each point stands for a gene. Red ones are significant marker genes: those at right-hand side are up-regulated genes for Cluster 1, while those at left-hand side are down-regulated genes.\n", "\n", "We can see that gene **TRAC** is the second to rightmost point, which is a significant up-regulated gene for Cluster 1. \n", "\n", "To store a specific DE analysis result to file, you can `write_results_to_excel` methods in `pegasus`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pg.write_results_to_excel(marker_dict, \"MantonBM_subset.de.xlsx\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Cell Type Annotation\n", "\n", "After done with DE analysis, we can use the test result to annotate the clusters." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "celltype_dict = pg.infer_cell_types(data, markers = 'human_immune')\n", "cluster_names = pg.infer_cluster_names(celltype_dict)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`infer_cell_types` has 2 critical parameters to set:\n", "* `markers`: Either `'human_immune'`, `'mouse_immune'`, `'human_brain'`, `'mouse_brain'`, `'human_lung'`, or a user-specified marker dictionary.\n", "* `de_test`: Decide which DE analysis test to be used for cell type inference. It can be either `'t'`, `'fisher'`, or `'mwu'`. Its default is `'mwu'`.\n", "\n", "`infer_cluster_names` by default uses `threshold = 0.5` to filter out candidate cell types of scores lower than 0.5.\n", "\n", "See [documentation](https://pegasus.readthedocs.io/en/stable/api/pegasus.infer_cell_types.html) for details.\n", "\n", "Below is the cell type annotation report for Cluster 1:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "celltype_dict['1']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The report has a list of predicted cell types along with their scores and support genes for users to decide.\n", "\n", "Next, substitute the inferred cluster names in data using `annotate` function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pg.annotate(data, name='anno', based_on='louvain_labels', anno_dict=cluster_names)\n", "data.obs['anno'].value_counts()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "So the cluster-specific cell type information is stored in `data.obs['anno']`.\n", "\n", "The `anno_dict` can be either a list or a dictionary. If provided a list (which is the case here), Pegasus will match cell types with cluster labels in the same order. Alternatively, you can create an annotation dictionary with keys being cluster labels and cell types being values.\n", "\n", "In practice, users may want to manually create this annotation structure by reading the report in `celltype_dict`. In this tutorial, we'll just use the output of `infer_cluster_names` function for demonstration.\n", "\n", "Now plot the data with cell types:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pg.scatter(data, attrs='anno', basis='tsne', dpi=100)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pg.scatter(data, attrs='anno', basis='umap', legend_loc='on data', dpi=150)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Raw Count vs Log-norm Count\n", "\n", "Now let's check the count matrix:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can see that besides `X`, there is another matrix `raw.X` generated for this analysis. As the key name indicates, `raw.X` stores the raw count matrix, which is the one after loading from the original Zarr file; while `X` stores the log-normalized counts.\n", "\n", "`data` currently binds to matrix `X`. To use the raw count instead, type:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data.select_matrix('raw.X')\n", "data" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now `data` binds to raw counts.\n", "\n", "We still need log-normalized counts for the following sections, so reset the default count matrix:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data.select_matrix('X')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Cell Development Trajectory and Diffusion Map\n", "\n", "Alternative, pegasus provides cell development trajectory plots using Force-directed Layout (FLE) algorithm:\n", "\n", "* `pg.fle`: FLE plot, using Force-Atlas 2 algorithm in [forceatlas2-python](https://github.com/klarman-cell-observatory/forceatlas2-python) package. [See details](https://pegasus.readthedocs.io/en/stable/api/pegasus.fle.html)\n", "* `pg.net_fle`: Approximated FLE plot with DNN model based speed up. [See details](https://pegasus.readthedocs.io/en/stable/api/pegasus.net_fle.html)\n", "\n", "Moreover, calculation of FLE plots is on Diffusion Map of the data, rather than directly on data points, in order to achieve a better efficiency. Thus, we need to first compute the diffusion map structure:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pg.diffmap(data, rep=pca_key)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "By default, diffmap method uses:\n", "\n", "* Number of Diffusion Components = 100\n", "* Compute diffusion map from PCA matrix.\n", "\n", "In this tutorial, we should use the corrected PCA matrix, which is specified in `pca_key`. The resulting diffusion map is in `data.obsm` with key `\"X_diffmap\"`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data.obsm['X_diffmap'].shape" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we are ready to calculate the pseudo-temporal trajectories of cell development. We use `fle` here:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pg.fle(data)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And show FLE plot regarding cell type annotations:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pg.scatter(data, attrs='anno', basis='fle')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Save Result to File\n", "\n", "Use `write_output` function to save analysis result `data` to file:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pg.write_output(data, \"MantonBM_result.zarr.zip\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It's stored in `zarr` format, because this is the default file format in Pegasus.\n", "\n", "Alternatively, you can also save it in `h5ad`, `mtx`, or `loom` format. See [its documentation](https://pegasus.readthedocs.io/en/stable/api/pegasus.write_output.html) for instructions." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Read More...\n", "\n", "* Read [Plotting Tutorial](https://pegasus-tutorials.readthedocs.io/en/latest/_static/tutorials/plotting_tutorial.html) for more plotting functions provided by Pegasus.\n", "\n", "* Read [Pegasus API](https://pegasus.readthedocs.io/en/stable/api/index.html) documentation for details on Pegasus functions." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.10" }, "toc": { "base_numbering": 1, "nav_menu": {}, "number_sections": true, "sideBar": true, "skip_h1_title": false, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": false, "toc_position": {}, "toc_section_display": true, "toc_window_display": false }, "widgets": { "application/vnd.jupyter.widget-state+json": { "state": {}, "version_major": 2, "version_minor": 0 } } }, "nbformat": 4, "nbformat_minor": 2 }