|
| 1 | +from typing import Optional |
| 2 | +import pandas as pd |
| 3 | +from scipy.sparse import issparse |
| 4 | +from anndata import AnnData |
| 5 | +from scanpy import logging |
| 6 | +import os |
| 7 | +from multiprocessing import cpu_count |
| 8 | + |
| 9 | + |
| 10 | +def copykat( |
| 11 | + adata: AnnData, |
| 12 | + gene_ids: str = "S", |
| 13 | + segmentation_cut: float = 0.1, |
| 14 | + distance: str = "euclidean", |
| 15 | + s_name: str = "copykat_result", |
| 16 | + min_genes_chr: int = 5, |
| 17 | + key_added: str = "cnv", |
| 18 | + inplace: bool = True, |
| 19 | + layer: str = None, |
| 20 | + n_jobs: Optional[int] = None, |
| 21 | +) -> pd.DataFrame: |
| 22 | + """Inference of genomic copy number and subclonal structure. |
| 23 | +
|
| 24 | + Runs CopyKAT (Copynumber Karyotyping of Tumors) :cite:`Gao2021` based on integrative |
| 25 | + Bayesian approaches to identify genome-wide aneuploidy at 5MB resolution |
| 26 | + in single cells to separate tumor cells from normal cells, and tumor |
| 27 | + subclones using high-throughput sc-RNAseq data. |
| 28 | +
|
| 29 | + Note on input data from the original authors: |
| 30 | +
|
| 31 | + The matrix values are often the count of unique molecular identifier (UMI) |
| 32 | + from nowadays high througput single cell RNAseq data. The early generation of |
| 33 | + scRNAseq data may be summarized as TPM values or total read counts, |
| 34 | + which should also work. |
| 35 | +
|
| 36 | + This means that unlike for :func:`infercnvpy.tl.infercnv` the input data |
| 37 | + should not be log-transformed. |
| 38 | +
|
| 39 | + CopyKAT also does NOT require running :func:`infercnvpy.io.genomic_position_from_gtf`, |
| 40 | + it infers the genomic position from the gene symbols in `adata.var_names`. |
| 41 | +
|
| 42 | + You can find more info on GitHub: https://github.com/navinlabcode/copykat |
| 43 | +
|
| 44 | + Parameters |
| 45 | + ---------- |
| 46 | + adata |
| 47 | + annotated data matrix |
| 48 | + key_added |
| 49 | + Key under which the copyKAT scores will be stored in `adata.obsm` and `adata.uns`. |
| 50 | + inplace |
| 51 | + If True, store the result in adata, otherwise return it. |
| 52 | + gene_ids |
| 53 | + gene id type: Symbol ("S") or Ensemble ("E"). |
| 54 | + segmentation_cut |
| 55 | + segmentation parameters, input 0 to 1; larger looser criteria. |
| 56 | + distance |
| 57 | + distance methods include "euclidean", and correlation coverted distance include "pearson" and "spearman". |
| 58 | + s_name |
| 59 | + sample (output file) name. |
| 60 | + min_genes_chr |
| 61 | + minimal number of genes per chromosome for cell filtering. |
| 62 | + n_jobs |
| 63 | + Number of cores to use for copyKAT analysis. Per default, uses all cores |
| 64 | + available on the system. Multithreading does not work on Windows and this |
| 65 | + value will be ignored. |
| 66 | +
|
| 67 | + Returns |
| 68 | + ------- |
| 69 | + Depending on the value of `inplace`, either returns `None` or a vector |
| 70 | + with scores. |
| 71 | + """ |
| 72 | + |
| 73 | + if n_jobs is None: |
| 74 | + n_jobs = cpu_count() |
| 75 | + if os.name != "posix": |
| 76 | + n_jobs = 1 |
| 77 | + |
| 78 | + try: |
| 79 | + from rpy2.robjects.packages import importr |
| 80 | + from rpy2.robjects import pandas2ri, numpy2ri |
| 81 | + from rpy2.robjects.conversion import localconverter |
| 82 | + from rpy2 import robjects as ro |
| 83 | + except ImportError: |
| 84 | + raise ImportError("copyKAT requires rpy2 to be installed. ") |
| 85 | + |
| 86 | + try: |
| 87 | + copyKAT = importr("copykat") |
| 88 | + except ImportError: |
| 89 | + raise ImportError( |
| 90 | + "copyKAT requires a valid R installation with the following packages: " |
| 91 | + "copykat" |
| 92 | + ) |
| 93 | + |
| 94 | + logging.info("Preparing R objects") |
| 95 | + with localconverter(ro.default_converter + numpy2ri.converter): |
| 96 | + expr = adata.X if layer is None else tmp_adata.layers[layer] |
| 97 | + if issparse(expr): |
| 98 | + expr = expr.T.toarray() |
| 99 | + else: |
| 100 | + expr = expr.T |
| 101 | + ro.globalenv["expr_r"] = ro.conversion.py2rpy(expr) |
| 102 | + ro.globalenv["gene_names"] = ro.conversion.py2rpy(list(adata.var.index)) |
| 103 | + ro.globalenv["cell_IDs"] = ro.conversion.py2rpy(list(adata.obs.index)) |
| 104 | + ro.globalenv["n_jobs"] = ro.conversion.py2rpy(n_jobs) |
| 105 | + ro.globalenv["gene_ids"] = ro.conversion.py2rpy(gene_ids) |
| 106 | + ro.globalenv["segmentation_cut"] = ro.conversion.py2rpy(segmentation_cut) |
| 107 | + ro.globalenv["distance"] = ro.conversion.py2rpy(distance) |
| 108 | + ro.globalenv["s_name"] = ro.conversion.py2rpy(s_name) |
| 109 | + ro.globalenv["min_gene_chr"] = ro.conversion.py2rpy(min_genes_chr) |
| 110 | + |
| 111 | + logging.info("Running copyKAT") |
| 112 | + ro.r( |
| 113 | + f""" |
| 114 | + rownames(expr_r) <- gene_names |
| 115 | + colnames(expr_r) <- cell_IDs |
| 116 | + copyKAT_run <- copykat(rawmat = expr_r, id.type = gene_ids, ngene.chr = min_gene_chr, win.size = 25, |
| 117 | + KS.cut = segmentation_cut, sam.name = s_name, distance = distance, norm.cell.names = "", |
| 118 | + n.cores = n_jobs, output.seg = FALSE) |
| 119 | + copyKAT_result <- copyKAT_run$CNAmat |
| 120 | + colnames(copyKAT_result) <- c('chrom', 'chrompos', 'abspos', cell_IDs) |
| 121 | + """ |
| 122 | + ) |
| 123 | + |
| 124 | + with localconverter( |
| 125 | + ro.default_converter + numpy2ri.converter + pandas2ri.converter |
| 126 | + ): |
| 127 | + copyKAT_result = ro.conversion.rpy2py(ro.globalenv["copyKAT_result"]) |
| 128 | + |
| 129 | + chrom_pos = { |
| 130 | + "chr_pos": { |
| 131 | + f"chr{chrom}": int(pos) |
| 132 | + for pos, chrom in copyKAT_result.loc[:, ["chrom"]] |
| 133 | + .drop_duplicates() |
| 134 | + .itertuples() |
| 135 | + } |
| 136 | + } |
| 137 | + |
| 138 | + # Drop cols |
| 139 | + new_cpkat = copyKAT_result.drop(["chrom", "chrompos", "abspos"], axis=1).values |
| 140 | + |
| 141 | + # transpose |
| 142 | + new_cpkat_trans = new_cpkat.T |
| 143 | + |
| 144 | + if inplace: |
| 145 | + adata.uns[key_added] = chrom_pos |
| 146 | + adata.obsm["X_%s" % key_added] = new_cpkat_trans |
| 147 | + else: |
| 148 | + return new_cpkat_trans |
0 commit comments