Advance Usage of SwiftCNV#
This notebook explains how to run SwiftCNV from a notebook using more advance parameters to fine tune the results.
import logging
import numpy as np
import pandas as pd
import swiftcnv as cnv
from swiftcnv.datasets import Qian2020_Ovarian
# Enable INFO level logging for verbosity
logging.basicConfig(level=logging.INFO, format='[%(levelname)s] %(name)s: %(message)s')
# Load example dataset
adata = Qian2020_Ovarian()
gtf_filename = 'gencode.v44.basic.annotation.gtf.gz'
# Run if needed
# gtf_url = 'https://ftp.ebi.ac.uk/pub/databases/gencode/Gencode_human/release_44/gencode.v44.basic.annotation.gtf.gz'
# 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!')
A cell annotation dataframe compatible with SwiftCNV can be generated using the function create_cell_annotation(). This function will also add a reference column to adata.obs layer.
cell_annotations = cnv.create_cell_annotation(
adata,
cell_type_key='cell_type',
sample_key='sample',
reference_cells=['T_cell', 'Macrophage', 'Fibroblast', 'Endothelial', 'B_cell']
)
cell_annotations.head()
| cell_name | reference | sample | |
|---|---|---|---|
| 0 | BT1303_TGATTTCAGATGGGTC | True | 11 |
| 1 | BT1303_TCTGGAACACAAGACG | True | 11 |
| 2 | BT1303_GGGCACTAGTATGACA | True | 11 |
| 3 | BT1303_CCTATTACACAAGTAA | True | 11 |
| 4 | BT1303_TTCTCAATCCTACAGA | True | 11 |
Alternatively, we can just add the reference column manually.
reference_cells=['T_cell', 'Macrophage', 'Fibroblast', 'Endothelial', 'B_cell']
adata.obs['reference'] = adata.obs['cell_type'].isin(reference_cells)
To run SwiftCNV manually, first create a SwiftCNV object with the input counts matrix, which will be converted to a scipy.sparse.csr_matrix. The cell_order pandas DataFrame must contain the columns cell_name, reference, and, optionally, sample. The gene_order pandas DataFrame must contain gene, chr, arm, chr_arm, start, and end. Both DataFrames can be generated from files using the helper functions get_cell_order() and get_gene_order().
counts = adata.X
counts, cell_order = cnv.get_cell_order(adata.obs, counts, adata.obs_names, column='reference', sample_col='sample')
counts, gene_order = cnv.get_gene_order(counts, adata.var_names, gtf_filename, exclude_immune=True, sex_chr=False)
obj = cnv.SwiftCNV(counts, cell_order, gene_order)
display(cell_order.head())
display(gene_order.head())
| cell_name | reference | sample | |
|---|---|---|---|
| 0 | BT1303_TGATTTCAGATGGGTC | True | 11 |
| 1 | BT1303_TCTGGAACACAAGACG | True | 11 |
| 2 | BT1303_GGGCACTAGTATGACA | True | 11 |
| 3 | BT1303_CCTATTACACAAGTAA | True | 11 |
| 4 | BT1303_TTCTCAATCCTACAGA | True | 11 |
| gene | chr | arm | chr_arm | start | end | |
|---|---|---|---|---|---|---|
| 120 | MTCO2P12 | chr1 | p | 1p | 632757 | 633438 |
| 198 | SAMD11 | chr1 | p | 1p | 923923 | 944575 |
| 201 | NOC2L | chr1 | p | 1p | 944203 | 959309 |
| 216 | HES4 | chr1 | p | 1p | 998962 | 1000172 |
| 219 | ISG15 | chr1 | p | 1p | 1001138 | 1014540 |
Run the CNV estimation with advanced parameters. Gene smoothing averages the value of each gene over a window of genes: bases_window in MB and genes_window in number of genes. If both are defined the shorter window to each direction applies, to avoid smoothing over distant genes and to increase resolution if many genes are available. If both are None (default) the windows are set to 30MB and 1% of the total remaining genes (with a minimum of 51).
cnv_scores = obj.run(
min_cells_per_gene=3, # Filter genes expressed in less than these cells
cutoff=0.1, # Filter genes below this normalized expression
bound_sd_amplifier=3.0, # Bound values to these times the std of the matrix (in log scale)
substract_reference_by_sample=False, # Substract the mean of the reference by each sample
smooth_by='arm', # Stratify gene smoothing by 'chr' or 'arm'
bases_window=None, # Window in MB for smoothing
genes_window=None, # Window in number of genes for smoothing
denoise=True, # Denoise low values that are likely noise
noise_filter=0.1, # Threshold to consider noise (|value| < noise_filter)
sd_amplifier=1.0, # Threshold to consider noise (|value| < std * sd_amplifier)
noise_logistic=True, # Smooth denoised values with a logistic function instead of a hard filter to zero
final_cap=1.5, # Hard clip to [-cap, cap] to the final values
inv_log=False, # Apply inverse log(x + 1) to the returned matrix (centered around 1 instead of 0)
)
run_from_adata is a helper function similar to the CLI. Additional arguments are passed to the main analysis (SwiftCNV.run).
adata = cnv.run_from_adata(
adata,
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,
cutoff=0.1
)
If an AnnData object is provided directly as input, the function returns a new AnnData object with the cnv_scores matrix added to adata.obsm["cnv_mat"]. Therefore here output_dir is optional.
adata
AnnData object with n_obs × n_vars = 4000 × 12000
obs: 'sample', 'cell_type', 'reference'
var: 'chr', 'arm', 'chr_arm', 'start', 'end', 'has_cnv'
obsm: 'X_umap', 'cnv_mat'