Malignant cell identification from SwiftCNV output

Malignant cell identification from SwiftCNV output#

This notebook demostrates how to identify malignant cells from the CNV matrix generated by swiftCNV and shows different functions on how to explore the results. It uses the classification logic described in SherlockCell, the complete pipeline for malignant cell classification.

import os
import sys
import scanpy as sc
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
import logging
import requests

import swiftcnv as cnv
from swiftcnv.datasets import Qian2020_Ovarian

logging.basicConfig(level=logging.INFO, datefmt='%H:%M:%S',
                    format='%(asctime)s [%(levelname)s]: %(message)s')

warnings.simplefilter('ignore')

sc.settings.set_figure_params(figsize=(4, 4))
sns.set_style("white")

We will first run SwiftCNV on the example dataset following the steps from the first tutorial.

gtf_filename = 'gencode.v44.basic.annotation.gtf.gz'
output_dir = 'example_output'

adata = Qian2020_Ovarian()
print(adata)
AnnData object with n_obs × n_vars = 4000 × 12000
    obs: 'sample', 'cell_type'
    obsm: 'X_umap'
sc.pl.umap(adata, color=['cell_type', 'sample'], wspace=0.5, frameon=False)
if os.path.exists(gtf_filename):
    print(f"File '{gtf_filename}' already exists. Skipping download.")
else:
    print('Downloading file...')
    with requests.get(gtf_url, stream=True) as r:
        r.raise_for_status()
        with open(gtf_filename, 'wb') as f:
            for chunk in r.iter_content(chunk_size=8192): 
                f.write(chunk)
    print('Download finished!')
File 'gencode.v44.basic.annotation.gtf.gz' already exists. Skipping download.

For speed we will skip HMM analysis and plotting.

adata = cnv.run_from_adata(
    adata,
    output_dir=output_dir,
    gtf_file=gtf_filename,
    reference_col='cell_type',
    reference_vals=['T_cell', 'Macrophage', 'Fibroblast', 'Endothelial', 'B_cell'],
    sample_col='sample',
    exclude_immune=True,
    read_X=True,
    plot=False,
    run_hmm=False,
    cutoff=0.1
)

Now we smooth the CNV matrix by chromosome arm.

cnv.summarise_by_var(adata, obsm_key='cnv_mat', by='chr_arm', key_added='cnv_mat_arms', inplace=True)
adata.obsm['cnv_mat_arms'].shape
(4000, 39)

Running Malignant Classification#

For the classification, we have to specify what kind of samples we have (either 'Normal' or 'Tumor'). In our case, all the samples are from tumor biopsies.

adata.obs['sample_type'] = 'Tumor'
classifier = cnv.MalignantClassifier(adata, 
                                    sample_key= 'sample', 
                                    cell_type_key= 'cell_type', 
                                    cell_of_origin= "Epithelial", 
                                    sample_type_key= 'sample_type', 
                                    outdir=output_dir)

Enabling report= True will generate a pdf with the classification report for each sample in the specified output directory. As mentioned above, the classification steps and the logic behind are explained here.

adata = classifier.run_classification(n_jobs=3, embedding_key='X_umap', report=True, verbose=True)

Plotting classification results#

The classifier calculates 3 independent malignancy scores from the CNV matrix to create a CNV-based classification. The distribution of these scores can be visualised with the plot_CNV_density function.

cnv.plot_CNV_density(adata, sample_key='sample', sample_name='14', figsize=(12, 5))

This initial classification is further refined with a KNN and a density based algorithm. The results at each step can be shown in the UMAP plot.

sc.pl.umap(adata, color=['CNV_classif', 'knn_classif', 'dbscan_outlier'], wspace=0.75)

The final malignant classification results is stored in malignant_classif. Additionally, an aggregated malignant score is calculated by averaging the 3 scores.

sc.pl.umap(adata, color=['malignant_classif', 'malignant_score'], wspace=0.7, cmap='viridis')

A summary of the malignant annotation process with the CNV heatmap is obtained with plot_cnv_by_sample.

hotspotarms_dict = (classifier.master_hotspotarms_df.loc[classifier.master_hotspotarms_df['hotspotarm'] == 'Yes']
    .groupby('sample')['chrarms']
    .agg(lambda x: x.unique())
    .to_dict()
    )


cnv.plot_cnv_by_sample(adata, 
                       cell_type_key = 'cell_type', 
                       group_key='sample', 
                       sample_name='14',
                       highlight_arms= hotspotarms_dict, 
                       figsize=(18,9))

The heatmaps for all the samples are genereted in the CNV_heatmaps_samples.pdf classification report.

Finally, the plot_alluvial function shows whihc original cell types were annotated as malignant

cnv.plot_alluvial(adata, cell_type_key='cell_type')