Markov Affinity-based Graph Imputation of Cells (MAGIC) is an algorithm for denoising and transcript recover of single cells applied to single-cell RNA sequencing data, as described in Van Dijk D et al. (2018), Recovering Gene Interactions from Single-Cell Data Using Data Diffusion, Cell https://www.cell.com/cell/abstract/S0092-8674(18)30724-4.
This tutorial shows loading, preprocessing, MAGIC imputation and visualization of myeloid and erythroid cells in mouse bone marrow, as described by Paul et al., 2015. You can edit it yourself at https://colab.research.google.com/github/KrishnaswamyLab/MAGIC/blob/master/python/tutorial_notebooks/bonemarrow_tutorial.ipynb
Installation
Loading data
Data preprocessing
Running MAGIC
Visualizing gene-gene interactions
Visualizing cell trajectories with PCA on MAGIC and PHATE
Using MAGIC data in downstream analysis
If you haven't yet installed MAGIC, we can install it directly from this Jupyter Notebook.
!pip install --user magic-impute
Here, we'll import MAGIC along with other popular packages that will come in handy.
import magic
import scprep
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
# Matplotlib command for Jupyter notebooks only
%matplotlib inline
Load your data using one of the following scprep.io
methods: load_csv
, load_tsv
, load_fcs
, load_mtx
, load_10x
. You can read about how to use them with help(scprep.io.load_csv)
or on https://scprep.readthedocs.io/.
bmmsc_data = scprep.io.load_csv('https://github.com/KrishnaswamyLab/PHATE/raw/master/data/BMMC_myeloid.csv.gz')
bmmsc_data.head()
scprep.plot.plot_library_size(bmmsc_data, cutoff=1000)
bmmsc_data = scprep.filter.filter_library_size(bmmsc_data, cutoff=1000)
bmmsc_data.head()
We should also remove genes that are not expressed above a certain threshold, since they are not adding anything valuable to our analysis.
bmmsc_data = scprep.filter.filter_rare_genes(bmmsc_data, min_cells=10)
bmmsc_data.head()
After filtering, the next steps are to perform library size normalization and transformation. Log transformation is frequently used for single-cell RNA-seq, however, this requires the addition of a pseudocount to avoid infinite values at zero. We instead use a square root transform, which has similar properties to the log transform but has no problem with zeroes.
bmmsc_data = scprep.normalize.library_size_normalize(bmmsc_data)
bmmsc_data = scprep.transform.sqrt(bmmsc_data)
bmmsc_data.head()
magic_op = magic.MAGIC()
The magic_op.fit_transform function takes the normalized data and an array of selected genes as its arguments. If no genes are provided, MAGIC will return a matrix of all genes. The same can be achieved by substituting the array of gene names with genes='all_genes'
.
bmmsc_magic = magic_op.fit_transform(bmmsc_data, genes=["Mpo", "Klf1", "Ifitm1"])
bmmsc_magic.head()
We can see gene-gene relationships much more clearly after applying MAGIC. Note that the change in absolute values of gene expression is not meaningful - the relative difference is all that matters.
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(16, 6))
scprep.plot.scatter(x=bmmsc_data['Mpo'], y=bmmsc_data['Klf1'], c=bmmsc_data['Ifitm1'], ax=ax1,
xlabel='Mpo', ylabel='Klf1', legend_title="Ifitm1", title='Before MAGIC')
scprep.plot.scatter(x=bmmsc_magic['Mpo'], y=bmmsc_magic['Klf1'], c=bmmsc_magic['Ifitm1'], ax=ax2,
xlabel='Mpo', ylabel='Klf1', legend_title="Ifitm1", title='After MAGIC')
plt.tight_layout()
plt.show()
The original data suffers from dropout to the point that we cannot infer anything about the gene-gene relationships. As you can see, the gene-gene relationships are much clearer after MAGIC. These relationships also match the biological progression we expect to see - Ifitm1 is a stem cell marker, Klf1 is an erythroid marker, and Mpo is a myeloid marker.
If you wish to modify any parameters for your MAGIC operator, you change do so without having to recompute intermediate values using the magic_op.set_params
method. Since our gene-gene relationship here appears a little too noisy, we can increase t
a little from the default value of 3
up to a larger value like 5
.
magic_op.set_params(t=5)
We can now run MAGIC on the data again with the new parameters. Given that we have already fitted our MAGIC operator to the data, we should run the magic_op.transform
method.
bmmsc_magic = magic_op.transform(genes=["Mpo", "Klf1", "Ifitm1"])
bmmsc_magic.head()
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(16, 6))
scprep.plot.scatter(x=bmmsc_data['Mpo'], y=bmmsc_data['Klf1'], c=bmmsc_data['Ifitm1'], ax=ax1,
xlabel='Mpo', ylabel='Klf1', legend_title="Ifitm1", title='Before MAGIC')
scprep.plot.scatter(x=bmmsc_magic['Mpo'], y=bmmsc_magic['Klf1'], c=bmmsc_magic['Ifitm1'], ax=ax2,
xlabel='Mpo', ylabel='Klf1', legend_title="Ifitm1", title='After MAGIC')
plt.tight_layout()
plt.show()
That looks better. The gene-gene relationships are restored without smoothing so far as to remove structure.
We can extract the principal components of the smoothed data by passing the keyword genes='pca_only'
and use this for visualizing the data.
bmmsc_magic_pca = magic_op.transform(genes="pca_only")
bmmsc_magic_pca.head()
We'll also perform PCA on the raw data for comparison.
from sklearn.decomposition import PCA
bmmsc_pca = PCA(n_components=3).fit_transform(np.array(bmmsc_data))
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(16, 6))
scprep.plot.scatter2d(bmmsc_pca, c=bmmsc_data['Ifitm1'],
label_prefix="PC", title='PCA without MAGIC',
legend_title="Ifitm1", ax=ax1, ticks=False)
scprep.plot.scatter2d(bmmsc_magic_pca, c=bmmsc_magic['Ifitm1'],
label_prefix="PC", title='PCA with MAGIC',
legend_title="Ifitm1", ax=ax2, ticks=False)
plt.tight_layout()
plt.show()
We can also plot this in 3D.
from mpl_toolkits.mplot3d import Axes3D
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(16, 6), subplot_kw={'projection':'3d'})
scprep.plot.scatter3d(bmmsc_pca, c=bmmsc_data['Ifitm1'],
label_prefix="PC", title='PCA without MAGIC',
legend_title="Ifitm1", ax=ax1, ticks=False)
scprep.plot.scatter3d(bmmsc_magic_pca, c=bmmsc_magic['Ifitm1'],
label_prefix="PC", title='PCA with MAGIC',
legend_title="Ifitm1", ax=ax2, ticks=False)
plt.tight_layout()
plt.show()
In complex systems, two dimensions of PCA are not sufficient to view the entire space. For this, PHATE is a suitable visualization tool which works hand in hand with MAGIC to view how gene expression evolves along a trajectory. For this, you will need to have installed PHATE. For help using PHATE, visit https://phate.readthedocs.io/.
!pip install --user phate
import phate
data_phate = phate.PHATE().fit_transform(bmmsc_data)
scprep.plot.scatter2d(data_phate, c=bmmsc_magic['Ifitm1'], figsize=(12,9),
ticks=False, label_prefix="PHATE", legend_title="Ifitm1")
Note that the structure of the data that we see here is much more subtle than in PCA. We see multiple branches at both ends of the trajectory. To learn more about PHATE, visit https://phate.readthedocs.io/.
If we are imputing many genes at once, we can speed this process up with the argument solver='approximate'
, which applies denoising in the PCA space and then projects these denoised principal components back onto the genes of interest. Note that this may return some small negative values. You will see below, however, that the results are largely similar to exact MAGIC.
approx_magic_op = magic.MAGIC(solver="approximate")
approx_bmmsc_magic = approx_magic_op.fit_transform(bmmsc_data, genes='all_genes')
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(16, 6))
scprep.plot.scatter(x=bmmsc_magic['Mpo'], y=bmmsc_magic['Klf1'], c=bmmsc_magic['Ifitm1'], ax=ax1,
xlabel='Mpo', ylabel='Klf1', legend_title="Ifitm1", title='Exact MAGIC')
scprep.plot.scatter(x=approx_bmmsc_magic['Mpo'], y=approx_bmmsc_magic['Klf1'], c=approx_bmmsc_magic['Ifitm1'], ax=ax2,
xlabel='Mpo', ylabel='Klf1', legend_title="Ifitm1", title='Approximate MAGIC')
plt.tight_layout()
plt.show()
To visualize what it means to set t
in MAGIC, we can plot an animation of the smoothing process, from raw to imputed values. Below, we show an animation of Mpo, Klf1 and Ifitm1 with increasingly more smoothing.
magic.plot.animate_magic(bmmsc_data, gene_x="Mpo", gene_y="Klf1", gene_color="Ifitm1",
operator=magic_op, t_max=10)