|
|
|
|
|
|
|
|
|
|
|
import cProfile |
|
from distutils import core |
|
from pathlib import Path |
|
import numpy as np |
|
import scipy as sp |
|
import pandas as pd |
|
import matplotlib.pyplot as plt |
|
from matplotlib.backends.backend_pdf import PdfPages |
|
import seaborn as sns |
|
import os |
|
import pickle |
|
import scipy.stats as stats |
|
import argparse |
|
from adjustText import adjust_text |
|
import matplotlib.backends.backend_pdf |
|
|
|
|
|
|
|
def main(): |
|
parser = argparse.ArgumentParser() |
|
parser.add_argument('-b', type = str, help = 'Path to barcodes') |
|
parser.add_argument('-xp', type = str, help = 'Experiment ID') |
|
parser.add_argument('-c', type = str, default = "D:\BCCAncer\FILES\codebook_0_C1E1_van.csv", help = 'Path to codebook') |
|
parser.add_argument('-a', type = str, default = "D:\BCCAncer\FILES\XP2474_4T1_C1E1_new_bulk.csv", help = 'Path to bulk file (abundance file)') |
|
parser.add_argument('-o', type = str, default = "D:\BCCAncer\EXP\XP7174\Correlations\BulkCorr", help = 'Path to save processed files') |
|
parser.add_argument('-is_cambridge', type = bool, default = False, help = 'Are the results for Cambridge datasets?') |
|
parser.add_argument('-drop_blanks', type = bool, default = False, help = 'Remove blanks before correlation') |
|
parser.add_argument('-log', type =bool, default = True, help = 'Do we want to take log while correlation of bulk?') |
|
parser.add_argument("-d", nargs="+", type = float, default=0.65, help = 'Max mean distance threshold for an area of detected barcode') |
|
parser.add_argument("-removeZ", nargs="+", type=int, default=None, help="Z slices to remove from evaluation") |
|
|
|
|
|
|
|
args = parser.parse_args() |
|
|
|
if not os.path.exists(args.o): |
|
os.makedirs(args.o) |
|
|
|
info_np = np.zeros(shape = (len(args.d), 7)) |
|
|
|
|
|
df = read_sheet(args.b) |
|
if args.removeZ is not None: |
|
removeZ_set = set(args.removeZ) |
|
df = df[~df['z'].isin(removeZ_set)] |
|
|
|
|
|
|
|
pdf = matplotlib.backends.backend_pdf.PdfPages(f'{args.o}/{args.xp}_correlation.pdf') |
|
correlation = Correlation(args.c, df, args.a, args.o, args.xp, args.is_cambridge, pdf) |
|
args.d.sort(reverse = True) |
|
|
|
|
|
for idx, dist_threshold in enumerate(args.d): |
|
filter_df = correlation.filter_distance(dist_threshold) |
|
gp_df = correlation.groupby(filter_df) |
|
gp_df = correlation.merge_df_cb(gp_df) |
|
|
|
tot_counts = gp_df.counts.sum() |
|
blank_counts = gp_df.loc[gp_df['gene_symbol'].isin(['Blank_01', 'Blank_02', 'Blank_03', 'Blank_04', 'Blank_05', 'Blank_06'])].counts.sum() |
|
|
|
info_np[idx][0] = dist_threshold |
|
info_np[idx][3] = int(tot_counts) |
|
info_np[idx][4] = int(blank_counts) |
|
info_np[idx][5] = int(len(gp_df)) |
|
|
|
gp_df = correlation.df_bulk(gp_df) |
|
|
|
if args.drop_blanks: |
|
gp_df = correlation.remove_blanks(gp_df) |
|
|
|
""" |
|
if args.gene_list: |
|
print('removing') |
|
gp_df = correlation.remove_specific_genes(gp_df) |
|
""" |
|
|
|
info_np[idx][-1] = len(gp_df) |
|
|
|
gp_df['log_counts'] = np.log2(gp_df['counts']+1) |
|
gp_df['log_tpm'] = np.log2(gp_df['bulk_exp']+0.0001) |
|
|
|
gp_df.to_csv(f'{args.o}/{args.xp}_{dist_threshold}.csv') |
|
|
|
|
|
info_np[idx][1], info_np[idx][2] = correlation.log_correlation(gp_df, dist_threshold) |
|
|
|
pdf.close() |
|
|
|
info_df = pd.DataFrame(info_np, columns = ['Distance Threshold',\ |
|
'Pearson correlation',\ |
|
'Spearman correlation',\ |
|
'# detected barcodes (including control barcodes)',\ |
|
'# detected control (blanks) barcodes',\ |
|
'# genes at dist threshold in correlation',\ |
|
'# barcodes counted towards correlaton estimation']) |
|
info_df.to_csv(f'{args.o}/info_{args.xp}.csv') |
|
|
|
def read_sheet(file): |
|
|
|
ext = file.split(".")[-1] |
|
if ext == "csv": |
|
df = pd.read_csv(file) |
|
elif ext == "tsv": |
|
df = pd.read_csv(file, '\t') |
|
elif ext in {"xls", "xlsx", "xlsm", "xlsb"}: |
|
df = pd.read_excel(file) |
|
else: |
|
raise ValueError("Unexpected file extension") |
|
return df |
|
|
|
class Correlation: |
|
def __init__(self, codebook, barcodes, bulk, output_dir, name, is_cambridge, pdf_object): |
|
self.codebook = read_sheet(codebook) |
|
self.barcodes = barcodes |
|
self.bulk = read_sheet(bulk) |
|
self.output_dir = output_dir |
|
self.name = name |
|
self.is_cambridge = is_cambridge |
|
self.pdf_object = pdf_object |
|
|
|
|
|
def filter_distance(self, distance_threshold): |
|
return self.barcodes.loc[self.barcodes['mean_distance']<distance_threshold] |
|
|
|
def groupby(self, df): |
|
return (df.groupby('barcode_id').size().reset_index(name='counts')) |
|
|
|
def modify_codebook(self): |
|
self.codebook['barcode_id'] = self.codebook.index |
|
self.codebook.rename(columns={"name": "gene_symbol"}, inplace = True) |
|
|
|
def merge_df_cb(self,df): |
|
self.modify_codebook() |
|
return pd.merge(self.codebook, df, how='inner', on='barcode_id') |
|
|
|
def df_bulk(self, df): |
|
return pd.merge(self.bulk, df, how='inner', on='gene_symbol') |
|
|
|
def remove_blanks(self,df): |
|
return df[df['bulk_exp'] != 0] |
|
|
|
""" |
|
def remove_specific_genes(self,df): |
|
c = 0 |
|
print(self.remove_genes_list) |
|
for gene in self.remove_genes_list: |
|
print(c, gene) |
|
df = df.loc[df['gene_symbol']!=gene] |
|
#cccprint(df.loc[df['gene_symbol']==gene]) |
|
c+=1 |
|
return df |
|
""" |
|
|
|
|
|
def log_correlation(self, df, dist_threshold): |
|
f1, ax = plt.subplots(figsize=(9, 9)) |
|
sns.set_palette("deep") |
|
sns.scatterplot(x="log_tpm",y="log_counts",data=df,ax=ax) |
|
|
|
if self.is_cambridge == True: |
|
count_type = "C_counts" |
|
else: count_type = "V_counts" |
|
|
|
|
|
ax.set_title("TPM Correlation for " + self.name, fontsize = 15) |
|
ax.set_xlabel("log2(TPM+1e-4), V_bulk", fontsize = 20) |
|
ax.set_ylabel("log2(# detected counts+1), "+ count_type, fontsize = 20) |
|
|
|
|
|
def plotlabel(xvar, yvar, label): |
|
ax.text(xvar+0.02, yvar, label) |
|
|
|
|
|
pearson, _ = stats.pearsonr(df["log_tpm"],df["log_counts"]) |
|
spearman, _ = stats.spearmanr(df["log_tpm"],df["log_counts"]) |
|
|
|
|
|
ax.text(.01, .95, 'Pearson = {:.2f}\nSpearman = {:.2f}'.format(pearson,spearman),transform=ax.transAxes) |
|
|
|
|
|
|
|
self.pdf_object.savefig(f1) |
|
|
|
texts = [] |
|
for xs,ys,label in zip(df['log_tpm'],df['log_counts'],df['gene_symbol']): |
|
texts.append(ax.text(xs,ys,label)) |
|
adjust_text(texts, force_points=0.2, force_text=0.2,expand_points=(1, 1), expand_text=(1, 1), arrowprops=dict(arrowstyle="-", color='black', lw=0.5)) |
|
plt.tight_layout() |
|
|
|
|
|
self.pdf_object.savefig(f1) |
|
|
|
return pearson, spearman |
|
|
|
|
|
if __name__ == '__main__': |
|
|
|
main() |
|
|