-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.R
More file actions
1478 lines (1069 loc) · 40.7 KB
/
utils.R
File metadata and controls
1478 lines (1069 loc) · 40.7 KB
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
#############
## IMPORTS ##
#############
library('NMF')
library('GenomicRanges')
library('GenomeInfoDb')
library('MutationalPatterns')
library('plotrix')
library("ggplot2")
#library("BSgenome.Hsapiens.UCSC.hg19")
library("reshape2")
library('knitr')
#library("plotly")
############
## UTILS ##
############
"
The util functions are organized by categories:
1) Metrics
- cosine.similarity
- L2
- RSS
2) General plot functions
- myImagePlot
- plot_in_3D
- plot_a_pie
3) Signature plot functions
- plot_profile_1 (intermediate function useful for plot_profile)
- plot_profile
4) Comparison with COSMIC
- assign_to_cosmic
- plot_compare_to_cosmic
5) Analysis functions
- matrix_reconstruction
- plot_similarity_matrix
- exposure_to_clusters
6) Matrix normalization
- column_normalization
- row_normalization
7) Data loading functions
- vcf_to_mutmat
- vcfs_to_mutmat
- get_sigpro_signatures
- get_sigpro_activities
- get_sigpro_stats
8) Bootstrapping functions
- profile_bootstrap
- fit_boot
- plot_boot
- add_poisson_noise
9) Phylogeny function
-
10) Fit to signatures
-
11) Penta-nucleotide functions
"
###################################### 1) Metrics ######################################
cosine.similarity<-function(A,B){
'Compute the cosine similarity between the vectors A and B'
return(sum(A*B)/sqrt(sum(A^2)*sum(B^2)))
}
L2<-function(A,B){
'Compute the L2-norm between the vectors A and B'
return (sqrt(sum((A-B)^2)))
}
RSS=function(distrib1,distrib2){
'Compute the RSS (residual sum of squares) between the NORMALIZED distributions distrib1 and distrib2'
rel1=distrib1/sum(distrib1)
rel2=distrib2/sum(distrib2)
diff=rel1-rel2
RSS=sum(diff^2)
return(RSS)
}
###################################### 2) General plot functions ######################################
myImagePlot <- function(x, ...){
"This function takes a matrix as input and color it.
You can change ColorRamp and ColorLevels if you want to change the color scale."
min=min(x)
max=max(x)
yLabels <- rownames(x)
xLabels <- colnames(x)
title <-c()
# check for additional function arguments
if( length(list(...)) ){
Lst <- list(...)
if( !is.null(Lst$zlim) ){
min <- Lst$zlim[1]
max <- Lst$zlim[2]
}
if( !is.null(Lst$yLabels) ){
yLabels <- c(Lst$yLabels)
}
if( !is.null(Lst$xLabels) ){
xLabels <- c(Lst$xLabels)
}
if( !is.null(Lst$title) ){
title <- Lst$title
}
}
# check for null values
if( is.null(xLabels) ){
xLabels <- c(1:ncol(x))
}
if( is.null(yLabels) ){
yLabels <- c(1:nrow(x))
}
layout(matrix(data=c(1,2), nrow=1, ncol=2), widths=c(4,1), heights=c(1,1))
# Red and green range from 0 to 1 while Blue ranges from 1 to 0
ColorRamp <- rgb( seq(0.,0.9,length=256), # Red
seq(0.,0.4,length=256), # Green
seq(0.,0.3,length=256)) # Blue
ColorLevels <- seq(min, max, length=length(ColorRamp))
# Reverse Y axis
reverse <- nrow(x) : 1
yLabels <- yLabels[reverse]
x <- x[reverse,]
# Data Map
par(mar = c(3,5,2.5,2))
image(1:length(xLabels), 1:length(yLabels), t(x), col=ColorRamp, xlab="",
ylab="", axes=FALSE, zlim=c(min,max))
if( !is.null(title) ){
title(main=title)
}
axis(BELOW<-1, at=1:length(xLabels), labels=xLabels, cex.axis=0.7)
axis(LEFT <-2, at=1:length(yLabels), labels=yLabels, las= HORIZONTAL<-1,
cex.axis=0.7)
# Color Scale
par(mar = c(3,2.5,2.5,2))
image(1, ColorLevels,
matrix(data=ColorLevels, ncol=length(ColorLevels),nrow=1),
col=ColorRamp,
xlab="",ylab="",
xaxt="n")
}
plot_in_3D=function(data,x,y,z,color,colors){
"
plot_in_3D is a function to visualize data in 3D.
Args :
- data: dataframe
- x,y,z : data$x -> axis you want to plot
- color,colors: vectors of colors associated with each point
Returns:
- plot
"
return(plot_ly(data=data, x = x, y = y, z = z,color=color,colors = colors))
}
plot_a_pie=function(count,categories){
"
plot_a_pie creates a pie plot based on the counts of each category
Args :
- vector of counts (ex: c(2,54,6,78))
- vector of categories associated with the counts
Returns:
- plot
"
count <- data.frame(group = categories,value = count/sum(count))
bp<- ggplot(count, aes(x="", y=value, fill=group,ylab="Number of mutation / category"))+geom_bar(width = 1, stat = "identity")
pie <- bp + coord_polar("y", start=0)
return(pie)
}
###################################### 3) Signature plot functions ######################################
plot_profile_1 = function(profile,
profile_name = c("profile"),
profile_ymax = 0.2,
diff_ylim = c(-0.02, 0.02),
colors){
"
plot_profile plots a signature profile based its vector of 96 channels.
/!\ it is able only to plot ONE signature
Args :
- profile: vector of SBS (96 values)
- profile_name: name of the sample (not necessary)
- profile_ymax: ymax of the scale
- colors: if you want to put your own colors. By default the colors used are those of MutationalPatterns
Returns:
- plot
Example:
plot_profile(signature[,1])
"
# if colors parameter not provided, set to default colors
if(missing(colors)){colors = c("#2EBAED", "#000000", "#DE1C14","#D4D2D2", "#ADCC54", "#F0D0CE")}
s1_relative = profile / sum(profile)
x = cbind(s1_relative)
colnames(x) = c(profile_name)
substitutions = c('C>A', 'C>G', 'C>T', 'T>A', 'T>C', 'T>G')
index = c(rep(1,1,16), rep(2,1,16), rep(3,1,16),
rep(4,1,16), rep(5,1,16), rep(6,1,16))
# Context
C_TRIPLETS=c("ACA", "ACC", "ACG", "ACT","CCA", "CCC", "CCG", "CCT","GCA", "GCC", "GCG", "GCT","TCA", "TCC", "TCG", "TCT")
T_TRIPLETS=c("ATA", "ATC", "ATG", "ATT","CTA", "CTC", "CTG", "CTT","GTA", "GTC", "GTG", "GTT","TTA", "TTC", "TTG", "TTT")
context = c(rep(C_TRIPLETS, 3), rep(T_TRIPLETS, 3))
# Replace mutated base with dot
substring(context,2,2) = "."
# Construct dataframe for plotting
df = data.frame(substitution = substitutions[index], context = context)
rownames(x) = NULL
df2 = cbind(df, as.data.frame(x))
df3 = melt(df2, id.vars = c("substitution", "context"))
# These variables will be available at run-time, but not at compile-time.
# To avoid compiling trouble, we initialize them to NULL.
value = NULL
substitution = NULL
Sample = NULL
Contribution = NULL
Signature = NULL
# Add dummy non_visible data points to force y axis limits per facet
df4 = data.frame(substitution = rep("C>A", 4),
context = rep("A.A",4),
variable = c(profile_name),
value = c(profile_ymax,profile_ymax))
plot = ggplot(data=df3, aes(x=context,
y=value,
fill=substitution,
width=1)) +
geom_bar(stat="identity",
position = "identity",
colour="black", size=.2) +
geom_point(data = df4, aes(x = context,
y = value), alpha = 0) +
scale_fill_manual(values=colors) +
facet_grid(variable ~ substitution, scales = "free_y") +
ylab("Relative contribution") +
# ylim(-yrange, yrange) +
# no legend
guides(fill=FALSE) +
# white background
theme_bw() +
# format text
theme(axis.title.y=element_text(size=12,vjust=1),
axis.text.y=element_text(size=8),
axis.title.x=element_text(size=12),
axis.text.x=element_text(size=5,angle=90,vjust=0.4),
strip.text.x=element_text(size=14),
strip.text.y=element_text(size=14),
panel.grid.major.x = element_blank(),
panel.spacing.x = unit(0, "lines"))
return(plot)
}
plot_profile=function(profiles,profile_name="none"){
"
Takes a set of profiles and plot the profile for which the name is provided.
If the set of profiles contains only one signature, the function will plot this signature.
Args :
- profiles: set of profiles [96,n_signatures]
- profile_name: name of the signature to plot /!\ it has to be the name of a column
Returns:
- the plot of the signature
"
# Makes sure that the input profiles matrix has the right profile
if(length(profiles)==96){
return(plot_profile_1(profiles))
}
if (nrow(profiles)!=96){
stop("The dimension has to be [nrow=96,ncol=number_of_signatures]")
}
if(profile_name=="none"){
if(length(profiles)!=96){
stop("You forgot to enter profile_name")
}
}
if(sum(1*(colnames(profiles)==profile_name))==0){
stop("There is no column named profile_name")
}
else{
ind=which(colnames(profiles)==profile_name)
return(plot_profile_1(profiles[,profile_name],profile_name = profile_name))
}
}
###################################### 4) Comparison with COSMIC ######################################
# Assign a set of signatures to to the most similar signature in COSMIC
assign_to_cosmic=function(signatures,cosmic_signatures="none"){
"
assign_to_cosmic compares a set of signatures to the COSMIC signatures according to the cosine similarity.
It prints the most similar COSMIC signatures and return the similarity matrix.
Args :
- signatures: set of signatures to compare to COSMIC signatures [nrow=96,ncol=number_of_signatures]
- cosmic_signatures: matrix containing the COSMIC signatures [nrow=96,ncol=number_of_COSMIC_signatures] (if not provided, take the August 2019 set of COSMIC sigs)
Returns:
- prints the most similar COSMIC signature for every input signature
- returns the similarity matrix
Example:
assign_to_cosmic(set_of_extracted_signatures)
"
if(cosmic_signatures=="none"){
cosmic_signatures<-read.csv(file="cosmic_signatures.csv",header=TRUE)
cosmic_signatures = as.matrix(cosmic_signatures[,3:ncol(cosmic_signatures)])
}
if(length(signatures)==96){
A=rep(0,ncol(cosmic_signatures))
for(i in seq(1,ncol(cosmic_signatures))){
A[i]=cosine.similarity(signatures,cosmic_signatures[,i])
}
print(paste("The closest COSMIC signature is ",colnames(cosmic_signatures)[which.max(A)]," with a CS= ",max(A)))
return(A)
}
A<-matrix(0L,nrow=ncol(signatures),ncol=ncol(cosmic_signatures))
for(i in 1:(ncol(signatures))){
for(j in (1:ncol(cosmic_signatures))){
A[i,j]=cosine.similarity(signatures[,i],cosmic_signatures[,j])
}
}
rownames(A)=colnames(signatures)
colnames(A)=colnames(cosmic_signatures)
for (i in 1:(ncol(signatures))){
print(paste("The closest COSMIC signature for ",colnames(signatures)[i]," is ",colnames(cosmic_signatures)[which.max(A[i,])]," with a CS= ",max(A[i,])))
}
return(A)
}
plot_compare_to_cosmic=function(signatures,cosmic_signatures="none"){
"
plot_compare_to_cosmic is equivalent to assign_to_cosmic but the similarity matrix is colored
"
if(cosmic_signatures=="none"){
cosmic_signatures<-read.csv(file="cosmic_signatures.csv",header=TRUE)
cosmic_signatures = as.matrix(cosmic_signatures[,3:ncol(cosmic_signatures)])
}
A<-matrix(0L,nrow=ncol(signatures),ncol=ncol(cosmic_signatures))
rownames(A)=colnames(signatures)
colnames(A)=colnames(cosmic_signatures)
for(i in 1:(ncol(signatures))){
for(j in (1:ncol(cosmic_signatures))){
A[i,j]=cosine.similarity(signatures[,i],cosmic_signatures[,j])
}
}
return(myImagePlot(A**4))
}
###################################### 5) Analysis functions ######################################
matrix_reconstruction=function(exposure,signatures){
"
Compute the matrix product exposure*signatures = reconstructed matrix
Args:
- exposure: [nrow=n_signatures,ncol=n_samples]
- signatures: [nrow=96,ncol=nsignatures]
Returns:
- reconstructed matrix
"
if(nrow(exposure)!=ncol(signatures)){
stop(print("The size of the matrix are not compatible"))
}
n_signatures=nrow(exposure)
n_samples=ncol(exposure)
n_channels=nrow(signatures)
reconstructed_matrix=matrix(0,nrow=n_channels,ncol=n_samples)
for(i in seq(1,n_samples)){
reconstructed_sample=rep(0,96)
for(j in seq(1,n_signatures)){
reconstructed_sample=reconstructed_sample+exposure[j,i]*signatures[,j]
}
reconstructed_matrix[,i]=reconstructed_sample
}
return(reconstructed_matrix)
}
plot_similarity_matrix=function(signatures_1,signatures_2){
"
plot_similarity_matrix plots the similarity matrix between signatures_1 and signatures_2 according to the cosine similarity
Args:
- signatures_1: first set of signatures [nrow=96,ncol=number_of_signatures]
- signatures_2: second set of signatures [nrow=96,ncol=number_of_signatures]
Returns:
- Plot of the colored similarity matrix
"
cos_sim<-matrix(0L,nrow=ncol(signatures_1),ncol=ncol(signatures_2))
for(i in 1:ncol(signatures_1)){
for(j in 1:ncol(signatures_2)){
cos_sim[i,j]=(cosine.similarity(signatures_1[,i],signatures_2[,j]))**4
}
}
myImagePlot(cos_sim)
}
exposure_to_clusters=function(exposure){
"
exposure_to_clusters takes the matrix of exposure, performs a HC and plot the obtained clusters given by the HC
Args:
- exposure: matrix of signature activities by samples [nrow=number_of_signatures,ncol=number_of_samples]
Returns:
- Plot the dendrogram, the given clusters (cosine sim) and the contribution of the signatures
- the permutation to apply in order to gather samples by cluster
"
# Normalization
exposure=row_normalization(exposure)
# Similarity matrix (according to the cosine similarity)
cos_sim_mat=matrix(0L,ncol=nrow(exposure),nrow=nrow(exposure))
for(i in seq(1,nrow(exposure))){
for(j in seq(1,nrow(exposure))){
cos_sim_mat[i,j]=cosine.similarity(exposure[i,],exposure[j,])
}
}
# Hierarchical clustering
dd <- dist(scale(exposure), method = "euclidean")
hc <- hclust(dd, method = "ward.D2")
dend <- as.dendrogram(hc)
dend_data <- dendro_data(dend, type = "rectangle")
# Permutation of the samples in the order given by the HC
reo=c()
for(name in dend_data$labels$label){
reo=c(reo,which(rownames(exposure)==name))
}
#Plots
plot(as.phylo(hc), cex = 0.6, label.offset = 0.5)
myImagePlot(cos_sim_mat[reo,reo]**4,min=0.,max=1)
myImagePlot(exposure[reo,],min=0,max=1)
return(reo)
}
###################################### 6) Matrix normalization ######################################
column_normalization=function(matrix){
"
column_normalization normalizes the columns of a matrix
Args:
- matrix: a matrix
Returns:
- the input matrix normalized by column
"
for (i in seq(1,ncol(matrix))){
matrix[,i]=matrix[,i]/sum(matrix[,i])
}
return(matrix)
}
row_normalization=function(matrix){
"
row_normalization normalizes the rows of a matrix
Args:
- matrix: a matrix
Returns:
- the input matrix normalized by column
"
for (i in seq(1,nrow(matrix))){
matrix[i,]=matrix[i,]/sum(matrix[i,])
}
return(matrix)
}
###################################### 7) Data loading functions ######################################
vcf_to_mutmat=function(PATH,name){
"
Takes the path of a vcf file and convert it to a count matrix
Args:
- PATH: string of the path of the vcf file
- name: string of the name of the vcf file
Returns:
- count matrix dim=[96,1]
"
ref_genome = "BSgenome.Hsapiens.UCSC.hg19"
vcf_file=PATH
sample=name
vcf=read_vcfs_as_granges(vcf_file,sample,ref_genome)
mut_mat <- mut_matrix(vcf_list = vcf, ref_genome = ref_genome)
return(as.numeric(t(mut_mat)))
}
vcfs_to_mutmat=function(FOLDER_PATH,names){
"
Takes the path of a vcf file and convert it to a count matrix
Args:
- FOLDER_PATH: path of the folder in which all the vcfs are gathered
- names: vector of the names of the vcf files
Returns:
- count matrix dim=[96,n_vcf_files]
"
ref_genome = "BSgenome.Hsapiens.UCSC.hg19"
vcf_files = list.files(path=FOLDER_PATH, full.names = T)
sample=names
vcf=read_vcfs_as_granges(vcf_files,sample,ref_genome)
mut_mat <- mut_matrix(vcf_list = vcf, ref_genome = ref_genome)
return(mut_mat)
}
get_sigpro_signatures=function(FOLDER_PATH,K,type="96"){
"
Takes the path of a vcf file and convert it to a count matrix
Args:
- FOLDER_PATH: folder of the SigProfiler extraction
- K: the value of K for which we want to get the results
Returns:
- the signatures from the extraction [96,n_signatures]
"
SName=paste(FOLDER_PATH,"SBS",type,"/All_solutions/SBS",type,"_",K,"_Signatures/SBS",type,"_S",K,"_Signatures.txt",sep="")
signatures=read.delim(SName,header=T)
rownames(signatures)=signatures[,1]
signatures=signatures[,2:(1+K)]
return(signatures)
}
get_sigpro_activities=function(FOLDER_PATH,K,type="96"){
"
Takes the path of a vcf file and convert it to a count matrix
Args:
- FOLDER_PATH: folder of the SigProfiler extraction
- K: the value of K for which we want to get the results
Returns:
- the activities of each signatures / sample [n_samples,n_signatures+1] (a column for the sample names)
"
AName=paste(FOLDER_PATH,"SBS",type,"/All_solutions/SBS",type,"_",K,"_Signatures/SBS",type,"_S",K,"_Activities.txt",sep="")
activities=read.delim(AName,header=T)
rownames(activities)=activities[,1]
activities=activities[,2:(1+K)]
return(activities)
}
get_sigpro_stats=function(FOLDER_PATH,K,type="96"){
"
Takes the path of a vcf file and convert it to a count matrix
Args:
- FOLDER_PATH: folder of the SigProfiler extraction
- K: the value of K for which we want to get the results
Returns:
- the reconstruction stats for each sample [n_samples,...]
"
StName=paste(FOLDER_PATH,"SBS",type,"/All_solutions/SBS",type,"_",K,"_Signatures/SBS",type,"_S",K,"_Samples_stats.txt",sep="")
stats=read.delim(StName,header=T)
rownames(stats)=stats[,1]
stats=stats[,2:ncol(stats)]
return(stats)
}
###################################### 8) Bootstrapping functions ######################################
profile_bootstrap=function(profile){
"
Takes a profile and resample it -> returns the bootstrapped profile
Args:
- profile: 96-channels profile [96,1]
Returns:
- the bootstrapped profile dim=[96,1]
"
profile_norm=profile/sum(profile)
boot=sample(96, sum(profile), prob = profile_norm, replace = T)
new_profile=rep(0,96)
for(i in boot){
new_profile[i]=new_profile[i]+1
}
return(new_profile)
}
fit_boot=function(sample,signatures,sample_name="Signature distribution",nboot=1000){
"
Takes a sample, resample it nboot times and fit each boostrapped sample with the set of signatures
Args:
- sample: 96-channels profile
- signatures: signatures that will be used for the fitting [96,n_sigs]
- nboot: number of bootstrap resampling
Returns:
- a list (contribution,reconstructed) of the contribution for each bootstrapped sample
"
samples=matrix(0L,ncol=nboot,nrow=96)
samples[,1]=sample
for(i in seq(2,nboot)){
samples[,i]=profile_bootstrap(sample)
}
boot_1=fit_to_signatures(samples,as.matrix(signatures))
d=as.data.frame(t(boot_1$contribution))
return(boot_1)
}
plot_boot=function(sample,signatures,sample_name="Signature distribution",nboot=1000){
"
Takes a sample, resample it nboot times and fit each boostrapped sample with the set of signatures and plot the distribution of activities
Args:
- sample: 96-channels profile
- signatures: signatures that will be used for the fitting [96,n_sigs]
- nboot: number of bootstrap resampling
Returns:
- the plot of the distribution of the activities for each signature
"
boot_1=fit_boot(sample=sample,signatures=signatures,sample_name=sample_name,nboot=nboot)
d=as.data.frame(t(boot_1$contribution))
return(ggplot(data=melt(d))+geom_boxplot(aes(x=variable,y=value))+ggtitle(sample_name)+theme(axis.text.x = element_text(angle = 90, hjust = 1)))
}
sieve_to_bootstrap=function(sieve,threshold=0.85,samples,signatures,sample_name="Signature distribution",nboot=1000){
ind_sigs=which(sieve[,colnames(sieve)==sample_name]>threshold)
sample=samples[,which(colnames(samples)==sample_name)]
return(plot_boot(sample=sample,signatures[,ind_sigs],sample_name=sample_name,nboot=1000))
}
add_poisson_noise=function(profile){
for(i in seq(1,length(profile))){
profile[i]=rpois(1, lambda = profile[i])
}
return(profile)
}
###################################### 9) Phylogeny ######################################
#PARTIE CALCUL DE COORDONNEES
calculate_coordinates=function(K,signatures,cosine_cutoff=0.5){
# INPUT
# K: final number of extraction
# signatures: /!\ has to be the list of the signatures for the different values of K : list(K1signatures,K2signatures...)
# cosine_cutoff: cutoff value from which we consider that 2 signatures are the same
# /!\ The plotting function is very sensitive to this value -> you have to try values between 0.95 and 0.99
# Rk: the form of Ksignatures has to be [96,number_of_signatures]
#Table of coordinates
X=matrix(0L, nrow=K, ncol = K)
Y=matrix(0L, nrow=K, ncol = K)
#Pas
#pas=16*c(128,64,32,16,8,4,2)
pas=c()
for(i in seq(1,K)){
pas=c(2**i,pas)
}
pas=16*pas
# Keep the info to create the futur branches
split_inds=c(1)
target_inds=matrix(0L, nrow=2, ncol = K)
assignation_inds=matrix(0L, nrow=K, ncol = K)
#Init
target_inds[1,1]=1
target_inds[2,1]=2
for(i in seq(1,K)){
for(j in seq(1,i)){
X[j,i]=5*(i-1)
}
}
Y[1:2,2]=c(pas[2],-pas[2])
for(Ki in seq(2,K-1)){
assignation=rep(0,Ki)
target=rep(0,Ki+1)
sigs1=signatures[[Ki]]
sigs2=signatures[[Ki+1]]
#New line
maxs=c()
#
for(i in seq(1,Ki)){
cos=c()
for(j in seq(1,Ki+1)){
cos=c(cos,cosine.similarity(sigs1[,i],sigs2[,j]))
}
if(max(cos)>cosine_cutoff){
assignation[i]=which.max(cos)
target[which.max(cos)]=1
}
# New
maxs=c(maxs,max(cos))
#
}
# OLD VERSION
#ind_splitting=which(assignation==0)
#inds_target=which(target==0)
#
# NEW VERSION: avoid the bug when all the max(cos)>cutoff
print(sum(1*(maxs>cosine_cutoff))==length(maxs))
if(sum(1*(maxs>cosine_cutoff))==length(maxs)){
assignation[which.min(maxs)]=0
cos=c()
for(j in seq(1,Ki+1)){
cos=c(cos,cosine.similarity(sigs1[,which.min(maxs)],sigs2[,j]))
}
target[which.max(cos)]=0
}
ind_splitting=which(assignation==0)
inds_target=which(target==0)
#
#Checking
if(is.na(inds_target[1])){
inds_target[1]=0
}
if(is.na(inds_target[2])){
inds_target[2]=0
}
print(ind_splitting)
if(is.na(ind_splitting)){
ind_splitting=0
}
#For next
split_inds=c(split_inds,ind_splitting)
target_inds[1,Ki]=inds_target[1]
target_inds[2,Ki]=inds_target[2]
assignation_inds[1:length(assignation),Ki]=assignation
# Parcours de assignation pour checker les signatures statiques
for(ind in seq(1,length(assignation))){
if(assignation[ind]>0){
Y[assignation[ind],i+1]=Y[ind,Ki]
}
else{
Y[inds_target[1],Ki+1]=Y[ind,Ki]-pas[Ki+1]
Y[inds_target[2],Ki+1]=Y[ind,Ki]+pas[Ki+1]
}
}
}
return(list(X,Y,split_inds,target_inds,assignation_inds))
}
calculate_paths=function(K,X,Y,split_inds,target_inds,assignation_inds){
paths=matrix(0L, nrow=K, ncol = K)
paths[1,1]=1
first_new=2
for(i in seq(1,K-1)){
split_ind=split_inds[i]
target_ind=target_inds[,i]
for(j in seq(1,i)){
if(paths[j,i]==split_ind){
paths[first_new,]=paths[j,]
paths[j,i+1]=target_ind[1]
paths[first_new,i+1]=target_ind[2]
first_new=first_new+1
}
else{
paths[j,i+1]=assignation_inds[paths[j,i],i]
}
}
}
return(paths)
}
calculates_paths_coordinates=function(K,paths,X,Y){
X_plot=matrix(0L, nrow=K, ncol = K)
Y_plot=matrix(0L, nrow=K, ncol = K)
for(i in seq(1,K)){
for(j in seq(1,K)){
if(paths[i,j]!=0){
X_plot[i,j]=X[paths[i,j],j]
Y_plot[i,j]=Y[paths[i,j],j]
}
}
}
return(list(X_plot,Y_plot))
}
assign_one_to_cosmic=function(profile,cosmic){
cos=rep(0,ncol(cosmic))
for(i in seq(1,ncol(cosmic))){
cos[i]=cosine.similarity(profile,cosmic[,i])
}
return(list(colnames(cosmic)[which.max(cos)],max(cos)))
}
convert_paths_to_letters=function(paths){
paths_sigs=matrix(0L, nrow=nrow(paths), ncol = ncol(paths))
for(i in seq(1,nrow(paths))){
for(j in seq(1,ncol(paths))){
paths_sigs[i,j]=paste("Sig",LETTERS[paths[i,j]],sep=" ")
}
}
return(paths_sigs)
}