CALDER_hierarchy.R 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. ############################################################
  2. get_gene_info <- function(genome) {
  3. if(genome == 'hg19') {
  4. gene_info_file = system.file("extdata", "TxDb.Hsapiens.UCSC.hg19.knownGene.rds", package = 'CALDER')
  5. } else if(genome == 'mm9') {
  6. gene_info_file = system.file("extdata", "TxDb.Mmusculus.UCSC.mm9.knownGene.rds", package = 'CALDER')
  7. } else {
  8. stop(paste0("Unknown genome (", genome, ")"))
  9. }
  10. gene_info = readRDS(gene_info_file)
  11. }
  12. CALDER_CD_hierarchy = function(contact_mat_file,
  13. chr,
  14. bin_size,
  15. save_dir,
  16. save_intermediate_data=FALSE,
  17. genome = 'hg19')
  18. {
  19. time0 = Sys.time()
  20. log_file = paste0(save_dir, '/chr', chr, '_log.txt')
  21. cat('\n')
  22. cat('>>>> Begin process contact matrix and compute correlation score at:', as.character(Sys.time()), '\n', file=log_file, append=FALSE)
  23. cat('>>>> Begin process contact matrix and compute correlation score at:', as.character(Sys.time()), '\n')
  24. processed_data = contact_mat_processing(contact_mat_file, bin_size=bin_size)
  25. A_oe = processed_data$A_oe
  26. ccA_oe_compressed_log_atanh = processed_data$atanh_score
  27. cat('\r', '>>>> Finish process contact matrix and compute correlation score at:', as.character(Sys.time()))
  28. cat('>>>> Finish process contact matrix and compute correlation score at:', as.character(Sys.time()), '\n', file=log_file, append=TRUE)
  29. p_thresh = ifelse(bin_size < 40000, 0.05, 1)
  30. window.sizes = 3
  31. compartments = vector("list", 2)
  32. chr_name = paste0("chr", chr)
  33. cat('>>>> Begin compute compartment domains and their hierachy at:', as.character(Sys.time()), '\n', file=log_file, append=TRUE)
  34. cat('\r', '>>>> Begin compute compartment domains and their hierachy at:', as.character(Sys.time()))
  35. compartments[[2]] = generate_compartments_bed(chr = chr, bin_size = bin_size, window.sizes = window.sizes, ccA_oe_compressed_log_atanh, p_thresh, out_file_name = NULL, stat_window_size = NULL)
  36. topDom_output = compartments[[2]]
  37. bin_names = rownames(A_oe)
  38. A_oe = as.matrix(A_oe)
  39. initial_clusters = apply(topDom_output$domain[, c("from.id", "to.id")], 1, function(v) v[1]:v[2])
  40. if (sum(sapply(initial_clusters, length)) != max(unlist(initial_clusters))) {
  41. stop(CELL_LINE, " initial_clusters error in topDom")
  42. }
  43. n_clusters = length(initial_clusters)
  44. A_oe_cluster_mean = HighResolution2Low_k_rectangle(A_oe, initial_clusters, initial_clusters, sum_or_mean = "mean")
  45. trend_mean_list = lapply( 1:4, function(v) 1*(A_oe_cluster_mean[, -(1:v)] > A_oe_cluster_mean[, - n_clusters - 1 + (v:1)]) )
  46. trend_mean = do.call(cbind, trend_mean_list)
  47. c_trend_mean = cor(t(trend_mean))
  48. atanh_c_trend_mean= atanh(c_trend_mean / (1+1E-7))
  49. # if(to_scale)
  50. {
  51. trend_mean = scale(trend_mean)
  52. c_trend_mean = scale(c_trend_mean)
  53. atanh_c_trend_mean= scale(atanh_c_trend_mean)
  54. }
  55. PC_12_atanh = get_PCs(atanh_c_trend_mean, which=1:10)
  56. PC_12_atanh[, 2:10] = PC_12_atanh[, 2:10]/5 ## xx-xx-xxxx: compress PC2
  57. rownames(PC_12_atanh) = 1:nrow(PC_12_atanh)
  58. ############################################################
  59. PC_direction = 1
  60. gene_info <- get_gene_info(genome)
  61. ## switch PC direction based on gene density
  62. {
  63. initial_clusters_ori_bins = lapply(initial_clusters, function(v) as.numeric(bin_names[v]))
  64. chr_bin_pc = data.table::data.table(chr=chr_name, bin=unlist(initial_clusters_ori_bins), PC1_val=rep(PC_12_atanh[,1], sapply(initial_clusters_ori_bins, length)))
  65. chr_bin_pc$start = (chr_bin_pc$bin - 1)*bin_size + 1
  66. chr_bin_pc$end = chr_bin_pc$bin*bin_size
  67. chr_bin_pc_range = makeGRangesFromDataFrame(chr_bin_pc, keep.extra.columns=TRUE)
  68. gene_info_chr = subset(gene_info, seqnames==chr_name)
  69. refGR = chr_bin_pc_range
  70. testGR = gene_info_chr
  71. hits <- findOverlaps(refGR, testGR)
  72. overlaps <- pintersect(refGR[queryHits(hits)], testGR[subjectHits(hits)])
  73. overlaps_bins = unique(data.table::data.table(overlap_ratio=width(overlaps)/bin_size, bin=overlaps$bin))
  74. bin_pc_gene_coverage = merge(chr_bin_pc, overlaps_bins, all.x=TRUE)
  75. bin_pc_gene_coverage$overlap_ratio[is.na(bin_pc_gene_coverage$overlap_ratio)] = 0
  76. gene_density_cor = cor(method='spearman', subset(bin_pc_gene_coverage, (PC1_val < quantile(PC1_val, 0.25)) | (PC1_val > quantile(PC1_val, 0.75)) , c('PC1_val', 'overlap_ratio')))[1,2]
  77. if(abs(gene_density_cor) < 0.2) warning('correlation between gene density and PC1 is too weak')
  78. PC_direction = PC_direction*sign(gene_density_cor)
  79. PC_12_atanh = PC_12_atanh*PC_direction
  80. }
  81. project_info = project_to_major_axis(PC_12_atanh)
  82. x_pro = project_info$x_pro
  83. ############################################################
  84. hc_disect_kmeans_PC12 = bisecting_kmeans(PC_12_atanh[, 1:10, drop=FALSE])
  85. hc_hybrid_PC12 = hc_disect_kmeans_PC12
  86. {
  87. reordered_names = reorder_dendro(hc_hybrid_PC12, x_pro, aggregateFun=mean)
  88. hc_hybrid_PC12_reordered = dendextend::rotate(hc_hybrid_PC12, reordered_names)
  89. hc_hybrid_x_pro = hc_disect_kmeans_PC12
  90. reordered_names_x_pro = get_best_reorder(hc_hybrid_x_pro, x_pro)
  91. CALDER_hc = dendextend::rotate(hc_hybrid_x_pro, reordered_names_x_pro)
  92. }
  93. ############################################################
  94. parameters = list(bin_size = bin_size, p_thresh = p_thresh)
  95. res = list( CALDER_hc=CALDER_hc, initial_clusters=initial_clusters, bin_names=bin_names, x_pro=x_pro, parameters=parameters)
  96. intermediate_data_file = paste0(save_dir, '/chr', chr, '_intermediate_data.Rds')
  97. hc = res$CALDER_hc
  98. hc_k_labels_full = try(get_cluser_levels(hc, k_clusters=Inf, balanced_4_clusters=FALSE)$cluster_labels)
  99. bin_comp = data.table::data.table(chr=chr, bin_index=res$bin_names, comp=rep(hc_k_labels_full, sapply(res$initial_clusters, length)))
  100. rownames(bin_comp) = NULL
  101. res$comp = bin_comp
  102. res$CDs = lapply(res$initial_clusters, function(v) res$bin_names[v])
  103. res$mat = A_oe
  104. res$chr = chr
  105. generate_hierachy_bed(chr=chr, res=res, save_dir=save_dir, bin_size=bin_size)
  106. cat('>>>> Finish compute compartment domains and their hierachy at: ', as.character(Sys.time()), '\n', file=log_file, append=TRUE)
  107. cat('\r', '>>>> Finish compute compartment domains and their hierachy at: ', as.character(Sys.time()))
  108. if(abs(gene_density_cor) < 0.2) cat('WARNING: correlation between gene density and PC1 on this chr is: ', substr(gene_density_cor, 1, 4), ', which is a bit low', '\n', file=log_file, append=TRUE)
  109. time1 = Sys.time()
  110. # delta_time = gsub('Time difference of', 'Total time used for computing compartment domains and their hierachy:', print(time1 - time0))
  111. delta_time <- time1 - time0
  112. timediff <- format(round(delta_time, 2), nsmall = 2)
  113. cat('\n\n', 'Total time used for computing compartment domains and their hierachy:', timediff, '\n', file=log_file, append=TRUE)
  114. # if(abs(gene_density_cor) > 0.2) cat('The gene density and PC1 correlation on this chr is: ', substr(gene_density_cor, 1, 4), '\n', file=log_file, append=TRUE)
  115. ############################################################
  116. intermediate_data = res
  117. if(save_intermediate_data==TRUE) saveRDS(intermediate_data, file=intermediate_data_file)
  118. # cat(intermediate_data_file)
  119. return(intermediate_data)
  120. }
  121. CALDER_sub_domains = function(intermediate_data_file=NULL, intermediate_data=NULL, chr, save_dir, bin_size)
  122. {
  123. time0 = Sys.time()
  124. log_file = paste0(save_dir, '/chr', chr, '_sub_domains_log.txt')
  125. cat('\r', '>>>> Begin compute sub-domains at:', as.character(Sys.time()))
  126. cat('>>>> Begin compute sub-domains at:', as.character(Sys.time()), '\n', file=log_file, append=FALSE)
  127. if(is.null(intermediate_data)) intermediate_data = readRDS(intermediate_data_file)
  128. {
  129. if(intermediate_data$chr!=chr) stop('intermediate_data$chr!=chr; check your input parameters\n')
  130. if( !setequal(rownames(intermediate_data$mat), intermediate_data$bin_names) ) stop('!setequal(rownames(intermediate_data$mat), intermediate_data$bin_names) \n')
  131. compartment_segs = generate_compartment_segs( intermediate_data$initial_clusters )
  132. cat('\r', '>>>> Begin compute sub-domains within each compartment domain at:', as.character(Sys.time()))
  133. cat('>>>> Begin compute sub-domains within each compartment domain at:', as.character(Sys.time()), '\n', file=log_file, append=TRUE)
  134. sub_domains_raw = HRG_zigzag_compartment_domain_main_fun(intermediate_data$mat, './', compartment_segs, min_n_bins=2)
  135. no_output = post_process_sub_domains(chr, sub_domains_raw, ncores=1, out_dir=save_dir, bin_size=bin_size)
  136. cat('>>>> Finish compute sub-domains within each compartment domain at:', as.character(Sys.time()), '\n', file=log_file, append=TRUE)
  137. cat('\r', '>>>> Finish compute sub-domains within each compartment domain at:', as.character(Sys.time()), '\n')
  138. time1 = Sys.time()
  139. # delta_time = gsub('Time difference of', 'Total time used for computing compartment domains and their hierachy:', print(time1 - time0))
  140. delta_time <- time1 - time0
  141. timediff <- format(round(delta_time, 2), nsmall = 2)
  142. cat('\n\n', 'Total time used for computing sub-domains:', timediff, '\n', file=log_file, append=TRUE)
  143. }
  144. # return(NULL)
  145. }
  146. ############################################################
  147. create_compartment_bed_v4 = function(chr_bin_domain, bin_size)
  148. {
  149. # for( chr in chrs )
  150. {
  151. v = chr_bin_domain
  152. # v$intra_domain = as.character(6 - (as.numeric(v$intra_domain))) ## invert the labeling
  153. # v$intra_domain = names(cols)[(as.numeric(v$intra_domain))]
  154. v = v[order(v$bin_index), ]
  155. borders_non_consecutive = which(diff(v$bin_index)!=1)
  156. borders_domain = cumsum(rle(v$comp)$lengths)
  157. borders = sort(union(borders_non_consecutive, borders_domain))
  158. bins = v$bin_index
  159. to_id = as.numeric(bins[borders])
  160. from_id = as.numeric(bins[c(1, head(borders, length(borders)-1)+1)])
  161. pos_start = (from_id-1)*bin_size + 1
  162. pos_end = to_id*bin_size
  163. # chr = as.numeric( gsub('chr', '', v$chr) )
  164. chr = gsub('chr', '', v$chr) ## no need for as.numeric, also makes it compatible with chrX
  165. compartment_info_tab = data.frame(chr=rep(unique(chr), length(pos_start)), pos_start=pos_start, pos_end=pos_end, domain=v$comp[borders])
  166. }
  167. return(compartment_info_tab)
  168. }
  169. ############################################################
  170. generate_hierachy_bed = function(chr, res, save_dir, bin_size)
  171. {
  172. chr_name = paste0('chr', chr)
  173. # res = reses[[chr_name]][[CELL_LINE]]
  174. hc = res$CALDER_hc
  175. hc_k_labels_full = try(get_cluser_levels(hc, k_clusters=Inf, balanced_4_clusters=FALSE)$cluster_labels)
  176. bin_comp = data.table::data.table(chr=chr, bin_index=as.numeric(res$bin_names), comp=rep(hc_k_labels_full, sapply(res$initial_clusters, length)))
  177. chr_bin_domain = bin_comp
  178. chr_bin_domain$chr = paste0('chr', chr_bin_domain$chr)
  179. # chr_bin_domain = chr_bin_domain[order(bin_index)]
  180. compartment_info_tab = create_compartment_bed_v4(chr_bin_domain, bin_size=bin_size)
  181. boundaries = unname(sapply(res$initial_clusters, max))
  182. boundaries_ori = as.numeric(res$bin_names[boundaries])*bin_size
  183. compartment_info_tab$is_boundary = 'gap'
  184. compartment_info_tab[compartment_info_tab$pos_end %in% boundaries_ori, 'is_boundary'] = 'boundary'
  185. colnames(compartment_info_tab)[4] = 'compartment_label'
  186. compartments_tsv_file = paste0(save_dir, '/chr', chr, '_domain_hierachy.tsv')
  187. compartments_bed_file = paste0(save_dir, '/chr', chr, '_sub_compartments.bed')
  188. boundary_bed_file = paste0(save_dir, '/chr', chr, '_domain_boundaries.bed')
  189. options(scipen=999)
  190. write.table( compartment_info_tab, file=compartments_tsv_file, quote=FALSE, sep='\t', row.names=FALSE )
  191. comp_cols = c("#FF0000", "#FF4848", "#FF9191", "#FFDADA", "#DADAFF", "#9191FF", "#4848FF", "#0000FF")
  192. names(comp_cols) = c('A.1.1', 'A.1.2', 'A.2.1', 'A.2.2', 'B.1.1', 'B.1.2', 'B.2.1', 'B.2.2')
  193. comp_val = (8:1)/8
  194. names(comp_val) = names(comp_cols)
  195. comp_8 = substr(compartment_info_tab$compartment_label, 1, 5)
  196. compartment_bed = data.frame(chr=paste0('chr', compartment_info_tab$chr), compartment_info_tab[, 2:4], comp_val[comp_8], '.', compartment_info_tab[, 2:3], comp_cols[comp_8])
  197. write.table( compartment_bed, file=compartments_bed_file, quote=FALSE, sep='\t', row.names=FALSE, col.names=FALSE )
  198. bounday_bed_raw = subset(compartment_info_tab, is_boundary=='boundary')
  199. bounday_bed = data.frame(chr=paste0('chr', compartment_info_tab$chr), compartment_info_tab[,3], compartment_info_tab[,3], '', '.', compartment_info_tab[,3], compartment_info_tab[,3], '#000000')
  200. write.table( bounday_bed, file=boundary_bed_file, quote=FALSE, sep='\t', row.names=FALSE, col.names=FALSE )
  201. }
  202. project_to_major_axis <- function(PC_12_atanh)
  203. {
  204. Data = data.frame(x=PC_12_atanh[,1], y=PC_12_atanh[,2])
  205. Data = Data[order(Data$x),]
  206. loess_fit <- loess(y ~ x, Data)
  207. more_x = seq(min(PC_12_atanh[,1]), max(PC_12_atanh[,1]), len=10*length(PC_12_atanh[,1]))
  208. major_axis = cbind(x=more_x, y=predict(loess_fit, newdata=more_x))
  209. new_x_axis = cumsum(c(0, sqrt(diff(major_axis[,1])^2 + diff(major_axis[,2])^2))) ## the new xaxis on the curved major_axis
  210. dis = fields::rdist(PC_12_atanh[, 1:2], major_axis)
  211. projected_x = new_x_axis[apply(dis, 1, which.min)]
  212. names(projected_x) = rownames(PC_12_atanh)
  213. # projected_x = major_axis[apply(dis, 1, which.min)]
  214. project_info = list(x_pro=projected_x, major_axis=major_axis)
  215. return(project_info)
  216. }
  217. get_best_reorder <- function(hc_hybrid_x_pro, x_pro)
  218. {
  219. n = length(x_pro)
  220. reordered_names_x_pro_list = list()
  221. reordered_names_x_pro_list[[1]] = reorder_dendro(hc_hybrid_x_pro, (x_pro), aggregateFun=mean) ## here the clusters are assigned into A.1 A.2 B.1 B.2
  222. best_index = which.max(sapply(reordered_names_x_pro_list, function(v) cor(1:n, unname(rank(x_pro, ties.method='first')[v]))))
  223. return(reordered_names_x_pro_list[[1]])
  224. }