-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFinal.R
1798 lines (1671 loc) · 79.1 KB
/
Final.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
######################################## Algorithm Implementation ########################################
# A Multi-metric Algorithm for Hierarchical Clustering of Same-length Protein Sequences - Final.R
# Tsarouchis Sotrios - Filippos
# email: [email protected]
# AEM: 7999
######################################## Install or load necessary libraries ########################################
ipak <- function(pkg){
new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])]
if (length(new.pkg))
install.packages(new.pkg, dependencies = TRUE)
sapply(pkg, require, character.only = TRUE)
}
packages <- c("stringr","dplyr","entropy","ggplot2","ggseqlogo","gridExtra","cluster","seqinr","collapsibleTree","data.tree","DiagrammeR","stringdist","igraph","networkD3","plsgenomics","shinycssloaders","shiny","shinyFiles","shinyjs","shinyBS","DT","plotly","xtable","tictoc","data.table","pryr")
ipak(packages)
######################################## Insert data and Initialize algorithm values ########################################
# Insert Data from csv
data <- read.csv(file.choose(), header = TRUE, sep = ";")
# Keep the desired columns based on the input data
udata = data[,c("Sequence.ID","AA.JUNCTION","V.GENE.and.allele")]
#udata = data[,c("Sequence.ID","J.GENE.and.allele","AA.JUNCTION","V.GENE.and.allele")]
udata$AA.JUNCTION <- as.character(udata$AA.JUNCTION)
sim = list("F","W",c("A","I","L","V"),c("M","C"),"P","G","Y",c("T","S"),c("H","K","R"),c("E","D"),c("Q","N"))
# Naming the group of similarities
names(sim) = c("F","W","Al","Su","P","G","Y","Hy","Ba","Ac","Am")
altsim = list("F","W",c("A","I","L","V"),c("M","C"),"P","G","Y",c("T","S"),c("H","K","R"),c("E","D"),c("Q","N"))
# Naming the group of similarities
names(altsim) = c("f","w","a","s","p","g","y","h","b","c","m")
# A table with the letters
let = c("A","C","D","E","F","G","H","I","K","L","M","N","P","Q","R","S","T","V","W","Y") # The letters matrix
# An empty vector wich will store the level for every cluster
clep = vector('numeric')
br = 0 # Initial value of branch
cl = 0 # Initial value of new clusters
met = 0 # Initial value of level capacity counter
ep = 1 # Initial value of level
d = 0
nn = FALSE # Initial value for the condition sumper < endper
endper = 90 # Set the percentage, which ends the programm
listxx = list() # Initialize a list for saving the permat of all branches
listyy = list() # Initialize a list for saving the persim of all branches
dfsum = data.frame(sumper = numeric(0),sumper2 = numeric(0),branch = numeric(0), len = numeric(0))
dfsd = data.frame(ff = character(0),Average_Identity_Value = numeric(0),Identity_Standar_Deviation = numeric(0),Average_Similarity_Value = numeric(0), Similarity_Standar_Deviation = numeric(0), stringsAsFactors = FALSE)
ggdf = data.frame(branch = numeric(0), len = numeric(0))
last = 0
flagtic = TRUE
udata$AA.JUNCTION = as.character(udata$AA.JUNCTION)
udata$clusters = 0 # Initialiaze the column clusters with 0
udata$level.0 = 0 # Initialize the column of cl.0 with 0
udata$temp= 0 # Creating a temp column with 0
progend = FALSE # flag which end the programm execution
listax = list()
listax$temp = 1:length(udata$AA.JUNCTION)
names(listax)[length(listax)] = sprintf('cl.%d', 0)
listq = list("listax" = listax,"ggdf" = ggdf, "dfsum" = dfsum,"list" = listxx, "listn" = listyy,"udata" = udata,"permat"= NA, "persim" = NA, "br" = br, "cl" = cl, "met" = met, "ep" = ep , "clep" = clep, "nn" = nn, "sumper" = NA,"sumper2" = NA, "ela" = NA, "cel" = NA,"endper" = endper, "last" = last,"progend" = progend, "leaf" = FALSE,"leaf2" = FALSE)
algo = "Identity" # Initial value of algo
algocol = 0 # Initial value of algocol
backcol = 0 # Initial value of backcol
backcolj6 = 0 # Initial value of backcolj6
listb = listq
levcut = 3
levcut =levcut +1
leaf2 = FALSE
enthr = FALSE
######################################## Function Matrices ########################################
# Function Matrices compute the apsolute matrix, the matrix with percentages, the absolute similarity matrix and the percentage similarity matrix
# Function Matrices contains the old function Finish. Finish compute cluster's identity and similarity and stop cluster's division if identity or similarity is greater than endper
Matrices <- function(list1){
# Count the execution time of Matrices
tic()
# Keep data up to date
udata = list1$udata
br = list1$br
permat = list1$permat
persim = list1$persim
cl = list1$cl
listxx = list1$list
listyy = list1$listn
sumper = list1$sumper
sumper2 = list1$sumper2
endper = list1$endper
dfsum = list1$dfsum
nn = list1$nn
last = list1$last
progend = list1$progend
leaf = list1$leaf
leaf2 = list1$leaf2
# Find the sequences with gene J6
ind1 = str_which(udata[udata$clusters == br,]$J.GENE.and.allele,"J6")
qw = 1:length(udata[udata$clusters == br,]$AA.JUNCTION)
if(length(ind1) == 0){
ind2 = qw
}else{
ind2 = qw[-ind1]
}
# Initialize matrices for J6 sequences
mymat1 = matrix(0,nrow=length(let), ncol=str_length(udata$AA.JUNCTION[1]))
simmat1 = matrix(0,nrow = length(sim),ncol =str_length(udata$AA.JUNCTION[1]))
rownames(mymat1) = let
rownames(simmat1) = c("F","W","Al","Su","P","G","Y","Hy","Ba","Ac","Am")
# Initialize matrices for NO J6 sequences
mymat2 = matrix(0,nrow=length(let), ncol=str_length(udata$AA.JUNCTION[1]))
simmat2 = matrix(0,nrow = length(sim),ncol =str_length(udata$AA.JUNCTION[1]))
rownames(mymat2) = let
rownames(simmat2) = c("F","W","Al","Su","P","G","Y","Hy","Ba","Ac","Am")
# Initialize matrices for all sequences
permat = matrix(0,nrow=length(let) + 1, ncol=str_length(udata$AA.JUNCTION[1]))
rownames(permat) = c(let,"Entropy")
persim = matrix(0,nrow = length(sim)+1,ncol =str_length(udata$AA.JUNCTION[1]))
rownames(persim) = c("F","W","Al","Su","P","G","Y","Hy","Ba","Ac","Am","Entropy")
# Compute matrices for J6 sequences
if(length(ind1) != 0 ){
trimudata = strsplit(udata[udata$clusters == br,]$AA.JUNCTION[ind1],"")
align = data.frame(matrix(unlist(trimudata), nrow=length(trimudata), byrow=T))
for(i in (algocol+1):(str_length(udata[udata$clusters == br,]$AA.JUNCTION[1]) - backcolj6)){
temptab = plyr::count(align[i],vars = colnames(align)[i])
names(temptab)[1] = "X1"
mymat1[which(is.na(match(names(mymat1[,i]),as.vector(unlist(temptab[1])))) == FALSE),i] = as.vector(unlist(temptab[2]))
temptab1 = temptab
gg = as.vector(unlist(temptab1[1]))
temptab1[1] = sapply(1:length(gg),function(x) gsub('[[:digit:]]+', '', names(unlist(sim)[which(str_detect(unlist(sim),gg[x]))])))
#temptab1[1] = names(sim)[sapply(as.vector(unlist(temptab1[1])),function(x) which(str_detect(sim,x)))]
temptab1 = aggregate(temptab1[2], by=temptab1[1], FUN=sum)
simmat1[sapply(as.vector(unlist(temptab1[1])),function(x) which(names(sim) == x)),i] = as.vector(unlist(temptab1[2]))
}
}
# Compute matrices for NO J6 sequences
if(length(ind2) != 0 ){
trimudata = strsplit(udata[udata$clusters == br,]$AA.JUNCTION[ind2],"")
align = data.frame(matrix(unlist(trimudata), nrow=length(trimudata), byrow=T))
for(i in (algocol+1):(str_length(udata[udata$clusters == br,]$AA.JUNCTION[1]) - backcol)){
temptab = plyr::count(align[i],vars = colnames(align)[i])
names(temptab)[1] = "X1"
mymat2[which(is.na(match(names(mymat2[,i]),as.vector(unlist(temptab[1])))) == FALSE),i] = as.vector(unlist(temptab[2]))
permat[length(let) + 1,i] = entropy(xtabs(freq ~ X1, temptab),base=exp(1))
temptab1 = temptab
gg = as.vector(unlist(temptab1[1]))
temptab1[1] = sapply(1:length(gg),function(x) gsub('[[:digit:]]+', '', names(unlist(sim)[which(str_detect(unlist(sim),gg[x]))])))
temptab1 = aggregate(temptab1[2], by=temptab1[1], FUN=sum)
simmat2[sapply(as.vector(unlist(temptab1[1])),function(x) which(names(sim) == x)),i] = as.vector(unlist(temptab1[2]))
persim[length(sim)+1,i] = entropy(xtabs(freq ~ X1, temptab1),base = exp(1))
}
}
# Combine matrices for No J6 and J6 sequences
mymat = mymat1 + mymat2
simmat = simmat1 + simmat2
meg = length(ind1) + length(ind2)
if(length(ind2) == 0 || backcol == backcolj6){
permat[1:length(let),(algocol+1):(str_length(udata[udata$clusters == br,]$AA.JUNCTION[1]) - backcolj6)] = (mymat[,(algocol+1):(str_length(udata[udata$clusters == br,]$AA.JUNCTION[1]) - backcolj6)] / meg) * 100
persim[1:length(sim),(algocol+1):(str_length(udata[udata$clusters == br,]$AA.JUNCTION[1]) - backcolj6)] = (simmat[,(algocol+1):(str_length(udata[udata$clusters == br,]$AA.JUNCTION[1]) - backcolj6)] / meg) * 100
}else{
permat[1:length(let),(algocol+1):(str_length(udata[udata$clusters == br,]$AA.JUNCTION[1]) - backcolj6)] = (mymat[,(algocol+1):(str_length(udata[udata$clusters == br,]$AA.JUNCTION[1]) - backcolj6)] / meg) * 100
persim[1:length(sim),(algocol+1):(str_length(udata[udata$clusters == br,]$AA.JUNCTION[1]) - backcolj6)] = (simmat[,(algocol+1):(str_length(udata[udata$clusters == br,]$AA.JUNCTION[1]) - backcolj6)] / meg) * 100
if(backcolj6 != 0){
permat[1:length(let),(str_length(udata[udata$clusters == br,]$AA.JUNCTION[1]) - backcolj6 + 1):(str_length(udata[udata$clusters == br,]$AA.JUNCTION[1]) - backcol)] = (mymat[,(str_length(udata[udata$clusters == br,]$AA.JUNCTION[1]) - backcolj6 + 1):(str_length(udata[udata$clusters == br,]$AA.JUNCTION[1]) - backcol)] / length(ind2)) * 100
persim[1:length(sim),(str_length(udata[udata$clusters == br,]$AA.JUNCTION[1]) - backcolj6 + 1):(str_length(udata[udata$clusters == br,]$AA.JUNCTION[1]) - backcol)] = (simmat[,(str_length(udata[udata$clusters == br,]$AA.JUNCTION[1]) - backcolj6 + 1):(str_length(udata[udata$clusters == br,]$AA.JUNCTION[1]) - backcol)] / length(ind2)) * 100
}
}
# Find the Entropy for all the sequences
trimudata = strsplit(udata[udata$clusters == br,]$AA.JUNCTION,"")
align = data.frame(matrix(unlist(trimudata), nrow=length(trimudata), byrow=T))
for(i in 1:(str_length(udata[udata$clusters == br,]$AA.JUNCTION[1]))){
temptab = plyr::count(align[i],vars = colnames(align)[i])
names(temptab)[1] = "X1"
permat[length(let) + 1,i] = entropy(xtabs(freq ~ X1, temptab),base=exp(1))
temptab1 = temptab
gg = as.vector(unlist(temptab1[1]))
temptab1[1] = sapply(1:length(gg),function(x) gsub('[[:digit:]]+', '', names(unlist(sim)[which(str_detect(unlist(sim),gg[x]))])))
temptab1 = aggregate(temptab1[2], by=temptab1[1], FUN=sum)
persim[length(sim)+1,i] = entropy(xtabs(freq ~ X1, temptab1),base = exp(1))
}
if(algocol != 0 && backcol!=0){
# Initialize matrices
mymat3 = matrix(0,nrow=length(let), ncol=str_length(udata$AA.JUNCTION[1]))
simmat3 = matrix(0,nrow = length(sim),ncol =str_length(udata$AA.JUNCTION[1]))
rownames(mymat3) = let
rownames(simmat3) = c("F","W","Al","Su","P","G","Y","Hy","Ba","Ac","Am")
permat3 = matrix(0,nrow=length(let) + 1, ncol=str_length(udata$AA.JUNCTION[1]))
rownames(permat3) = c(let,"Entropy")
persim3 = matrix(0,nrow = length(sim)+1,ncol =str_length(udata$AA.JUNCTION[1]))
rownames(persim3) = c("F","W","Al","Su","P","G","Y","Hy","Ba","Ac","Am","Entropy")
trimudata = strsplit(udata[udata$clusters == br,]$AA.JUNCTION,"")
align = data.frame(matrix(unlist(trimudata), nrow=length(trimudata), byrow=T))
exc = 1:algocol
exc2 = (str_length(udata[udata$clusters == br,]$AA.JUNCTION[1]) - backcol):str_length(udata[udata$clusters == br,]$AA.JUNCTION[1])
exc = c(exc,exc2)
for(i in 1:length(exc)){
temptab = plyr::count(align[exc[i]],vars = colnames(align)[exc[i]])
names(temptab)[1] = "X1"
mymat3[which(is.na(match(names(mymat3[,exc[i]]),as.vector(unlist(temptab[1])))) == FALSE),exc[i]] = as.vector(unlist(temptab[2]))
permat3[length(let) + 1,exc[i]] = entropy(xtabs(freq ~ X1, temptab),base=exp(1))
temptab1 = temptab
gg = as.vector(unlist(temptab1[1]))
temptab1[1] = sapply(1:length(gg),function(x) gsub('[[:digit:]]+', '', names(unlist(sim)[which(str_detect(unlist(sim),gg[x]))])))
#temptab1[1] = names(sim)[sapply(as.vector(unlist(temptab1[1])),function(x) which(str_detect(sim,x)))]
temptab1 = aggregate(temptab1[2], by=temptab1[1], FUN=sum)
simmat3[sapply(as.vector(unlist(temptab1[1])),function(x) which(names(sim) == x)),exc[i]] = as.vector(unlist(temptab1[2]))
persim3[length(sim)+1,i] = entropy(xtabs(freq ~ X1, temptab1),base = exp(1))
}
permat3[1:length(let),] = (mymat3 / length(udata[udata$clusters == br,]$AA.JUNCTION)) * 100
persim3[1:length(sim),] = (simmat3 / length(udata[udata$clusters == br,]$AA.JUNCTION)) * 100
permat[1:length(let),exc] = permat3[1:length(let),exc]
persim[1:length(sim),exc] = persim3[1:length(sim),exc]
}
# Keep a list with total permat matrix
listxx$temp = permat
names(listxx)[length(listxx)] = sprintf('permat_br.%d', br) # Save the permat with this format
# Keep a list with total persim matrix
listyy$temp = persim
names(listyy)[length(listyy)] = sprintf('persim_br.%d', br) # Save the persim with this format
################################ Old Finish ###########################
t1 = which(permat[-nrow(permat),] == 100,arr.ind = TRUE)
sumper = (length(as.numeric(t1[,2]))* 100) / str_length(udata$AA.JUNCTION[1]) # Compute Identity
t2 = which(persim[-nrow(persim),] == 100,arr.ind = TRUE)
sumper2 = (length(as.numeric(t2[,2]))* 100) / str_length(udata$AA.JUNCTION[1]) # Compute Similarity
vv = length(udata[udata$clusters == br,]$AA.JUNCTION) # Compute cluster sequences
dfsum[nrow(dfsum) + 1,] = c(sumper,sumper2,br,vv)
# Check if the clusters division needs to stop
if(algo == "Identity"){
if (sumper > endper && leaf == FALSE){
nn = TRUE # When nn = TRUE the percentage of sumper < endper%
if (sumper2 > endper && leaf == FALSE){
leaf2 = TRUE
}
}
}else{
if (sumper2 > endper){
leaf2 = TRUE
}
}
# The return list
result1 = list("listax" = list1$listax,"ggdf" = list1$ggdf, "dfsum" = dfsum,"list" = listxx, "listn" = listyy, "udata" = udata,"permat"= permat, "persim" = persim, "br" = br, "cl" = cl, "met" = list1$met, "ep"= list1$ep, "clep" = list1$clep,"nn" = nn, "sumper" = sumper, "sumper2" = sumper2, "ela" = list1$ela, "cel" = list1$cel,"endper" = list1$endper, "last" = last, "progend" = progend, "leaf" = leaf,"leaf2" = leaf2)
en = toc(quiet = TRUE)
cat(paste0("Matrices","\t",length(udata[udata$clusters == br,]$AA.JUNCTION),"\t",str_length(udata$AA.JUNCTION[1]),"\t",en$toc - en$tic,"\t",(pryr::mem_used() / 10^6)), file=logFile, append=TRUE, sep = "\n")
if ( leaf == TRUE){
nn = FALSE
result1 = list("listax" = list1$listax,"ggdf" = list1$ggdf, "dfsum" = dfsum,"list" = listxx, "listn" = listyy, "udata" = udata,"permat"= permat, "persim" = persim, "br" = br, "cl" = cl, "met" = list1$met, "ep"= list1$ep, "clep" = list1$clep,"nn" = nn, "sumper" = sumper, "sumper2" = sumper2, "ela" = list1$ela, "cel" = list1$cel,"endper" = list1$endper, "last" = last, "progend" = progend, "leaf" = leaf,"leaf2" = leaf2)
return(result1)
}else{
return(result1)
}
}
######################################## Function Choice ########################################
# Function Choice choose which matrix cell will be used for the division of the data
# Function Choice contains the old Divide. Divide is responsible for dividing the sequences based on the cell given.
# Function Choice also contains the old Control. Control is responsible for updating level, cluster and other counters as well as for stopping the algorithm
Choice <- function(list2){
# Count the execution time of Choices
tic()
# Keep data up to date
udata = list2$udata
br = list2$br
cl = list2$cl
nn = list2$nn
cel = list2$cel
ela = list2$ela
met = list2$met
ep = list2$ep
clep = list2$clep
ggdf = list2$ggdf
progend = list2$progend
leaf = list2$leaf
listax = list2$listax
leaf2 = list2$leaf2
# Find desired cell for division
if(nn == TRUE || (algo == "Similarity") ){
permat = list2$persim # If sumper < endper% we want to check only the persim matrix
}else{
permat =list2$permat # Else permat and if it is necessary the persim matrix
persim = list2$persim
}
cel = which(permat[,(algocol + 1):(ncol(permat)-backcol)] == max(permat[,(algocol + 1):(ncol(permat)-backcol)]), arr.ind = TRUE)
ela = 1
poss = max(permat[,(algocol + 1):(ncol(permat)-backcol)])
# We exclude the 100 % from the max values
if (max(permat[,(algocol + 1):(ncol(permat)-backcol)]) == 100){
cel = which(permat[,(algocol + 1):(ncol(permat)-backcol)] == max(permat[,(algocol + 1):(ncol(permat)-backcol)][permat[,(algocol + 1):(ncol(permat)-backcol)]!=max(permat[,(algocol + 1):(ncol(permat)-backcol)])]), arr.ind = TRUE) # The desired cell
poss = max(permat[,(algocol + 1):(ncol(permat)-backcol)][permat[,(algocol + 1):(ncol(permat)-backcol)]!=max(permat[,(algocol + 1):(ncol(permat)-backcol)])])
}
# Check if clusters division is stopped or not
if(leaf2 == FALSE && poss != 0){
# if cel contain more than one cells, find the best cell matching some criteria
ela = 1
if(algo == "Identity"){
if ((length(cel)/2) > 1){
dddff = min(permat[,(algocol + 1):(ncol(permat)-backcol)][nrow(permat[,(algocol + 1):(ncol(permat)-backcol)]),cel[,2]])
dddff2 = which(permat[,(algocol + 1):(ncol(permat)-backcol)][nrow(permat[,(algocol + 1):(ncol(permat)-backcol)]),cel[,2]] == dddff)
ela = dddff2[1]
if (length(dddff2)>1 && nn == FALSE){ # If the vector has 2 or more numbers means that we have columns with the same entropy and nn = FALSE in order not to double check the persim
dddff3 = persim[,(algocol + 1):(ncol(permat)-backcol)][sapply(1:length(dddff2), function (x){ str_which(names(sim),gsub('[[:digit:]]+', '', names(unlist(sim)[which(str_detect(unlist(sim),let[cel[x,1]]))])))}),cel[,2]]
dddff3 = max(diag(dddff3))
dddff4 = which(diag( persim[,(algocol + 1):(ncol(permat)-backcol)][sapply(1:length(dddff2), function (x){str_which(names(sim),gsub('[[:digit:]]+', '', names(unlist(sim)[which(str_detect(unlist(sim),let[cel[x,1]]))])))}),cel[,2]]) == dddff3)
ela = dddff4[1]
if(length(dddff4)> 1){
dddff5 = min(persim[,(algocol + 1):(ncol(permat)-backcol)][nrow(persim[,(algocol + 1):(ncol(permat)-backcol)]),cel[dddff4,2]])
dddff6 = which(persim[,(algocol + 1):(ncol(permat)-backcol)][nrow(persim[,(algocol + 1):(ncol(permat)-backcol)]),cel[dddff4,2]] == dddff5)
ela = dddff6[1]
}
}
}
}else{
if ((length(cel)/2) > 1){
dddff = min(permat[,(algocol + 1):(ncol(permat)-backcol)][nrow(permat[,(algocol + 1):(ncol(permat)-backcol)]),cel[,2]])
dddff2 = which(permat[,(algocol + 1):(ncol(permat)-backcol)][nrow(permat[,(algocol + 1):(ncol(permat)-backcol)]),cel[,2]] == dddff)
ela = dddff2[1]
}
}
nn = FALSE # Return nn in it's original value
##################################################### Old Divide ############################
# If we need a new level, then we create a new column in udata dataframe with its name (level.ep)
if (met == 0) {
udata$temp = NA
names(udata)[length(udata)] = sprintf('level.%d', ep)
}
if (algo == "Identity"){
# Find sequences contains the cell's letter in cell's position
x1 = str_which(str_detect(str_sub(udata[udata$clusters == br,]$AA.JUNCTION,(cel[ela,2]+algocol),(cel[ela,2]+algocol)), let[cel[ela,1]]), "TRUE")
mk1 = length(x1)
cltp1 = cl + 1
y1 = udata[udata$clusters == br,]$AA.JUNCTION
z1 = y1[x1]
# The other sequences of the cluster
x2 = str_which(str_detect(str_sub(udata[udata$clusters == br,]$AA.JUNCTION,(cel[ela,2]+algocol),(cel[ela,2]+algocol)), let[cel[ela,1]]), "FALSE")
mk2 = length(x2)
cltp2 = cl + 2
y2 = udata[udata$clusters == br,]$AA.JUNCTION
z2 = y2[x2]
lengdif = FALSE
# Find wich new sub-cluster has more sequences and give it first cluster name
if(mk1 < mk2){
lengdif = TRUE
templeng = z1
z1 = z2
z2 = templeng
temp2 = x1
x1 = x2
x2 = temp2
ggdf[nrow(ggdf) + 1,] = c(cltp1,mk2)
ggdf[nrow(ggdf) + 1,] = c(cltp2,mk1)
}else{
ggdf[nrow(ggdf) + 1,] = c(cltp1,mk1)
ggdf[nrow(ggdf) + 1,] = c(cltp2,mk2)
}
listax$temp = as.vector(unlist(listax[sprintf('cl.%d', br)]))[x1]
names(listax)[length(listax)] = sprintf('cl.%d', cl+1)
listax$temp = as.vector(unlist(listax[sprintf('cl.%d', br)]))[x2]
names(listax)[length(listax)] = sprintf('cl.%d', cl+2)
udata[as.vector(unlist(listax[sprintf('cl.%d', br)]))[x1],sprintf('level.%d', ep)] = cl+1
udata[as.vector(unlist(listax[sprintf('cl.%d', br)]))[x2],sprintf('level.%d', ep)] = cl+2
if(lengdif == TRUE){
udata[udata$clusters == br,]$clusters <- ifelse(str_detect(str_sub(udata[udata$clusters == br,]$AA.JUNCTION,(cel[ela,2]+algocol),(cel[ela,2]+algocol)), let[cel[ela,1]]), cl+2 ,cl+1)
}else{
udata[udata$clusters == br,]$clusters <- ifelse(str_detect(str_sub(udata[udata$clusters == br,]$AA.JUNCTION,(cel[ela,2]+algocol),(cel[ela,2]+algocol)), let[cel[ela,1]]), cl+1 ,cl+2)
}
}else{
# Find sequences contains the cell's similarity group in cell's position
strings.to.find = unlist(sim[cel[ela,1]])
x1 = str_which(str_detect(str_sub(udata[udata$clusters == br,]$AA.JUNCTION,(cel[ela,2]+algocol),(cel[ela,2]+algocol)), str_c(strings.to.find, collapse="|")), "TRUE")
mk1 = length(x1)
cltp1 = cl + 1
y1 = udata[udata$clusters == br,]$AA.JUNCTION
z1 = y1[x1]
# The other sequences of the cluster
x2 = str_which(str_detect(str_sub(udata[udata$clusters == br,]$AA.JUNCTION,(cel[ela,2]+algocol),(cel[ela,2]+algocol)), str_c(strings.to.find, collapse="|")), "FALSE")
mk2 = length(x2)
cltp2 = cl + 2
y2 = udata[udata$clusters == br,]$AA.JUNCTION
z2 = y2[x2]
lengdif = FALSE
# Find wich new sub-cluster has more sequences and give it first cluster name
if(mk1 < mk2){
lengdif = TRUE
templeng = z1
z1 = z2
z2 = templeng
temp2 = x1
x1 = x2
x2 = temp2
ggdf[nrow(ggdf) + 1,] = c(cltp1,mk2)
ggdf[nrow(ggdf) + 1,] = c(cltp2,mk1)
}else{
ggdf[nrow(ggdf) + 1,] = c(cltp1,mk1)
ggdf[nrow(ggdf) + 1,] = c(cltp2,mk2)
}
listax$temp = as.vector(unlist(listax[sprintf('cl.%d', br)]))[x1]
names(listax)[length(listax)] = sprintf('cl.%d', cl+1) # Save the permat with this format
listax$temp = as.vector(unlist(listax[sprintf('cl.%d', br)]))[x2]
names(listax)[length(listax)] = sprintf('cl.%d', cl+2) # Save the permat with this format
udata[as.vector(unlist(listax[sprintf('cl.%d', br)]))[x1],sprintf('level.%d', ep)] = cl+1
udata[as.vector(unlist(listax[sprintf('cl.%d', br)]))[x2],sprintf('level.%d', ep)] = cl+2
if(lengdif == TRUE){
udata[udata$clusters == br,]$clusters <- ifelse(str_detect(str_sub(udata[udata$clusters == br,]$AA.JUNCTION,(cel[ela,2]+algocol),(cel[ela,2]+algocol)), str_c(strings.to.find, collapse="|")), cl+2 ,cl+1)
}else{
udata[udata$clusters == br,]$clusters <- ifelse(str_detect(str_sub(udata[udata$clusters == br,]$AA.JUNCTION,(cel[ela,2]+algocol),(cel[ela,2]+algocol)), str_c(strings.to.find, collapse="|")), cl+1 ,cl+2)
}
}
clep[cl+1] = ep # Level of the cluster cl+1
clep[cl+2] = ep # Level of the cluster cl+2
cl = cl + 2 # Increase the cluster by 2
}else{
leaf2 = FALSE
nn = FALSE
}
############################################ Old Control #############################################
br = br + 1 # Increase the branch by 1
met = met + 2 # Increase the counter by 2
list2 = list("listax" = listax,"ggdf" = ggdf, "dfsum" = list2$dfsum,"list" = list2$list, "listn" = list2$listn, "udata" = udata,"permat"= list2$permat, "persim" = list2$persim, "br" = br, "cl" = cl, "met" = met, "ep"= ep, "clep" = clep,"nn" = nn, "sumper" = list2$sumper, "sumper2" = list2$sumper2, "ela" = ela, "cel" = cel,"endper" = list2$endper, "last" = list2$last,"progend" = progend, "leaf" = leaf,"leaf2" = leaf2)
if( ((clep[br-1] < clep[br]) && (sum(clep == clep[br]) != (2^clep[br]))) == TRUE && (length(which(udata$clusters == br)) > 2) ){ # If the next branch is in the next level
met = geomSeq(1,2,1,1000)[ep+1]
}
while (length(which(udata$clusters == br)) <= 1){ # While the number of sequences in the branch is less than 1, go to the next branch and change counter
# Condition wich ends the algorithm
if(is.na(str_length(udata[udata$clusters == br,]$AA.JUNCTION[1]))){
clmax = cl
brtemp = br
progend = TRUE
list2 = list("listax" = list2$listax,"ggdf" = list2$ggdf, "dfsum" = list2$dfsum,"list" = list2$list, "listn" = list2$listn, "udata" = list2$udata,"permat"= list2$permat, "persim" = list2$persim, "br" = brtemp, "cl" = list2$cl, "met" = list2$met, "ep"= list2$ep, "clep" = list2$clep,"nn" = list2$nn, "sumper" = list2$sumper, "sumper2" = list2$sumper2, "ela" = list2$ela, "cel" = list2$cel,"endper" = list2$endper, "last" = list2$last,"progend" = progend, "leaf" = leaf,"leaf2" = leaf2)
if(brtemp < clmax){
# Find the statistics of the remaining clusters before you end
for (i in (br+1):clmax) {
brtemp = i
list2 = list("listax" = list2$listax,"ggdf" = list2$ggdf, "dfsum" = list2$dfsum,"list" = list2$list, "listn" = list2$listn, "udata" = list2$udata,"permat"= list2$permat, "persim" = list2$persim, "br" = brtemp, "cl" = list2$cl, "met" = list2$met, "ep"= list2$ep, "clep" = list2$clep,"nn" = list2$nn, "sumper" = list2$sumper, "sumper2" = list2$sumper2, "ela" = list2$ela, "cel" = list2$cel,"endper" = list2$endper, "last" = list2$last,"progend" = progend, "leaf" = leaf,"leaf2" = leaf2)
list2 = Matrices(list2)
}
}
en = toc(quiet = TRUE)
cat(paste0("Choice","\t",length(udata[udata$clusters == br,]$AA.JUNCTION),"\t",str_length(udata$AA.JUNCTION[1]),"\t",en$toc - en$tic,"\t",(pryr::mem_used() / 10^6)), file=logFile, append=TRUE, sep = "\n")
return(list2)
}
# Run Matrices as leaf
leaf = TRUE
list2 = list("listax" = listax,"ggdf" = list2$ggdf, "dfsum" = list2$dfsum,"list" = list2$list, "listn" = list2$listn, "udata" = udata,"permat"= list2$permat, "persim" = list2$persim, "br" = br, "cl" = cl, "met" = met, "ep"= ep, "clep" = clep,"nn" = nn, "sumper" = list2$sumper, "sumper2" = list2$sumper2, "ela" = ela, "cel" = cel,"endper" = list2$endper, "last" = list2$last, "progend" = progend, "leaf" = leaf,"leaf2" = leaf2)
list2 = Matrices(list2)
# Condition wich ends the algorithm
if(is.na(((clep[br] < clep[br+1]) && (sum(clep == clep[br]) != (2^clep[br]))))){
clmax = cl
brtemp = br
progend = TRUE
list2 = list("listax" = list2$listax,"ggdf" = list2$ggdf, "dfsum" = list2$dfsum,"list" = list2$list, "listn" = list2$listn, "udata" = list2$udata,"permat"= list2$permat, "persim" = list2$persim, "br" = brtemp, "cl" = list2$cl, "met" = list2$met, "ep"= list2$ep, "clep" = list2$clep,"nn" = list2$nn, "sumper" = list2$sumper, "sumper2" = list2$sumper2, "ela" = list2$ela, "cel" = list2$cel,"endper" = list2$endper, "last" = list2$last,"progend" = progend, "leaf" = leaf,"leaf2" = leaf2)
if(brtemp < clmax){
# Find the statistics of the remaining clusters before you end
for (i in (br+1):clmax) {
brtemp = i
list2 = list("listax" = list2$listax,"ggdf" = list2$ggdf, "dfsum" = list2$dfsum,"list" = list2$list, "listn" = list2$listn, "udata" = list2$udata,"permat"= list2$permat, "persim" = list2$persim, "br" = brtemp, "cl" = list2$cl, "met" = list2$met, "ep"= list2$ep, "clep" = list2$clep,"nn" = list2$nn, "sumper" = list2$sumper, "sumper2" = list2$sumper2, "ela" = list2$ela, "cel" = list2$cel,"endper" = list2$endper, "last" = list2$last,"progend" = progend, "leaf" = leaf,"leaf2" = leaf2)
list2 = Matrices(list2)
}
}
en = toc(quiet = TRUE)
cat(paste0("Choice","\t",length(udata[udata$clusters == br,]$AA.JUNCTION),"\t",str_length(udata$AA.JUNCTION[1]),"\t",en$toc - en$tic,"\t",(pryr::mem_used() / 10^6)), file=logFile, append=TRUE, sep = "\n")
return(list2)
}
# If the next branch is in the next level
if( ((clep[br] < clep[br+1]) && (sum(clep == clep[br]) != (2^clep[br]))) == TRUE ){
met = 0
ep = ep + 1
br = br + 1
}else{
br = br + 1
met = met +2
}
list2 = list("listax" = list2$listax,"ggdf" = list2$ggdf, "dfsum" = list2$dfsum,"list" = list2$list, "listn" = list2$listn, "udata" = list2$udata,"permat"= list2$permat, "persim" = list2$persim, "br" = br, "cl" = cl, "met" = met, "ep"= ep, "clep" = clep,"nn" = list2$nn, "sumper" = list2$sumper, "sumper2" = list2$sumper2, "ela" = list2$ela, "cel" = list2$cel,"endper" = list2$endper, "last" = list2$last, "progend" = progend, "leaf" = leaf,"leaf2" = leaf2)
}
# When the counter reaches the end value (geometric sequence) we increase the level counter
if( met == geomSeq(1,2,1,1000)[ep+1]){
met = 0
ep = ep + 1
}
# The return list
leaf = FALSE
result2 = list("listax" = list2$listax,"ggdf" = list2$ggdf, "dfsum" = list2$dfsum,"list" = list2$list, "listn" = list2$listn, "udata" = udata,"permat"= list2$permat, "persim" = list2$persim, "br" = br, "cl" = cl, "met" = met, "ep"= ep, "clep" = clep,"nn" = nn, "sumper" = list2$sumper, "sumper2" = list2$sumper2, "ela" = ela, "cel" = cel,"endper" = list2$endper, "last" = list2$last, "progend" = progend, "leaf" = leaf,"leaf2" = leaf2)
en = toc(quiet = TRUE)
cat(paste0("Choice","\t",length(udata[udata$clusters == br,]$AA.JUNCTION),"\t",str_length(udata$AA.JUNCTION[1]),"\t",en$toc - en$tic,"\t",(pryr::mem_used() / 10^6)), file=logFile, append=TRUE, sep = "\n")
return(result2)
}
######################################## Geometric Sequence ########################################
# A function that generates a geometric sequence
geomSeq <- function(start,ratio,begin,end){
begin=begin-1
end=end-1
start*ratio**(begin:end)
}
######################################## LogFile ########################################
# Initialization of logfile
logFile = paste0(getwd(),"/log_file ",trunc(as.numeric(Sys.time())),".txt")
cat(paste0("Function","\t","Num of input rows","\t","Num of input columns","\t","Duration","\t","Memory used"), file=logFile, append=FALSE, sep = "\n")
######################################## The Main Run of Algorithm ########################################
tic()
while (progend == FALSE){
lista = Matrices(listb)
progend = lista$progend
if(progend == TRUE){
break
}
listb = Choice(lista)
progend = listb$progend
}
en = toc(quiet = TRUE)
cat(paste0("lastlist","\t",length(udata[udata$clusters == br,]$AA.JUNCTION),"\t",str_length(udata$AA.JUNCTION[1]),"\t",en$toc - en$tic,"\t",(pryr::mem_used() / 10^6)), file=logFile, append=TRUE, sep = "\n")
lastlist = listb
######################################## Creating Matrices from return list results ########################################
# The final name of udata data frame
df = lastlist$udata
# A list with the permat matrix for every branch
perlist = lastlist$list
persimlist = lastlist$listn
# Create a dataframe with all clusters and their identity and similarity percentage
ff = lastlist$dfsum
ff$level[1]= 0
ff$level[2:(length(lastlist$clep[ff$branch]) +1 )] = lastlist$clep[ff$branch] #without leaves
Clus = as.data.frame(matrix(100, ncol = 3, nrow = max(df$clusters)+1))
names(Clus) = c("ClusterId","Identity","Similarity")
Clus$ClusterId = 0:max(df$clusters)
Clus$seqnum[1] = nrow(df)
Clus$seqnum[2:(max(df$clusters)+1)] = lastlist$ggdf$len
Clus$level = c(0,lastlist$clep)
for(i in 1:length(ff$branch) ){
ll = which(Clus$ClusterId == ff$branch[i])
Clus$Identity[ll] = ff$sumper[i]
Clus$Similarity[ll] = ff$sumper2[i]
}
######################################## Compute the max tree ########################################
lev = max(na.omit(lastlist$clep))
df = df[ do.call( order , df[ , match( colnames(df[str_which(names(df), "level.")]) , names(df) ) ] ) , ]
df_args <- c(df[str_which(names(df), "level.")], sep="/")
if(lev == max(na.omit(lastlist$clep))){
df$pathString<- do.call(paste, df_args)
kk = df$pathString
for(i in 1:length(kk)){
temp = str_locate(kk[i],"/NA")
if(is.na(temp[1]) == FALSE){
temp2 = str_sub(kk[i], 1, temp[1]-1);
kk[i] = temp2
}
}
}else{
df$pathString<- do.call(paste, df_args)
kk = df$pathString
gg =as.data.frame(str_locate_all(kk,"/"))
tem = 1
for (i in 1:length(kk)){
kk[i] = str_sub(kk[i],1,gg[,tem][lev+1]-1)
tem = tem + 2
}
for(i in 1:length(kk)){
temp = str_locate(kk[i],"/NA")
if(is.na(temp[1]) == FALSE){
temp2 = str_sub(kk[i], 1, temp[1]-1);
kk[i] = temp2
}
}
}
df$pathString = kk
x <- ToDataFrameTree(df, "pathstring")
xN <- as.Node(x)
######################################## Enabling Threshold ########################################
# If enable threshold cut the tree
if(enthr == TRUE){
matches <- regmatches(unique(x$pathString), gregexpr("[[:digit:]]+", unique(x$pathString)))
arxpath = unique(x$pathString)
for(i in 1:length(matches)){
ggg = as.numeric(unlist(matches[i])) +1
if(levcut <= (length(ggg)-1)){
for(j in levcut:(length(ggg)-1)){
if(algo == "Identity"){
ddd1 = ((Clus$seqnum[ggg[j]] - Clus$seqnum[ggg[j+1]]) / Clus$seqnum[ggg[j]]) * 100
ddd2 = (Clus$Identity[ggg[j+1]] - Clus$Identity[ggg[j]]) * 0.5 + (Clus$Similarity[ggg[j+1]] - Clus$Similarity[ggg[j]]) * 0.5
if(ddd1 < threshold1 || ddd2 < threshold2){
deik = which(x$pathString == arxpath[i])
tem = str_locate(arxpath[i],as.character(ggg[j]-1))
fftemp = str_sub(x$pathString[deik[1]],1,tem[2])
ff2 = str_sub(x$pathString[deik[1]],tem[1],tem[2])
ff3 = as.numeric(ff2)
x$clusters[deik] = ff3
ff4 = lastlist$clep[ff3]
ff5 = str_which(names(x),sprintf("level.%d",ff4))
ff6 = str_which(names(x), "level.")
if(is.na(ff5[1]) == FALSE){
x[deik,(ff5[1]+1):max(ff6)] = NA
}
x$pathString[deik] = fftemp
break()
}
}else if(algo == "Similarity"){
ddd1 = ((Clus$seqnum[ggg[j]] - Clus$seqnum[ggg[j+1]]) / Clus$seqnum[ggg[j]]) * 100
ddd2 = Clus$Similarity[ggg[j+1]] - Clus$Similarity[ggg[j]]
print(paste0("ddd1=",ddd1," ddd2=",ddd2))
print(paste0("i=",i," j=",j) )
if(ddd1 < threshold1 || ddd2 < threshold2){
deik = which(x$pathString == arxpath[i])
tem = str_locate(arxpath[i],as.character(ggg[j]-1))
fftemp = str_sub(x$pathString[deik[1]],1,tem[2])
ff2 = str_sub(x$pathString[deik[1]],tem[1],tem[2])
ff3 = as.numeric(ff2)
x$clusters[deik] = ff3
ff4 = lastlist$clep[ff3]
ff5 = str_which(names(x),sprintf("level.%d",ff4))
ff6 = str_which(names(x), "level.")
if(is.na(ff5[1]) == FALSE){
x[deik,(ff5[1]+1):max(ff6)] = NA
}
x$pathString[deik] = fftemp
break()
}
}
}
}
}
xN <- as.Node(x)
bo = which(lastlist$clep == lev)
levtel = lastlist$clep
j = 1
jfjf = vector()
for(i in 1:max(bo)){
temp1 = as.numeric(names(FindNode(xN,(sprintf("%d",i)))$children))
if(length(temp1) == 1){
if(temp1[1] %% 2 == 1){
ff7 = temp1[1] + 1
}else{
ff7 = temp1[1] - 1
}
ff8 = lastlist$clep[ff7]
ff9 = str_which(names(x),sprintf("level.%d",ff8))
deik2 = which(df[ff9] == ff7)
x[deik2,ff9] = df[deik2,ff9]
tem = str_locate(df$pathString[deik2[1]],as.character(ff7))
fftemp = str_sub(df$pathString[deik2[1]],1,tem[2])
x$pathString[deik2] = fftemp
jfjf[j] = ff7
j = j+1
}
if(is.null(FindNode(xN,(sprintf("%d",i)))$isLeaf) && is.element(i, jfjf) == FALSE){
levtel[i] = NA
Clus[i+1,] = NA
ff[i+1,] = NA
}
}
xN <- as.Node(x)
}
######################################## Visualization 1 - Static Tree ########################################
# Creating a Static Tree visualization
Den <- function(lev){
if(flagtic == TRUE) tic(sprintf("Den -- Level: %d ", lev))
df = df[ do.call( order , df[ , match( colnames(df[str_which(names(df), "level.")]) , names(df) ) ] ) , ]
df_args <- c(df[str_which(names(df), "level.")], sep="/")
if(lev == max(na.omit(lastlist$clep))){
df$pathString<- do.call(paste, df_args)
kk = df$pathString
for(i in 1:length(kk)){
temp = str_locate(kk[i],"/NA")
if(is.na(temp[1]) == FALSE){
temp2 = str_sub(kk[i], 1, temp[1]-1);
kk[i] = temp2
}
}
}else{
df$pathString<- do.call(paste, df_args)
kk = df$pathString
gg =as.data.frame(str_locate_all(kk,"/"))
tem = 1
for (i in 1:length(kk)){
kk[i] = str_sub(kk[i],1,gg[,tem][lev+1]-1)
tem = tem + 2
}
for(i in 1:length(kk)){
temp = str_locate(kk[i],"/NA")
if(is.na(temp[1]) == FALSE){
temp2 = str_sub(kk[i], 1, temp[1]-1);
kk[i] = temp2
}
}
}
df$pathString = kk
x <- ToDataFrameTree(df, "pathstring")
if(enthr == TRUE){
matches <- regmatches(unique(x$pathString), gregexpr("[[:digit:]]+", unique(x$pathString)))
arxpath = unique(x$pathString)
for(i in 1:length(matches)){
# i = 2
ggg = as.numeric(unlist(matches[i])) +1
if(levcut <= (length(ggg)-1)){
for(j in levcut:(length(ggg)-1)){
if(algo == "Identity"){
ddd1 = ((Clus$seqnum[ggg[j]] - Clus$seqnum[ggg[j+1]]) / Clus$seqnum[ggg[j]]) * 100
ddd2 = (Clus$Identity[ggg[j+1]] - Clus$Identity[ggg[j]]) * 0.5 + (Clus$Similarity[ggg[j+1]] - Clus$Similarity[ggg[j]]) * 0.5
if(ddd1 < threshold1 || ddd2 < threshold2){
deik = which(x$pathString == arxpath[i])
tem = str_locate(arxpath[i],as.character(ggg[j]-1))
fftemp = str_sub(x$pathString[deik[1]],1,tem[2])
ff2 = str_sub(x$pathString[deik[1]],tem[1],tem[2])
ff3 = as.numeric(ff2)
x$clusters[deik] = ff3
ff4 = lastlist$clep[ff3]
ff5 = str_which(names(x),sprintf("level.%d",ff4))
ff6 = str_which(names(x), "level.")
if(is.na(ff5[1]) == FALSE){
x[deik,(ff5[1]+1):max(ff6)] = NA
}
x$pathString[deik] = fftemp
break()
}
}else if(algo == "Similarity"){
ddd1 = ((Clus$seqnum[ggg[j]] - Clus$seqnum[ggg[j+1]]) / Clus$seqnum[ggg[j]]) * 100
ddd2 = Clus$Similarity[ggg[j+1]] - Clus$Similarity[ggg[j]]
if(ddd1 < threshold1 || ddd2 < threshold2){
deik = which(x$pathString == arxpath[i])
tem = str_locate(arxpath[i],as.character(ggg[j]-1))
fftemp = str_sub(x$pathString[deik[1]],1,tem[2])
ff2 = str_sub(x$pathString[deik[1]],tem[1],tem[2])
ff3 = as.numeric(ff2)
x$clusters[deik] = ff3
ff4 = lastlist$clep[ff3]
ff5 = str_which(names(x),sprintf("level.%d",ff4))
ff6 = str_which(names(x), "level.")
if(is.na(ff5[1]) == FALSE){
x[deik,(ff5[1]+1):max(ff6)] = NA
}
x$pathString[deik] = fftemp
break()
}
}
}
}
}
xN <- as.Node(x)
bo = which(lastlist$clep == lev)
levtel = lastlist$clep
j = 1
jfjf = vector()
for(i in 1:max(bo)){
temp1 = as.numeric(names(FindNode(xN,(sprintf("%d",i)))$children))
if(length(temp1) == 1){
if(temp1[1] %% 2 == 1){
ff7 = temp1[1] + 1
}else{
ff7 = temp1[1] - 1
}
ff8 = lastlist$clep[ff7]
ff9 = str_which(names(x),sprintf("level.%d",ff8))
deik2 = which(df[ff9] == ff7)
x[deik2,ff9] = df[deik2,ff9]
tem = str_locate(df$pathString[deik2[1]],as.character(ff7))
fftemp = str_sub(df$pathString[deik2[1]],1,tem[2])
x$pathString[deik2] = fftemp
jfjf[j] = ff7
j = j+1
}
if(is.null(FindNode(xN,(sprintf("%d",i)))$isLeaf) && is.element(i, jfjf) == FALSE){
levtel[i] = NA
Clus[i+1,] = NA
ff[i+1,] = NA
}
}
}
xN <- as.Node(x)
if(flagtic == TRUE) toc(log = TRUE,quiet = TRUE)
plot(xN)
}
# Example - Den(5)
######################################## Visualization 2a - SatLev ########################################
# Copmute the sequnces, Identity, Similarity of level and leaf (until this level) clusters and make barplots
SatLev <- function(lev){
if(flagtic == TRUE) tic()
if( is.element(lev,lastlist$clep) == FALSE){
NULL
}else{
xN <- as.Node(df)
# Level clusters
t1 = which(lastlist$clep == lev)
# leaves until level
xm = as.numeric(as.data.frame(xN$leaves))
orio = min(which(lastlist$clep == lev))
xm2 = sort(xm[xm < orio])
t1 = sort(append(xm2,t1,after = length(xm2)))
# Visualization with barplot
par(mfrow=c(1,3))
a = table(Clus[t1+1,]$seqnum)
barplot(a, width=2, main = sprintf('Sequences for level.%d' ,lev))
b = table(round(Clus[t1+1,]$Identity,2))
barplot(b, width=2, main = sprintf('Identity of sequences for level.%d' ,lev))
c = table(round(Clus[t1+1,]$Similarity,2))
barplot(c, width=2, main = sprintf('Similarity of sequences for level.%d' ,lev))
}
if(flagtic == TRUE){
en = toc(quiet = TRUE)
cat(paste0(sprintf("LogoLev -- Level: %d ", lev),"\t","-","\t","-","\t",en$toc - en$tic), file=logFile, append=TRUE, sep = "\n")
}
}
# Example - SatLev(5)
######################################## Visualization 2b - LogoLev ########################################
# Create custom colour scheme
cs1 = make_col_scheme(chars=c("F","W","A","I","L","V","M","C","P","G","Y","T","S","H","K","R","E","D","Q","N"),
cols=c("#1E90FF", "#BA55D3", "#0000FF", "#0000FF", "#0000FF", "#0000FF", "#C6E2FF", "#C6E2FF", "#FFD700", "#00EE00", "#C1FFC1", "#54FF9F", "#54FF9F", "#FF0000", "#FF0000", "#FF0000", "#FFD700", "#FFD700", "#ED9121", "#ED9121"))
# A function to plot logos of level and leaf (until this level) clusters
LogoLev <- function(lev,seqthr,idethr,simthr,simen,seqen,ideen){
if(flagtic == TRUE) tic(sprintf("LogoLev -- Level: %d ", lev))
if( is.element(lev,lastlist$clep) == FALSE){
print("Den yparxei")
}else{
# Level clusters
t1 = which(lastlist$clep == lev)
# leaves until level
xm = as.numeric(as.data.frame(xN$leaves))
orio = min(which(lastlist$clep == lev))
xm2 = sort(xm[xm < orio])
t1 = sort(append(xm2,t1,after = length(xm2)))
# Actions with Sequence Threshold Enabled
if(seqen == TRUE){
if(length(which(Clus[t1+1,]$seqnum < seqthr)) != 0){
t1 = t1[-which(Clus[t1+1,]$seqnum < seqthr)]
}
}
# Actions with Identity Threshold Enabled
if(ideen == TRUE){
if(length(which(Clus[t1+1,]$Identity < idethr)) != 0){
t1 = t1[-which(Clus[t1+1,]$Identity < idethr)]
}
}
# Actions with Similarity Threshold Enabled
if (simen == TRUE){
if(length(which(Clus[t1+1,]$Similarity < simthr)) != 0){
t1 = t1[-which(Clus[t1+1,]$Similarity < simthr)]
}
}
listff = list()
nc = 3 #3 logos in every row
if(length(t1) > 0){
for(i in 1:length(t1)){
# leaves
if(t1[i]<= max(xm2)){
listff$temp = na.omit(df[df[names(df) == sprintf('level.%d', lastlist$clep[t1[i]])] == t1[i],]$AA.JUNCTION)
names(listff)[length(listff)] = sprintf('Cluster.%d - seqnum:%d - Id:%g - Sim:%g - leaf', t1[i],Clus$seqnum[t1[i]+1],Clus$Identity[t1[i]+1],Clus$Similarity[t1[i]+1])
}else{
# level clusters
x1 = as.data.frame(na.omit(df[df[which(names(df) == sprintf("level.%d", lev))] == t1[i], ]$AA.JUNCTION))
if (nrow(x1) >0){
names(x1)[1]= "AA.JUNCTION"
x1 = as.character(x1$AA.JUNCTION)
listff$temp = x1
names(listff)[length(listff)] = sprintf('Cluster.%d - seqnum:%d - Id:%g - Sim:%g', t1[i],Clus$seqnum[t1[i]+1],Clus$Identity[t1[i]+1],Clus$Similarity[t1[i]+1])
}
}
}
if(flagtic == TRUE){
en = toc(quiet = TRUE)
cat(paste0(sprintf("LogoLev -- Level: %d ", lev),"\t","-","\t","-","\t",en$toc - en$tic), file=logFile, append=TRUE, sep = "\n")
}
# Plot logos
ggseqlogo(listff, ncol=nc, method = "prob",col_scheme=cs1)
}else{
if(flagtic == TRUE){
en = toc(quiet = TRUE)
cat(paste0(sprintf("LogoLev -- Level: %d ", lev),"\t","-","\t","-","\t",en$toc - en$tic), file=logFile, append=TRUE, sep = "\n")
}
NULL
}
}
}
# Example - LogoLev(5,5,10,20,TRUE,FALSE,TRUE)
######################################## Visualization 2c - LogoCl ########################################
# A function to plot the logo of a cluster
LogoCl <- function(cl){
if(flagtic == TRUE) tic(sprintf("LogoCl -- Cluster: %d ", cl))
if(flagtic == TRUE) toc(log = TRUE,quiet = TRUE)
if(is.na(lastlist$clep[cl])){
print("Den yparxei")
}else{
xN <- as.Node(df)
listff = list()
listff$temp = na.omit(df[df[names(df) == sprintf('level.%d', lastlist$clep[cl])] == cl,]$AA.JUNCTION)
xm = as.numeric(as.data.frame(xN$leaves))
if(is.element(cl,xm)){
names(listff)= sprintf('Cluster: %s num:%d - leaf', cl ,Clus$seqnum[cl+1])
}else{
names(listff)= sprintf('Cluster: %s num:%d', cl ,Clus$seqnum[cl+1])
}
# Plot logo
ggseqlogo(listff, method = "prob", col_scheme=cs1)
}
}
# Example - LogoCl(5)
######################################## Visualization 3a - BarLev ########################################
# A function to plot barplots of level and leaf (until this level) clusters
BarLev <- function(lev){
if(flagtic == TRUE) tic(sprintf("BarLev -- Level: %d ", lev))
if(cho == "Identity"){
if( is.element(lev,lastlist$clep) == FALSE){
print("Den yparxei")
}else{
xN <- as.Node(df)
# Level clusters
t2 = which(lastlist$clep == lev)
# leaves until level
xm = as.numeric(as.data.frame(xN$leaves))
orio = min(which(lastlist$clep == lev))
xm2 = sort(xm[xm < orio])
t2 = sort(append(xm2,t2,after = length(xm2)))
# 3 barplots in every row
if(length(t2) %% 3 == 0){
par(mfrow = c(length(t2)%/%3,3))
}else{
par(mfrow = c(length(t2)%/%3 + 1,3))
}
for(i in 1:length(t2)){
ar = str_which(names(perlist),as.character(t2[i]))[1]
par(xpd=TRUE)
output <- matrix(unlist(perlist[ar]), ncol = str_length(lastlist$udata$AA.JUNCTION[1]), byrow = FALSE)
if(i<= length(xm2)){ # leaves
barplot(output[-nrow(output),], col=heat.colors(length(output[,1])-1), width=2, main = sprintf('Cluster.%d - seqnum:%d - leaf', t2[i],Clus$seqnum[t2[i]+1]))
}else{ # level clusters
barplot(output[-nrow(output),], col=heat.colors(length(output[,1])-1), width=2, main = sprintf('Cluster.%d - seqnum:%d', t2[i],Clus$seqnum[t2[i]+1]))
}
legend("topright",inset=c(-0.03,0), fill=heat.colors(length(output[,1])-1), legend=let,cex = 0.6)
}
}
}else{
if( is.element(lev,lastlist$clep) == FALSE){
print("Den yparxei")
}else{
xN = as.Node(df)
# Level clusters
t2 = which(lastlist$clep == lev)
# leaves until level
xm = as.numeric(as.data.frame(xN$leaves))
orio = min(which(lastlist$clep == lev))
xm2 = sort(xm[xm < orio])
t2 = sort(append(xm2,t2,after = length(xm2)))
# 3 barplots in every row
if(length(t2) %% 3 == 0){
par(mfrow = c(length(t2)%/%3,3))