forked from broadinstitute/infercnv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
inferCNV.R
executable file
·2758 lines (2533 loc) · 96.5 KB
/
inferCNV.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env Rscript
CHR = "chr"
START = "start"
STOP = "stop"
# Remove the average of the genes of the reference observations from all
# observations' expression. Normalization by column.
#
# Args:
# average_data: Matrix containing the data to remove average
# from (this includes the reference observations).
# Row = Genes, Col = Cells.
# ref_observations: Indices of reference observations.
# Only these are used in the average.
# ref_groups: A list of vectors of indices refering to the
# different groups of the reference indices.
#
# Returns:
# Expression with the average gene expression in the reference
# observations removed.
average_over_ref <- function(average_data,
ref_observations,
ref_groups){
# r = genes, c = cells
logging::loginfo(paste("::average_over_ref:Start", sep=""))
# Max and min mean gene expression within reference groups.
average_max <- NULL
average_min <- NULL
average_reference_obs <- average_data[,ref_observations, drop=FALSE]
# Reference gene within reference groups
for (ref_group in ref_groups){
grp_average <- rowMeans(average_reference_obs[,ref_group,
drop=FALSE],
na.rm=TRUE)
if(is.null(average_max)){
average_max <- grp_average
}
if(is.null(average_min)){
average_min <- grp_average
}
average_max <- pmax(average_max, grp_average)
average_min <- pmin(average_min, grp_average)
}
# Remove the Max and min averages of the reference groups from the
# For each gene.
for(gene_i in 1:nrow(average_data)){
current_col <- average_data[gene_i, ]
i_max <- which(current_col > average_max[gene_i])
i_min <- which(current_col < average_min[gene_i])
row_init <- rep(0, length(current_col))
if(length(i_max) > 0){
row_init[i_max] <- current_col[i_max] - average_max[gene_i]
}
if(length(i_min) > 0){
row_init[i_min] <- current_col[i_min] - average_min[gene_i]
}
average_data[gene_i, ] <- row_init
}
return(average_data)
}
# Not testing, parameters ok.
# Helper function allowing greater control over the steps in a color palette.
# Source:http://menugget.blogspot.com/2011/11/define-color-steps-for-
# colorramppalette.html#more
# Args:
# steps: Vector of colors to change use in the palette
# between: Steps where gradients change
#
# Returns:
# Color palette
color.palette <- function(steps,
between=NULL, ...){
if (is.null(between)){
between <- rep(0, (length(steps) - 1))
}
if (length(between) != length(steps) - 1){
stop("Must have one less \"between\" value than steps")
}
fill.steps <- cumsum(rep(1, length(steps)) + c(0, between))
RGB <- matrix(NA, nrow=3, ncol=fill.steps[length(fill.steps)])
RGB[, fill.steps] <- col2rgb(steps)
for(i in which(between > 0)){
col.start <- RGB[, fill.steps[i]]
col.end <- RGB[, fill.steps[i + 1]]
for(j in seq(3)){
vals <- seq(col.start[j],
col.end[j],
length.out=between[i] + 2)
vals <- vals[2:(2 + between[i] - 1)]
RGB[j, (fill.steps[i] + 1):(fill.steps[i + 1] - 1)] <- vals
}
}
new.steps <- rgb(RGB[1, ], RGB[2, ], RGB[3, ], maxColorValue=255)
pal <- colorRampPalette(new.steps, ...)
return(pal)
}
# Create a sepList forthe heatmap.3 plotting function given integer vectors
# of rows and columns where speration should take place.
# The expected input to the heatmap function is a list of 2 lists.
# The first list are column based rectangles, and the second row.
# To define a rectagle the index of the row or column where the line of the rectagle
# should be placed is done with a vector of integers, left, bottom, right and top line.
# Ie. list(list(c(1,0,3,10), c(5, 0, 10,10)), list(c(1,2,3,4)))
#
# Args:
# row_count: Total number of rows
# col_count: Total number of columns
# row_seps: Vector of integers indices for row breaks
# col_seps: Vector of integer indices for column breaks
#
# Returns
# List of lists of vectors
create_sep_list <- function(row_count,
col_count,
row_seps=NULL,
col_seps=NULL){
sepList <- list()
# Heatmap.3 wants a list of boxes for seperating columns
# Column data
if(!is.null(col_seps) &&
!is.na(col_seps) &&
(length(col_seps)>0) &&
col_count > 0){
colList <- list()
for(sep in 1:length(col_seps)){
colList[[sep]] <- c(col_seps[sep],0,col_seps[sep],row_count)
}
sepList[[1]] <- colList
} else {
sepList[[1]] <- list()
sepList[[1]][[1]] <- c(0,0,0,0)
}
# Row data
# This is measured from bottom to top
# So you have to adjust the values of the data
row_seps <- row_count-row_seps
if(!is.null(row_seps) &&
!is.na(row_seps) &&
(length(row_seps)>0) &&
row_count > 0){
rowList <- list()
for(sep in 1:length(row_seps)){
rowList[[sep]] <- c(0,row_seps[sep],col_count,row_seps[sep])
}
sepList[[2]] <- rowList
} else {
sepList[[2]] <- list()
sepList[[2]][[1]] <- c(0,0,0,0)
}
return(sepList)
}
# Split up reference observations in to k groups and return indices
# for the different groups.
#
# Args:
# average_data: Matrix containing data. Row = Genes, Col = Cells.
# ref_obs: Indices of reference obervations.
# num_groups: The number of groups to partition nodes in or a list
# of already partitioned indices.
#
# Returns:
# Returns a list of grouped reference observations given as
# vectors of groups. These are indices relative to the reference
# observations only, so a return 1 indicates the first reference
# row, not the first row.
split_references <- function(average_data,
ref_obs,
num_groups){
logging::loginfo(paste("::split_references:Start", sep=""))
ret_groups <- list()
split_groups <- NULL
if(is.null(average_data)){
return(ret_groups)
}
if(is.null(num_groups)){
num_groups <- 1
}
if(is.null(ref_obs)){
ref_obs <- 1:ncol(average_data)
}
# If a supervised grouping is given as a commandline argument
# num_groups will be a list of length of more than 1.
# Otherwise do this.
if (length(num_groups) == 1){
num_groups <- unlist(num_groups)
if (num_groups > ncol(average_data)){
num_groups <- ncol(average_data)
}
# If only one group is needed, short-circuit and
# return all indices immediately
# If only one group is asked for or only one reference is
# available to give.
if ((num_groups < 2) ||
(length(ref_obs) < 2)){
ret_groups[[1]] <- ref_obs
return(ret_groups)
}
# Get HCLUST
# Get reference observations only.
average_reference_obs <- t(average_data[, ref_obs, drop=FALSE])
hc <- hclust(dist(average_reference_obs))
split_groups <- cutree(hc, k=num_groups)
split_groups <- split_groups[hc$order]
# Keep the sort of the hclust
for(cut_group in unique(split_groups)){
group_idx <- which(split_groups == cut_group)
ret_groups[[cut_group]] <- hc$order[group_idx]
}
} else {
ret_groups <- num_groups
}
return(ret_groups)
}
# Set outliers to some upper or lower bound. Then normalize values to
# approximately [-1, 1]. This is to prep the data for visualization.
#
# Args:
# data: data to remove outliers. Outliers removed within columns.
# out_method: Method to remove outliers [(average_bound, NA (hard threshold))]
# lower_bound: Lower bound which identifies a measurement
# as an outlier.
# upper_bound: Upper bound which identifies a measurement
# as an outlier.
# plot_step: True will plot this analysis step.
#
# Returns:
# Return data matrix with outliers removed
remove_outliers_norm <- function(data,
out_method=NA,
lower_bound=NA,
upper_bound=NA,
plot_step=NA){
logging::loginfo(paste("::remove_outlier_norm:Start"))
if(is.na(data) || is.null(data) || nrow(data) < 1 || ncol(data) < 1){
return(data)
}
if (is.na(lower_bound) || is.na(upper_bound)){
if(is.na(out_method)){
logging::loginfo("::remove_outlier_norm:WARNING outlier removal was not performed.")
return(data)
}
if (out_method == "average_bound"){
lower_bound <- mean(apply(data, 2,
function(x) quantile(x)[[1]]))
upper_bound <- mean(apply(data, 2,
function(x) quantile(x)[[5]]))
# Plot bounds on data
if(!is.na(plot_step)){
pdf(plot_step, useDingbats=FALSE)
boxplot(data)
points(1:ncol(data), rep(lower_bound, ncol(data)),
pch=19, col="orange")
points(1:ncol(data), rep(upper_bound, ncol(data)),
pch=19, col="orange")
dev.off()
}
data[data < lower_bound] <- lower_bound
data[data > upper_bound] <- upper_bound
return(data)
} else {
logging::logerror(paste("::remove_outlier_norm:Error, please",
"provide an approved method for outlier",
"removal for visualization."))
stop(991)
}
}
# Hard threshold given bounds
if(!is.na(plot_step)){
pdf(plot_step, useDingbats=FALSE)
boxplot(data)
points(1:ncol(data), rep(lower_bound, ncol(data)),
pch=19, col="orange")
points(1:ncol(data), rep(upper_bound, ncol(data)),
pch=19, col="orange")
dev.off()
}
data[data < lower_bound] <- lower_bound
data[data > upper_bound] <- upper_bound
return(data)
}
# Center data after smoothing. Center with in cells using median.
#
# Args:
# data_smoothed: Matrix to center.
# Row = Genes, Col = cells.
#
# Returns:
# Matrix that is median centered.
# Row = Genes, Col = cells.
center_smoothed <- function(data_smoothed){
logging::loginfo(paste("::center_smoothed:Start"))
# Center within columns
row_median <- apply(data_smoothed, 2, median)
return(t(apply(data_smoothed, 1, "-", row_median)))
}
# Center data and threshold (both negative and postive values)
#
# Args:
# center_data: Matrix to center. Row = Genes, Col = Cells.
# threshold: Values will be required to be with -/+1 *
# threshold after centering.
# Returns:
# Centered and thresholded matrix
center_with_threshold <- function(center_data, threshold){
logging::loginfo(paste("::center_with_threshold:Start", sep=""))
# Center data (automatically ignores zeros)
center_data <- center_data - rowMeans(center_data, na.rm=TRUE)
# Cap values between threshold and -threshold and recenter
center_data[center_data > threshold] <- threshold
center_data[center_data < (-1 * threshold)] <- -1 * threshold
center_data <- center_data - rowMeans(center_data, na.rm=TRUE)
return(center_data)
}
# Returns the color palette for contigs.
#
# Returns:
# Color Palette
get_group_color_palette <- function(){
return(colorRampPalette(RColorBrewer::brewer.pal(12,"Set3")))
}
#' @title Infer CNV changes given a matrix of RNASeq counts. Output a pdf and matrix of final values.
#'
#' @param data: Expression matrix (genes X samples),
#' assumed to be log2(TPM+1) .
#' @param gene_order: Ordering of the genes (data's rows)
#' according to their genomic location
#' To include all genes use 0.
#' @param cutoff: Cut-off for the average expression of genes to be
#' used for CNV inference.
#' @param reference_obs: Column names of the subset of samples (data's columns)
#' that should be used as references.
#' If not given, the average of all samples will
#' be the reference.
#' @param transform_data: Indicator to log2 + 1 transform
#' @param window_length: Length of the window for the moving average
#' (smoothing). Should be an odd integer.
#' @param max_centered_threshold: The maximum value a a value can have after
#' centering. Also sets a lower bound of
#' -1 * this value.
#' @param noise_threshold: The minimum difference a value can be from the
#' average reference in order for it not to be
#' removed as noise.
#' @param num_ref_groups: The number of reference groups of a list of
#' indicies for each group of reference indices in
#' relation to reference_obs.
#' @param out_path: The path to what to save the pdf as. The raw data is
#' also written to this path but with the extension .txt .
#' @param plot_steps: If true turns on plotting intermediate steps.
#' @param contig_tail: Length of the tail removed from the ends of contigs.
#' @param method_bound: Method to use for bounding values in the visualization.
#' @param lower_bound_vis: Lower bound to normalize data to for visualization.
#' @param upper_bound_vis: Upper bound to normalize data to for visualization.
#'
#' @return
#' Returns a list including:
#' CNV matrix before visualization.
#' CNV matrix after outlier removal for visualization.
#' Contig order
#' Column names of the subset of samples that should be used as references.
#' Names of samples in reference groups.
#' @export
infer_cnv <- function(data,
gene_order,
cutoff,
reference_obs,
transform_data,
window_length,
max_centered_threshold,
noise_threshold,
num_ref_groups,
out_path,
plot_steps=FALSE,
contig_tail= (window_length - 1) / 2,
method_bound_vis=NA,
lower_bound_vis=NA,
upper_bound_vis=NA){
logging::loginfo(paste("::infer_cnv:Start", sep=""))
# Return list of matrices
ret_list <- list()
# Plot incremental steps.
if (plot_steps){
plot_step(data=data,
plot_name=file.path(out_path,
"00_reduced_data.pdf"))
}
# Make sure data is log transformed + 1
if (transform_data){
data <- log2(data / 10 + 1)
}
# Plot incremental steps.
if (plot_steps){
plot_step(data=data,
plot_name=file.path(out_path,
"02_transformed.pdf"))
}
# Reduce by cutoff
keep_gene_indices <- above_cutoff(data, cutoff)
if (!is.null(keep_gene_indices)){
data <- data[keep_gene_indices, , drop=FALSE]
gene_order <- gene_order[keep_gene_indices, , drop=FALSE]
logging::loginfo(paste("::infer_cnv:Reduce by cutoff, ",
"new dimensions (r,c) = ",
paste(dim(data), collapse=","),
" Total=", sum(data),
" Min=", min(data),
" Max=", max(data),
".", sep=""))
logging::logdebug(paste("::infer_cnv:Keeping indices.", sep=""))
} else {
logging::loginfo(paste("::infer_cnv:Reduce by cutoff.", sep=""))
logging::logwarn(paste("::No indicies left to keep.",
" Stoping."))
stop(998)
}
# Plot incremental steps.
if (plot_steps){
plot_step(data=data,
plot_name=file.path(out_path,
"03_reduced_by_cutoff.pdf"))
}
# Reduce contig info
chr_order <- gene_order[1]
gene_order <- NULL
# Center data (automatically ignores zeros)
data <- center_with_threshold(data, max_centered_threshold)
logging::loginfo(paste("::infer_cnv:Outlier removal, ",
"new dimensions (r,c) = ",
paste(dim(data), collapse=","),
" Total=", sum(data),
" Min=", min(data),
" Max=", max(data),
".", sep=""))
# Plot incremental steps.
if (plot_steps){
plot_step(data=data,
plot_name=file.path(out_path,
"05_center_with_threshold.pdf"))
}
# Smooth the data with gene windows
data_smoothed <- smooth_window(data, window_length)
data <- NULL
logging::loginfo(paste("::infer_cnv:Smoothed data.", sep=""))
# Plot incremental steps.
if (plot_steps){
plot_step(data=data_smoothed,
plot_name=file.path(out_path,
"06_smoothed.pdf"))
}
# Center cells/observations after smoothing. This helps reduce the
# effect of complexity.
data_smoothed <- center_smoothed(data_smoothed)
# Plot incremental steps.
if (plot_steps){
plot_step(data=data_smoothed,
plot_name=file.path(out_path,
"07_recentered.pdf"))
}
# Split the reference data into groups if requested
groups_ref <- split_references(average_data=data_smoothed,
ref_obs=reference_obs,
num_groups=num_ref_groups)
logging::loginfo(paste("::infer_cnv:split_reference. ",
"found ",length(groups_ref)," reference groups.",
sep=""))
# Remove average reference
i_ref_obs <- which(colnames(data_smoothed) %in% reference_obs)
data_smoothed <- average_over_ref(average_data=data_smoothed,
ref_observations=i_ref_obs,
ref_groups=groups_ref)
logging::loginfo(paste("::infer_cnv:Remove average, ",
"new dimensions (r,c) = ",
paste(dim(data_smoothed), collapse=","),
" Total=", sum(data_smoothed),
" Min=", min(data_smoothed),
" Max=", max(data_smoothed),
".", sep=""))
# Plot incremental steps.
if (plot_steps){
plot_step(data=data_smoothed,
plot_name=file.path(out_path,
"08_remove_average.pdf"))
}
# Remove Ends
logging::logdebug(chr_order)
remove_indices <- c()
for (chr in unlist(unique(chr_order))){
logging::loginfo(paste("::infer_cnv:Remove tail contig ",
chr, ".", sep=""))
remove_chr <- remove_tails(data_smoothed,
which(chr_order == chr),
contig_tail)
remove_indices <- c(remove_indices, remove_chr)
}
if (length(remove_indices) > 0){
chr_order <- chr_order[remove_indices,]
data_smoothed <- data_smoothed[remove_indices, , drop=FALSE]
}
# Plot incremental steps.
if (plot_steps){
plot_step(data=data_smoothed,
plot_name=file.path(out_path,
"09_remove_ends.pdf"))
}
logging::loginfo(paste("::infer_cnv:Remove ends, ",
"new dimensions (r,c) = ",
paste(dim(data_smoothed), collapse=","),
" Total=", sum(data_smoothed),
" Min=", min(data_smoothed),
" Max=", max(data_smoothed),
".", sep=""))
# Remove noise
data_smoothed <- remove_noise(smooth_matrix=data_smoothed,
threshold=noise_threshold)
logging::loginfo(paste("::infer_cnv:Remove moise, ",
"new dimensions (r,c) = ",
paste(dim(data_smoothed), collapse=","),
" Total=", sum(data_smoothed),
" Min=", min(data_smoothed),
" Max=", max(data_smoothed),
".", sep=""))
# Plot incremental steps.
if (plot_steps){
plot_step(data=data_smoothed,
plot_name=file.path(out_path,
"11_denoise.pdf"))
}
# Output before viz outlier
ret_list[["PREVIZ"]] = data_smoothed
# Remove outliers for viz
remove_outlier_viz_pdf <- NA
if (plot_steps){
remove_outlier_viz_pdf <- file.path(out_path,
"10A_remove_outlier.pdf")
}
ret_list[["VIZ"]] <- remove_outliers_norm(data=data_smoothed,
out_method=method_bound_vis,
lower_bound=lower_bound_vis,
upper_bound=upper_bound_vis,
plot_step=remove_outlier_viz_pdf)
# Plot incremental steps.
if (plot_steps){
plot_step(data=ret_list[["VIZ"]],
plot_name=file.path(out_path,
"10B_remove_outlier.pdf"))
}
logging::loginfo(paste("::infer_cnv:remove outliers, ",
"new dimensions (r,c) = ",
paste(dim(ret_list[["VIZ"]]), collapse=","),
" Total=", sum(ret_list[["VIZ"]]),
" Min=", min(ret_list[["VIZ"]]),
" Max=", max(ret_list[["VIZ"]]),
".", sep=""))
ret_list[["CONTIGS"]] = paste(as.vector(as.matrix(chr_order)))
ret_list[["REF_OBS_IDX"]] = reference_obs
ret_list[["REF_GROUPS"]] = groups_ref
return(ret_list)
}
# Not testing, params ok
# Log intermediate step with a plot and text file of the steps.
#
# Args:
# data: The data frame to plot.
# plot_name: The absolute path to the pdf to be plotted.
#
# Returns:
# No return
plot_step <- function(data, plot_name){
text_file <- unlist(strsplit(plot_name, "\\."))
text_file <- paste(c(text_file[1:length(text_file)], "txt"),
collapse=".", sep=".")
pdf(plot_name, useDingbats=FALSE)
image(as.matrix(data),
col=colorRampPalette(c("cyan","white","white","magenta"))(n=100))
dev.off()
write.table(data, file=text_file)
}
#' @title Plot the matrix as a heatmap. Clustering is on observation only, gene position is preserved.
#'
#' @param plot_data: Data matrix to plot (columns are observations).
#' @param contigs: The contigs the data is group in in order of rows.
#' @param reference_idx: Vector of reference indices.
#' @param ref_contig: If given, will focus cluster on only genes in this contig
#' @param reg_groups: Groups of vector indices (as indices in reference_idx)
#' @param out_dir: Directory in which to save pdf and other output.
#' @param title: Plot title.
#' @param obs_title: Title for the observations matrix.
#' @param ref_title: Title for the reference matrix.
#' @param contig_cex: Contig text size.
#' @param k_obs_groups: Number of groups to break observation into
#' @param color_safe_pal: Logical indication of using a color blindness safe
#' palette.
#'
#' @return
#' No return, void.
#' @export
plot_cnv <- function(plot_data,
contigs,
reference_idx,
ref_contig,
ref_groups,
out_dir,
title,
obs_title,
ref_title,
contig_cex=1,
k_obs_groups=1,
color_safe_pal=TRUE){
logging::loginfo(paste("::plot_cnv:Start", sep=""))
logging::loginfo(paste("::plot_cnv:Current data dimensions (r,c)=",
paste(dim(plot_data), collapse=","),
" Total=", sum(plot_data),
" Min=", min(plot_data),
" Max=", max(plot_data),
".", sep=""))
logging::loginfo(paste("::plot_cnv:Depending on the size of the matrix",
" this may take a moment.",
sep=""))
# Contigs
unique_contigs <- unique(contigs)
n_contig <- length(unique_contigs)
ct.colors <- get_group_color_palette()(n_contig)
names(ct.colors) <- unique_contigs
# Select color palette
custom_pal <- color.palette(c("purple3", "white", "darkorange2"),
c(2, 2))
if (color_safe_pal == FALSE){
custom_pal <- color.palette(c("darkblue", "white", "darkred"),
c(2, 2))
}
# Row seperation based on reference
ref_idx <- NULL
if (!is.null(reference_idx) && length(reference_idx) < ncol(plot_data)){
reference_idx <- which(colnames(plot_data) %in% reference_idx)
if(length(reference_idx) > 0){
ref_idx <- reference_idx
}
}
# Column seperation by contig and label axes with only one instance of name
contig_tbl <- table(contigs)[unique_contigs]
col_sep <- cumsum(contig_tbl)
col_sep <- col_sep[-1 * length(col_sep)]
# These labels are axes labels, indicating contigs at the first column only
# and leaving the rest blank.
contig_labels <- c()
contig_names <-c()
for (contig_name in names(contig_tbl)){
contig_labels <- c(contig_labels,
contig_name,
rep("", contig_tbl[contig_name] - 1))
contig_names <- c(contig_names,rep(contig_name,contig_tbl[contig_name]))
}
# Rows observations, Columns CHR
pdf(paste(out_dir,"infercnv.pdf",sep="."),
useDingbats=FALSE,
width=10,
height=7.5,
paper="USr")
# Plot observations
## Make Observation Samples
## Remove observation col names, too many to plot
## Will try and keep the reference names
## They are more informative anyway
obs_data <- plot_data
if (!is.null(ref_idx)){
obs_data <- plot_data[, -1 * ref_idx, drop=FALSE]
if (ncol(obs_data) == 1){
plot_data <- cbind(obs_data, obs_data)
names(obs_data) <- c("", names(obs_data)[1])
}
}
# Create file base for plotting output
force_layout <- plot_observations_layout()
plot_cnv_observations(obs_data=t(obs_data),
file_base_name=out_dir,
cluster_contig=ref_contig,
contig_colors=ct.colors[contigs],
contig_label=contig_labels,
contig_names=contig_names,
col_pal=custom_pal,
contig_seps=col_sep,
num_obs_groups=k_obs_groups,
cnv_title=title,
cnv_obs_title=obs_title,
contig_lab_size=contig_cex,
layout_lmat=force_layout[["lmat"]],
layout_lhei=force_layout[["lhei"]],
layout_lwid=force_layout[["lwid"]])
obs_data <- NULL
if(!is.null(ref_idx)){
plot_cnv_references(ref_data=plot_data[, ref_idx, drop=FALSE],
ref_groups=ref_groups,
col_pal=custom_pal,
contig_seps=col_sep,
file_base_name=out_dir,
cnv_ref_title=ref_title,
layout_add=TRUE)
}
dev.off()
}
# TODO Tested, test make files so turned off but can turn on and should pass.
# Plot the observational samples
#
# Args:
# obs_data: Data to plot as observations. Rows = Cells, Col = Genes
# col_pal: The color palette to use.
# contig_colors: The colors for the contig bar.
# contig_labels: The labels for the contigs.
# contig_names: Names of the contigs
# contig_seps: Indices for line seperators of contigs.
# num_obs_groups: Number of groups of observations to create
# file_base_name: Base of the file to used to make output file names.
# cnv_title: Title of the plot.
# cnv_obs_title: Title for the observation matrix.
# contig_lab_size: Text size for contigs.
# cluster_contig: A value directs cluster to only genes on this contig
# layout_lmat: lmat values to use in layout
# layout_lhei: lhei values to use in layout
# layout_lwid: lwid values to use in layout
#
# Returns:
# Void
plot_cnv_observations <- function(obs_data,
col_pal,
contig_colors,
contig_labels,
contig_names,
contig_seps,
num_obs_groups,
file_base_name,
cnv_title,
cnv_obs_title,
contig_lab_size=1,
cluster_contig=NULL,
testing=FALSE,
layout_lmat=NULL,
layout_lhei=NULL,
layout_lwid=NULL){
logging::loginfo("plot_cnv_observation:Start")
logging::loginfo(paste("Observation data size: Cells=",
nrow(obs_data),
"Genes=",
ncol(obs_data),
sep=" "))
observation_file_base <- paste(file_base_name, "observations.txt", sep=.Platform$file.sep)
# Output dendrogram representation as Newick
# Need to precompute the dendrogram so we can manipulate
# it before the heatmap plot
## Optionally cluster by a specific contig
hcl_desc <- "General"
hcl_group_indices <- 1:ncol(obs_data)
if(!is.null(cluster_contig)){
hcl_contig_indices <- which(contig_names == cluster_contig)
if(length(hcl_group_indices)>0){
hcl_group_indices <- hcl_contig_indices
hcl_desc <- cluster_contig
logging::loginfo(paste("plot_cnv_observation:Clustering only by contig ", cluster_contig))
} else {
logging::logwarning(paste("plot_cnv_observations: Not able to cluster by",
cluster_contig,
"Clustering by all genomic locations.",
"To cluster by local genomic location next time",
"select from:",
unique(contig_names),
collapse=",",
sep=" "))
}
}
# HCL with a inversely weighted euclidean distance.
obs_hcl <- hclust(dist(obs_data[,hcl_group_indices]),"average")
obs_dendrogram <- as.dendrogram(obs_hcl)
write.tree(as.phylo(obs_hcl),
file=paste(file_base_name, "observations_dendrogram.txt", sep=.Platform$file.sep))
# Output HCL group membership.
# Record locations of seperations
obs_seps <- c(0)
ordered_names <- rev(row.names(obs_data)[obs_hcl$order])
split_groups <- cutree(obs_hcl, k=num_obs_groups)
# Make colors based on groupings
row_groupings <- get_group_color_palette()(length(table(split_groups)))[split_groups]
# Make a file of coloring and groupings
logging::loginfo("plot_cnv_observation:Writing observation groupings/color.")
groups_file_name <- file.path(file_base_name, "observation_groupings.txt")
file_groups <- rbind(split_groups,row_groupings)
row.names(file_groups) <- c("Group","Color")
write.table(t(file_groups), groups_file_name)
# Make a file of members of each group
logging::loginfo("plot_cnv_observation:Writing observations by grouping.")
for (cut_group in unique(split_groups)){
group_memb = names(split_groups)[which(split_groups == cut_group)]
# Write group to file
memb_file <- file(paste(file_base_name,
paste(hcl_desc,"HCL",cut_group,"members.txt",sep="_"),
sep=.Platform$file.sep))
write.table(obs_data[group_memb,], memb_file)
# Record seperation
ordered_memb <- which(ordered_names %in% group_memb)
obs_seps <- c(obs_seps, max(ordered_memb),max(ordered_memb))
}
obs_hcl <- NULL
obs_seps <- unique(obs_seps)
obs_seps <- sort(obs_seps)
# Generate the Sep list for heatmap.3
contigSepList <- create_sep_list(row_count=nrow(obs_data),
col_count=ncol(obs_data),
col_seps=contig_seps)
# Remove row/col labels, too cluttered
# and print.
orig_row_names <- row.names(obs_data)
row.names(obs_data) <- rep("", nrow(obs_data))
data_observations <- heatmap.cnv(obs_data,
Rowv=obs_dendrogram,
Colv=FALSE,
cluster.by.col=FALSE,
main=cnv_title,
ylab=cnv_obs_title,
margin.for.labRow=10,
margin.for.labCol=2,
xlab="Genomic Region",
key=TRUE,
labCol=contig_labels,
cexCol=contig_lab_size,
notecol="black",
density.info="histogram",
denscol="blue",
trace="none",
dendrogram="row",
cexRow=0.8,
scale="none",
x.center=0,
color.FUN=col_pal,
if.plot=!testing,
# Seperate by contigs
sepList=contigSepList,
sep.color="black",
sep.lty=1,
sep.lwd=1,
# Color rows by user defined cut
RowIndividualColors=row_groupings,
# Color by contigs
ColIndividualColors=contig_colors,
# Legend
key.title="Distribution of Expression",
key.xlab="Modified Expression",
key.ylab="Count",
# Layout
force_lmat=layout_lmat,
force_lwid=layout_lwid,
force_lhei=layout_lhei)
# Write data to file.
logging::loginfo(paste("plot_cnv_references:Writing observation data to",
observation_file_base,
sep=" "))
row.names(obs_data) <- orig_row_names
write.table(obs_data[data_observations$rowInd,data_observations$colInd],
file=observation_file_base)
}
# Not Testing, params ok.
# Create the layout for the plot
# This is a modification of the original
# layout from the GMD heatmap.3 function
#
# Returns:
# list with slots "lmat" (layout matrix),
# "lhei" (height, numerix vector),
# and "lwid" (widths, numeric vector)
plot_observations_layout <- function()
{
## Plot observational samples
obs_lmat <- c(0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
6, 8, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4, 2, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4, 2, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4, 2, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4, 2, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4, 2, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4, 2, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4, 2, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4, 2, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4, 2, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
obs_lmat <- matrix(obs_lmat,ncol=13,byrow=TRUE)
obs_lhei <- c(1.125, 2.215, .15,
.5, .5, .5,
.5, .5, .5,
.5, .5, .5,
0.0075, 0.0075, 0.0075)
return(list(lmat=obs_lmat,
lhei=obs_lhei,
lwid=NULL))
}
# TODO Tested, test make files so turned off but can turn on and should pass.
# Plot the reference samples
#
# Args:
# ref_data: Data to plot as references. Rows = Cells, Col = Genes
# ref_groups: Groups of references to plot together.
# col_pal: The color palette to use.
# contig_seps: Indices for line seperators of contigs.
# file_base_name: Base of the file to used to make output file names.
# cnv_ref_title: Title for reference matrix.
# layout_lmat: lmat values to use in the layout.
# layout_lwid: lwid values to use in the layout.
# layout_lhei: lhei values to use in the layout.
# layout_add: Indicates the ref image shoudl be added to the previous plot.
# testing: Turns off plotting when true.
#
# Returns:
# Void
plot_cnv_references <- function(ref_data,
ref_groups,
col_pal,
contig_seps,
file_base_name,
cnv_ref_title,
layout_lmat=NULL,
layout_lwid=NULL,
layout_lhei=NULL,
layout_add=FALSE,
testing=FALSE){
logging::loginfo("plot_cnv_references:Start")
logging::loginfo(paste("Reference data size: Cells=",
ncol(ref_data),
"Genes=",
nrow(ref_data),
sep=" "))
number_references <- ncol(ref_data)
reference_ylab <- NA
reference_data_file <- paste(file_base_name, "references.txt", sep=.Platform$file.sep)
ref_seps <- c()
# Handle only one reference
# heatmap3 requires a 2 x 2 matrix, so with one reference
# I just duplicate the row and hid the second name so it
# visually looks like it is just taking up the full realestate.
if(number_references == 1){