{ "cells": [ { "cell_type": "raw", "metadata": {}, "source": [ "---\n", "description: Identify genes that are significantly over or\n", " under-expressed between conditions in specific cell populations.\n", "subtitle: Scanpy Toolkit\n", "title: Differential gene expression\n", "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", "> **Note**\n", ">\n", "> Code chunks run Python commands unless it starts with `%%bash`, in\n", "> which case, those chunks run shell commands.\n", "\n", "
\n", "\n", "In this tutorial we will cover differential gene expression, which\n", "comprises an extensive range of topics and methods. In single cell,\n", "differential expresison can have multiple functionalities such as\n", "identifying marker genes for cell populations, as well as identifying\n", "differentially regulated genes across conditions (healthy vs control).\n", "We will also cover controlling batch effect in your test.\n", "\n", "Differential expression is performed with the function rank_genes_group.\n", "The default method to compute differential expression is the\n", "t-test_overestim_var. Other implemented methods are: logreg, t-test and\n", "wilcoxon.\n", "\n", "By default, the .raw attribute of AnnData is used in case it has been\n", "initialized, it can be changed by setting use_raw=False.\n", "\n", "The clustering with resolution 0.6 seems to give a reasonable number of\n", "clusters, so we will use that clustering for all DE tests.\n", "\n", "First, let's import libraries and fetch the clustered data from the\n", "previous lab." ] }, { "cell_type": "code", "metadata": {}, "source": [ "import numpy as np\n", "import pandas as pd\n", "import scanpy as sc\n", "import gseapy\n", "import matplotlib.pyplot as plt\n", "import warnings\n", "import os\n", "import urllib.request\n", "\n", "warnings.simplefilter(action=\"ignore\", category=Warning)\n", "\n", "# verbosity: errors (0), warnings (1), info (2), hints (3)\n", "sc.settings.verbosity = 2\n", "\n", "sc.settings.set_figure_params(dpi=80)" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Read in the clustered data object." ] }, { "cell_type": "code", "metadata": {}, "source": [ "# download pre-computed data if missing or long compute\n", "fetch_data = True\n", "\n", "# url for source and intermediate data\n", "path_data = \"https://export.uppmax.uu.se/naiss2023-23-3/workshops/workshop-scrnaseq\"\n", "\n", "path_results = \"data/covid/results\"\n", "if not os.path.exists(path_results):\n", " os.makedirs(path_results, exist_ok=True)\n", "\n", "# path_file = \"data/covid/results/scanpy_covid_qc_dr_scanorama_cl.h5ad\"\n", "path_file = \"data/covid/results/scanpy_covid_qc_dr_scanorama_cl.h5ad\"\n", "if fetch_data and not os.path.exists(path_file):\n", " urllib.request.urlretrieve(os.path.join(\n", " path_data, 'covid/results/scanpy_covid_qc_dr_scanorama_cl.h5ad'), path_file)\n", "\n", "adata = sc.read_h5ad(path_file)\n", "adata" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": {}, "source": [ "print(adata.X.shape)\n", "print(adata.raw.X.shape)\n", "print(adata.raw.X[:10,:10])" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As you can see, the X matrix only contains the variable genes, while the\n", "raw matrix contains all genes.\n", "\n", "Printing a few of the values in adata.raw.X shows that the raw matrix is\n", "normalized.\n", "\n", "For DGE analysis we would like to run with all genes, on normalized\n", "values, so we will have to revert back to the raw matrix. In case you\n", "have raw counts in the matrix you also have to renormalize and\n", "logtransform." ] }, { "cell_type": "code", "metadata": {}, "source": [ "adata = adata.raw.to_adata()" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now lets look at the clustering of the object we loaded in the umap. We\n", "will use louvain_0.6 clustering in this exercise." ] }, { "cell_type": "code", "metadata": {}, "source": [ "sc.pl.umap(adata, color='louvain_0.6')" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## T-test" ] }, { "cell_type": "code", "metadata": {}, "source": [ "sc.tl.rank_genes_groups(adata, 'louvain_0.6', method='t-test', key_added = \"t-test\")\n", "sc.pl.rank_genes_groups(adata, n_genes=25, sharey=False, key = \"t-test\")\n", "\n", "# results are stored in the adata.uns[\"t-test\"] slot\n", "adata" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## T-test overestimated_variance" ] }, { "cell_type": "code", "metadata": {}, "source": [ "sc.tl.rank_genes_groups(adata, 'louvain_0.6', method='t-test_overestim_var', key_added = \"t-test_ov\")\n", "sc.pl.rank_genes_groups(adata, n_genes=25, sharey=False, key = \"t-test_ov\")" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Wilcoxon rank-sum\n", "\n", "The result of a Wilcoxon rank-sum (Mann-Whitney-U) test is very similar.\n", "We recommend using the latter in publications, see e.g., Sonison &\n", "Robinson (2018). You might also consider much more powerful differential\n", "testing packages like MAST, limma, DESeq2 and, for python, the recent\n", "diffxpy." ] }, { "cell_type": "code", "metadata": {}, "source": [ "sc.tl.rank_genes_groups(adata, 'louvain_0.6', method='wilcoxon', key_added = \"wilcoxon\")\n", "sc.pl.rank_genes_groups(adata, n_genes=25, sharey=False, key=\"wilcoxon\")" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Logistic regression test\n", "\n", "As an alternative, let us rank genes using logistic regression. For\n", "instance, this has been suggested by Natranos et al. (2018). The\n", "essential difference is that here, we use a multi-variate appraoch\n", "whereas conventional differential tests are uni-variate. Clark et\n", "al. (2014) has more details." ] }, { "cell_type": "code", "metadata": {}, "source": [ "sc.tl.rank_genes_groups(adata, 'louvain_0.6', method='logreg',key_added = \"logreg\")\n", "sc.pl.rank_genes_groups(adata, n_genes=25, sharey=False, key = \"logreg\")" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Compare genes\n", "\n", "Take all significant DE genes for cluster0 with each test and compare\n", "the overlap." ] }, { "cell_type": "code", "metadata": {}, "source": [ "#compare cluster1 genes, only stores top 100 by default\n", "\n", "wc = sc.get.rank_genes_groups_df(adata, group='0', key='wilcoxon', pval_cutoff=0.01, log2fc_min=0)['names']\n", "tt = sc.get.rank_genes_groups_df(adata, group='0', key='t-test', pval_cutoff=0.01, log2fc_min=0)['names']\n", "tt_ov = sc.get.rank_genes_groups_df(adata, group='0', key='t-test_ov', pval_cutoff=0.01, log2fc_min=0)['names']\n", "\n", "from matplotlib_venn import venn3\n", "\n", "venn3([set(wc),set(tt),set(tt_ov)], ('Wilcox','T-test','T-test_ov') )\n", "plt.show()" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As you can see, the Wilcoxon test and the T-test with overestimated\n", "variance gives very similar result. Also the regular T-test has good\n", "overlap.\n", "\n", "## Visualization\n", "\n", "There are several ways to visualize the expression of top DE genes. Here\n", "we will plot top 5 genes per cluster from Wilcoxon test as heatmap,\n", "dotplot, violin plot or matrix." ] }, { "cell_type": "code", "metadata": {}, "source": [ "sc.pl.rank_genes_groups_heatmap(adata, n_genes=5, key=\"wilcoxon\", groupby=\"louvain_0.6\", show_gene_labels=True)\n", "sc.pl.rank_genes_groups_dotplot(adata, n_genes=5, key=\"wilcoxon\", groupby=\"louvain_0.6\")\n", "sc.pl.rank_genes_groups_stacked_violin(adata, n_genes=5, key=\"wilcoxon\", groupby=\"louvain_0.6\")\n", "sc.pl.rank_genes_groups_matrixplot(adata, n_genes=5, key=\"wilcoxon\", groupby=\"louvain_0.6\")" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Compare specific clusters\n", "\n", "We can also do pairwise comparisons of individual clusters on one vs\n", "many clusters. For instance, clusters 1 & 2 have very similar expression\n", "profiles." ] }, { "cell_type": "code", "metadata": {}, "source": [ "sc.tl.rank_genes_groups(adata, 'louvain_0.6', groups=['1'], reference='2', method='wilcoxon')\n", "sc.pl.rank_genes_groups(adata, groups=['1'], n_genes=20)" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Plot as violins for those two groups." ] }, { "cell_type": "code", "metadata": {}, "source": [ "sc.pl.rank_genes_groups_violin(adata, groups='1', n_genes=10)\n", "\n", "# plot the same genes as violins across all the datasets.\n", "\n", "# convert numpy.recarray to list\n", "mynames = [x[0] for x in adata.uns['rank_genes_groups']['names'][:10]]\n", "sc.pl.stacked_violin(adata, mynames, groupby = 'louvain_0.6')" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## DGE across conditions\n", "\n", "The second way of computing differential expression is to answer which\n", "genes are differentially expressed within a cluster. For example, in our\n", "case we have libraries comming from patients and controls and we would\n", "like to know which genes are influenced the most in a particular cell\n", "type. For this end, we will first subset our data for the desired cell\n", "cluster, then change the cell identities to the variable of comparison\n", "(which now in our case is the **type**, e.g. Covid/Ctrl)." ] }, { "cell_type": "code", "metadata": {}, "source": [ "cl1 = adata[adata.obs['louvain_0.6'] == '4',:]\n", "cl1.obs['type'].value_counts()\n", "\n", "sc.tl.rank_genes_groups(cl1, 'type', method='wilcoxon', key_added = \"wilcoxon\")\n", "sc.pl.rank_genes_groups(cl1, n_genes=25, sharey=False, key=\"wilcoxon\")" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": {}, "source": [ "sc.pl.rank_genes_groups_violin(cl1, n_genes=10, key=\"wilcoxon\")" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can also plot these genes across all clusters, but split by \"type\",\n", "to check if the genes are also up/downregulated in other celltypes." ] }, { "cell_type": "code", "metadata": {}, "source": [ "import seaborn as sns\n", "\n", "genes1 = sc.get.rank_genes_groups_df(cl1, group='Covid', key='wilcoxon')['names'][:5]\n", "genes2 = sc.get.rank_genes_groups_df(cl1, group='Ctrl', key='wilcoxon')['names'][:5]\n", "genes = genes1.tolist() + genes2.tolist() \n", "df = sc.get.obs_df(adata, genes + ['louvain_0.6','type'], use_raw=False)\n", "df2 = df.melt(id_vars=[\"louvain_0.6\",'type'], value_vars=genes)\n", "\n", "sns.catplot(x = \"louvain_0.6\", y = \"value\", hue = \"type\", kind = 'violin', col = \"variable\", data = df2, col_wrap=4, inner=None)" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As you can see, we have many sex chromosome related genes among the top\n", "DE genes. And if you remember from the QC lab, we have inbalanced sex\n", "distribution among our subjects, so this may not be related to covid at\n", "all.\n", "\n", "### Remove sex chromosome genes\n", "\n", "To remove some of the bias due to inbalanced sex in the subjects we can\n", "remove the sex chromosome related genes." ] }, { "cell_type": "code", "metadata": {}, "source": [ "annot = sc.queries.biomart_annotations(\n", " \"hsapiens\",\n", " [\"ensembl_gene_id\", \"external_gene_name\", \"start_position\", \"end_position\", \"chromosome_name\"],\n", " ).set_index(\"external_gene_name\")\n", "\n", "chrY_genes = adata.var_names.intersection(annot.index[annot.chromosome_name == \"Y\"])\n", "chrX_genes = adata.var_names.intersection(annot.index[annot.chromosome_name == \"X\"])\n", "\n", "sex_genes = chrY_genes.union(chrX_genes)\n", "print(len(sex_genes))\n", "all_genes = cl1.var.index.tolist()\n", "print(len(all_genes))\n", "\n", "keep_genes = [x for x in all_genes if x not in sex_genes]\n", "print(len(keep_genes))\n", "\n", "cl1 = cl1[:,keep_genes]" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Rerun differential expression." ] }, { "cell_type": "code", "metadata": {}, "source": [ "sc.tl.rank_genes_groups(cl1, 'type', method='wilcoxon', key_added = \"wilcoxon\")\n", "sc.pl.rank_genes_groups(cl1, n_genes=25, sharey=False, key=\"wilcoxon\")" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Patient batch effects\n", "\n", "When we are testing for Covid vs Control we are running a DGE test for 3\n", "vs 3 individuals. That will be very sensitive to sample differences\n", "unless we find a way to control for it. So first, lets check how the top\n", "DGEs are expressed across the individuals:" ] }, { "cell_type": "code", "metadata": {}, "source": [ "genes1 = sc.get.rank_genes_groups_df(cl1, group='Covid', key='wilcoxon')['names'][:5]\n", "genes2 = sc.get.rank_genes_groups_df(cl1, group='Ctrl', key='wilcoxon')['names'][:5]\n", "genes = genes1.tolist() + genes2.tolist() \n", "\n", "sc.pl.violin(cl1, genes1, groupby='sample')\n", "sc.pl.violin(cl1, genes2, groupby='sample')" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As you can see, many of the genes detected as DGE in Covid are unique to\n", "one or 2 patients.\n", "\n", "We can also plot the top Covid and top Ctrl genes as a dotplot:" ] }, { "cell_type": "code", "metadata": {}, "source": [ "genes1 = sc.get.rank_genes_groups_df(cl1, group='Covid', key='wilcoxon')['names'][:20]\n", "genes2 = sc.get.rank_genes_groups_df(cl1, group='Ctrl', key='wilcoxon')['names'][:20]\n", "genes = genes1.tolist() + genes2.tolist() \n", "\n", "sc.pl.dotplot(cl1,genes, groupby='sample')" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Clearly many of the top Covid genes are only high in the covid_17\n", "sample, and not a general feature of covid patients.\n", "\n", "This is also the patient with the highest number of cells in this\n", "cluster:" ] }, { "cell_type": "code", "metadata": {}, "source": [ "cl1.obs['sample'].value_counts()" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Subsample\n", "\n", "So one obvious thing to consider is an equal amount of cells per\n", "individual so that the DGE results are not dominated by a single sample.\n", "\n", "So we will downsample to an equal number of cells per sample, in this\n", "case 34 cells per sample as it is the lowest number among all samples" ] }, { "cell_type": "code", "metadata": {}, "source": [ "target_cells = 37\n", "\n", "tmp = [cl1[cl1.obs['sample'] == s] for s in cl1.obs['sample'].cat.categories]\n", "\n", "for dat in tmp:\n", " if dat.n_obs > target_cells:\n", " sc.pp.subsample(dat, n_obs=target_cells)\n", "\n", "cl1_sub = tmp[0].concatenate(*tmp[1:])\n", "\n", "cl1_sub.obs['sample'].value_counts()" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": {}, "source": [ "sc.tl.rank_genes_groups(cl1_sub, 'type', method='wilcoxon', key_added = \"wilcoxon\")\n", "sc.pl.rank_genes_groups(cl1_sub, n_genes=25, sharey=False, key=\"wilcoxon\")" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": {}, "source": [ "genes1 = sc.get.rank_genes_groups_df(cl1_sub, group='Covid', key='wilcoxon')['names'][:20]\n", "genes2 = sc.get.rank_genes_groups_df(cl1_sub, group='Ctrl', key='wilcoxon')['names'][:20]\n", "genes = genes1.tolist() + genes2.tolist() \n", "\n", "sc.pl.dotplot(cl1,genes, groupby='sample')" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It looks much better now. But if we look per patient you can see that we\n", "still have some genes that are dominated by a single patient. Still, it\n", "is often a good idea to control the number of cells from each sample\n", "when doing differential expression.\n", "\n", "There are many different ways to try and resolve the issue of patient\n", "batch effects, however most of them require R packages. These can be run\n", "via rpy2 as is demonstraded in this compendium:\n", "https://www.sc-best-practices.org/conditions/differential_gene_expression.html\n", "\n", "However, we have not included it here as of now. So please have a look\n", "at the patient batch effect section in the seurat DGE tutorial where we\n", "run EdgeR on pseudobulk and MAST with random effect.\n", "\n", "## Gene Set Analysis (GSA)\n", "\n", "### Hypergeometric enrichment test\n", "\n", "Having a defined list of differentially expressed genes, you can now\n", "look for their combined function using hypergeometric test." ] }, { "cell_type": "code", "metadata": {}, "source": [ "#Available databases : ‘Human’, ‘Mouse’, ‘Yeast’, ‘Fly’, ‘Fish’, ‘Worm’ \n", "gene_set_names = gseapy.get_library_name(organism='Human')\n", "print(gene_set_names)" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Get the significant DEGs for the Covid patients." ] }, { "cell_type": "code", "metadata": {}, "source": [ "#?gseapy.enrichr\n", "glist = sc.get.rank_genes_groups_df(cl1_sub, group='Covid', key='wilcoxon', log2fc_min=0.25, pval_cutoff=0.05)['names'].squeeze().str.strip().tolist()\n", "print(len(glist))" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": {}, "source": [ "enr_res = gseapy.enrichr(gene_list=glist, organism='Human', gene_sets='GO_Biological_Process_2018', cutoff = 0.5)\n", "enr_res.results.head()" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Some databases of interest:\\\n", "`GO_Biological_Process_2017b``KEGG_2019_Human``KEGG_2019_Mouse``WikiPathways_2019_Human``WikiPathways_2019_Mouse`\\\n", "You visualize your results using a simple barplot, for example:" ] }, { "cell_type": "code", "metadata": {}, "source": [ "gseapy.barplot(enr_res.res2d,title='GO_Biological_Process_2018')" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Gene Set Enrichment Analysis (GSEA)\n", "\n", "Besides the enrichment using hypergeometric test, we can also perform\n", "gene set enrichment analysis (GSEA), which scores ranked genes list\n", "(usually based on fold changes) and computes permutation test to check\n", "if a particular gene set is more present in the Up-regulated genes,\n", "among the DOWN_regulated genes or not differentially regulated.\n", "\n", "We need a table with all DEGs and their log foldchanges. However, many\n", "lowly expressed genes will have high foldchanges and just contribue\n", "noise, so also filter for expression in enough cells." ] }, { "cell_type": "code", "metadata": {}, "source": [ "gene_rank = sc.get.rank_genes_groups_df(cl1_sub, group='Covid', key='wilcoxon')[['names','logfoldchanges']]\n", "gene_rank.sort_values(by=['logfoldchanges'], inplace=True, ascending=False)\n", "\n", "# calculate_qc_metrics will calculate number of cells per gene\n", "sc.pp.calculate_qc_metrics(cl1, percent_top=None, log1p=False, inplace=True)\n", "\n", "# filter for genes expressed in at least 30 cells.\n", "gene_rank = gene_rank[gene_rank['names'].isin(cl1.var_names[cl1.var.n_cells_by_counts>30])]\n", "\n", "gene_rank" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Once our list of genes are sorted, we can proceed with the enrichment\n", "itself. We can use the package to get gene set from the Molecular\n", "Signature Database (MSigDB) and select KEGG pathways as an example." ] }, { "cell_type": "code", "metadata": {}, "source": [ "#Available databases : ‘Human’, ‘Mouse’, ‘Yeast’, ‘Fly’, ‘Fish’, ‘Worm’ \n", "gene_set_names = gseapy.get_library_name(organism='Human')\n", "print(gene_set_names)" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Next, we will run GSEA. This will result in a table containing\n", "information for several pathways. We can then sort and filter those\n", "pathways to visualize only the top ones. You can select/filter them by\n", "either `p-value` or normalized enrichment score (`NES`)." ] }, { "cell_type": "code", "metadata": {}, "source": [ "res = gseapy.prerank(rnk=gene_rank, gene_sets='KEGG_2021_Human')\n", "\n", "terms = res.res2d.Term\n", "terms[:10]" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": {}, "source": [ "gseapy.gseaplot(rank_metric=res.ranking, term=terms[0], **res.results[terms[0]])" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", "> **Discuss**\n", ">\n", "> Which KEGG pathways are upregulated in this cluster? Which KEGG\n", "> pathways are dowregulated in this cluster? Change the pathway source\n", "> to another gene set (e.g. CP:WIKIPATHWAYS or CP:REACTOME or\n", "> CP:BIOCARTA or GO:BP) and check the if you get similar results?\n", "\n", "
\n", "\n", "Finally, let's save the integrated data for further analysis." ] }, { "cell_type": "code", "metadata": {}, "source": [ "adata.write_h5ad('./data/covid/results/scanpy_covid_qc_dr_scanorama_cl_dge.h5ad')" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Session info\n", "\n", "```{=html}\n", "
\n", "```\n", "```{=html}\n", "\n", "```\n", "Click here\n", "```{=html}\n", "\n", "```" ] }, { "cell_type": "code", "metadata": {}, "source": [ "sc.logging.print_versions()" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```{=html}\n", "
\n", "```" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 4 }