-
Notifications
You must be signed in to change notification settings - Fork 9
/
server.R
1213 lines (810 loc) · 45.1 KB
/
server.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
################################################
#
# THE GENETIC MAP COMPARATOR
#
###############################################
shinyServer(function(input, output, session) {
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------
# --- ALLOWS USER TO DOWNLOAD EXAMPLE DATASET
#-----------------------------------------------------------------------------
# format OneMap
output$load_ex_format1 <- downloadHandler(
filename = "GenMapComp_Example1.csv",
content <- function(file) {
file.copy("DATA/EX_HELP_PAGE/Example_Data_Set1.csv", file)
}
)
#format Mapchart
output$load_ex_format2 <- downloadHandler(
filename = "GenMapComp_Example2.csv",
content <- function(file) {
file.copy("DATA/EX_HELP_PAGE/Example_Data_Set2.csv", file)
}
)
#format Carthagène
output$load_ex_format3 <- downloadHandler(
filename = "GenMapComp_Example3.csv",
content <- function(file) {
file.copy("DATA/EX_HELP_PAGE/Example_Data_Set3.csv", file)
}
)
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------
# --- UPLOAD MAPS AND FILE FORMATING
#-----------------------------------------------------------------------------
# 0/ --- Selection of the data set: default dataset / Example dataset / Chosen dataset
inFile=reactive({
# Cleaning
rm(list=ls())
my_global_old_choice <- c(3)
# If nothing is choosen I take the chosen exemple dataset
if ( is.null(input$file1)) {
# So no error message needed
output$error_message<- renderUI({ helpText("") })
if( input$file2=="sorghum (Mace et al. 2009)" | is.null(input$file2)){ inFile=data.frame(name=as.character(c("CIRAD","S2","S4","S5","S6","TAMU")) , datapath=as.character(c("DATA/SORGHUM/CIRAD", "DATA/SORGHUM/S2" , "DATA/SORGHUM/S4" , "DATA/SORGHUM/S5" , "DATA/SORGHUM/S6" , "DATA/SORGHUM/TAMU" )) ) }
else if( input$file2=="wheat (Maccaferri et al. 2015)"){ inFile=data.frame(name=as.character(c("Ben_Pi41025","Colosseo_Lloyd","Kofa_svevo","Langdon_G1816","Latino_MG5323","Mohawk_Cocorrit69","Simeto_Levante")) , datapath=as.character(c("DATA/WHEAT_MACAF/CLEAN/Ben_Pi41025", "DATA/WHEAT_MACAF/CLEAN/Colosseo_Lloyd" , "DATA/WHEAT_MACAF/CLEAN/Kofa_svevo", "DATA/WHEAT_MACAF/CLEAN/Langdon_G1816", "DATA/WHEAT_MACAF/CLEAN/Latino_MG5323", "DATA/WHEAT_MACAF/CLEAN/Mohawk_Cocorrit69", "DATA/WHEAT_MACAF/CLEAN/Simeto_Levante" )) ) }
else if( input$file2=="wheat (Holtz et al. 2016)"){ inFile=data.frame(name=as.character(c("map_DS","map_DL","map_consensus","physical_position")) , datapath=as.character(c("DATA/WHEAT_TRAM/map_DS","DATA/WHEAT_TRAM/map_DL","DATA/WHEAT_TRAM/map_consensus","DATA/WHEAT_TRAM/physical_position" )) ) }
# If the user proposes a dataset:
}else{
# I have to check if the proposed fileS ARE readable and in the good format!
mistake_presence=FALSE
output$error_message<- renderUI({ helpText("") })
# I need at least 2 files
if( length(input$file1$datapath)<2 ){
mistake_presence=TRUE
output$error_message<- renderUI({ helpText("Please select at least 2 maps" , style="color:red ; font-family: 'times'; font-size:13pt") })
# If I have at least 2 maps, I check them one by one:
}else{
for(i in c(input$file1$datapath)) {
# I try to read the file
a=try(read.table(i, header=T , dec="." ,na.strings="NA"))
# if the file is NOT readable by R
if(class(a)=="try-error"){
mistake_presence=TRUE
output$error_message<- renderUI({ helpText("File input is not readable by R. Is it a genetic map?" , style="color:red ; font-family: 'times'; font-size:13pt") })
break
# if the file does not have 2 or 3 columns
}else{
if( !ncol(a)%in%c(1,2,3) & nrow(a)!=0 ){
mistake_presence=TRUE
output$error_message<- renderUI({ helpText("One of your file does not have 2 nor 3 columns" , style="color:red ; font-family: 'times'; font-size:13pt") })
break
}}}
}
# So if there is a mistake in the proposed files, I keep sorghum as an example. Else I take the proposed files
if( mistake_presence==TRUE){
inFile=data.frame(name=as.character(c("CIRAD","S2","S4","S5","S6","TAMU")) , datapath=as.character(c("DATA/SORGHUM/CIRAD", "DATA/SORGHUM/S2" , "DATA/SORGHUM/S4" , "DATA/SORGHUM/S5" , "DATA/SORGHUM/S6" , "DATA/SORGHUM/TAMU" )) )
}else{
inFile <- input$file1
}
}
})
# Check if it worked properly
#observe({ print("Mon inFile") ; print ( inFile() ) ; print("--") })
# 1/ --- Catch the map names we have to compare :
MY_map_files=reactive({
# List of map files:
map_files=as.list(inFile()$name)
# return this list, but do not forget to format it:
return(as.character(unlist(map_files)))
})
# Check if it worked properly
#observe({ print("mes maps selectionnées") ; print ( MY_map_files()) ; print("test widget selection") ; selected=c(MY_map_files()[1],MY_map_files()[2]) ; print(selected) })
# 2/ --- Load every maps and add their content in a list.
MY_maps=reactive({
# I am reactive to the selection of input files !
inFile=inFile()
# Read and format maps one by one, and add them to a list:
my_maps=list()
for(i in inFile$datapath){
# Load the map
map_tmp=read.table(i , header=T , dec="." ,na.strings="NA")
# If I have only 1 column, the separator was wrong, I try with ";":
if(ncol(map_tmp)==1){
map_tmp=read.table(i , header=T , dec="." ,na.strings="NA" , sep=";")
}
# If I have 2 columns, It is the MAPCHART format --> I need to reformat it!
if(ncol(map_tmp)==2){
junctions=c(1, as.numeric(row.names(map_tmp[map_tmp[,1]=="group" , ])), nrow(map_tmp)+1 )
nb_rep=junctions[-1] - junctions[-length(junctions)]
LG_names=c(colnames(map_tmp)[2] , as.character(map_tmp[map_tmp[,1]=="group" , 2]) )
map_tmp$new=rep(LG_names , times=nb_rep)
map_tmp=map_tmp[map_tmp[,1]!="group" , ]
map_tmp=map_tmp[ , c(3,1,2)]
}
# If I have only 0 line, it is the CARTHAGENE Format --> I need to reformat it!
if(nrow(map_tmp)==0){
tmp_data=read.table(i , header=F , sep=" ")
tmp_data=apply(tmp_data, 2 , as.character)
tmp_data=gsub("\\}" , "" , tmp_data )
tmp_data=tmp_data[-c(1,2)]
map_tmp=data.frame(matrix(0, length(tmp_data), 3))
num=0
for(k in tmp_data){
# If the LG changes, I change my "LG" variable, and num1 back to -2
if( substr(k,1,1) == "{" ){
LG=gsub("\\{","",k)
num1=-2
}
# For each step of the loop, num1 increases
num1=num1+1
# When I am not reading a LG name (num1=-2) or a likelihood (num1=0), I add stuff in my map_tmp table
# The line number (num) increase only once every 2 iterations
if( num1>0){
num=num+num1%%2
map_tmp[num,1]=LG
map_tmp[num,num1%%2+2]=k
}}
# Clean this map_tmp
map_tmp=map_tmp[ c(1:num) , c(1,3,2)]
}
# Columns must be in the good format:
map_tmp[,1]=as.factor(map_tmp[,1])
map_tmp[,2]=as.factor(map_tmp[,2])
map_tmp[,3]=as.numeric(as.character(map_tmp[,3]))
# With the good names:
colnames(map_tmp)=c("group","marker","position")
# I keep only the first 3 columns (if they are more..)
map_tmp=map_tmp[,c(1:3)]
# I remove positions where an information is missing:
map_tmp=na.omit(map_tmp)
# And ordered
map_tmp=map_tmp[order(map_tmp$group , map_tmp$position ) , ]
# I remove markers if the user choosed to remove markers in the raw data sheet!
if(input$keep_or_remove=="remove"){
list_mark_remove=unlist(strsplit(input$text_mark_remove, ","))
list_mark_remove=paste("^",list_mark_remove,"$",sep="")
for(i in list_mark_remove){
map_tmp=map_tmp[!grepl(i,map_tmp$marker) , ]
}
}
# I keep only some markers if the user choosed to keep markers in the raw data sheet!
if(input$keep_or_remove=="keep"){
list_mark_keep=unlist(strsplit(input$text_mark_remove, ","))
list_mark_keep=paste("^",list_mark_keep,"$",sep="")
for(i in list_mark_keep){
map_tmp=map_tmp[grepl(i,map_tmp$marker) , ]
}
}
# Add it to the list
my_maps[[length(my_maps)+1]]=map_tmp
}
return(my_maps)
})
# Check everything worked properly
#observe({ print("summary de la carte 1:") ; print ( head(MY_maps()[[1]]) ) })
# 3/ --- Merge the maps together
MY_data=reactive({
# Get back the reactive objects needed:
my_maps=MY_maps()
nb_de_carte=length(my_maps)
map_files=MY_map_files()
# Merge the n maps together:
data=merge(my_maps[[1]] , my_maps[[2]], by.x=2 , by.y=2 , all=T)
colnames(data)=c("marker",paste("chromo",map_files[1],sep="_") , paste("pos",map_files[1],sep="_") , paste("chromo",map_files[2],sep="_") , paste("pos",map_files[2],sep="_"))
if(nb_de_carte>2){
for(i in c(3:nb_de_carte)){
data=merge(data , my_maps[[i]] , by.x=1 , by.y=2 , all=T)
colnames(data)[c( ncol(data)-1 , ncol(data) )]= c( paste("chromo",map_files[i],sep="_") , paste("pos",map_files[i],sep="_") )
}}
# I have now a file summarizing the information for every markers present at least one time ! Return it!
return(data)
})
# Check everything worked properly
#observe({ print("summary du fichier mergé data:") ; print ( head( MY_data() ) ) })
# 4/ --- List of chromosomes ?
MY_chromosome_list=reactive({
# Get back the reactive objects needed:
data=MY_data()
# --- Get a list with the existing chromosomes:
chromosome_list=unlist(data[ , seq(2,ncol(data),2) ])
chromosome_list=as.character(unique(sort( chromosome_list[!is.na(chromosome_list)] )))
# Return the chromosome liste
return(chromosome_list)
})
# Did it work ?
#observe({ print("Liste des chromosomes:") ; print ( head( MY_chromosome_list() ) ) })
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------
# --- COMPUTE SUMMARY STATISTICS FOR EVERY MAPS
#-----------------------------------------------------------------------------
MY_summary_stat=reactive({
# Get the needed reactive objects:
my_maps=MY_maps()
nb_de_carte=length(my_maps)
# Function 1 : give it a piece of map, it calculates some statistics and add it to a bilan data frame.
my_fun=function(my_map, bilan, i){
num=nrow(bilan)
num=num+1
bilan[num,1]=i
bilan[num,2]=nrow(my_map)
bilan[num,3]=max(my_map[,3])
# Calcul des gaps: je vais prendre les gaps entre position unique, pas les gaps entre chaque marqueurs !
gaps = sort(my_map[,3])[-1] - sort(my_map[,3])[-length(my_map[,3])]
gaps=gaps[gaps!=0]
bilan[num,4]=round(mean(gaps),2)
bilan[num,5]=max(gaps)
bilan[num,6]=nrow(unique(my_map[,c(1,3)]))
return(bilan)
}
# Compute summary statistics for every maps applying this function !
summary_stat=list()
for(j in 1:nb_de_carte){
# Make an emty matrix
map=my_maps[[j]]
bilan=data.frame(matrix(0,0,6)) ; num=0
colnames(bilan)=c("Chr.","#markers","map_size","average gap_size","biggest gap_size","#unique positions")
# Apply the my_fun function to each chromosome one by one
for(i in levels(map[,1])){
map_K=map[map[,1]==i,]
bilan=my_fun(map_K , bilan , i)
}
# And then to the whole map
i="tot"
bilan=my_fun(map , bilan , "all")
#Correct map size
bilan[nrow(bilan) , 3] = sum(bilan[ -nrow(bilan) ,3])
#Correctaverage gap size
bilan[nrow(bilan) , 4] = round(mean(bilan[ -nrow(bilan) ,4], na.rm=T),2)
#Correct biggest gap
bilan[nrow(bilan) , 5] = max(bilan[ -nrow(bilan) ,5], na.rm=T)
#Add the result to the list containing all the map summaries
summary_stat[[length(summary_stat)+1]]=bilan
}
# If I want the summary of the first map : summary_stat[[1]]
return(summary_stat)
})
# Check if everything is all right
#observe({ print("fichier de summary statistique:") ; for(u in MY_summary_stat()) {print ( u )} })
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#
# --------------------------------------------------------------------------------
# CREATION OF THE DYNAMICS BUTTONS FOR THE UI SCRIPT
#--------------------------------------------------------------------------------
# ======== sheet2: Summary Statistics =========
# MAP to study
output$choose_maps_sheet2<- renderUI({ checkboxGroupInput("selected_maps_sheet2", legend2[9], choices=MY_map_files(), selected=c(MY_map_files()[1],MY_map_files()[2]) , inline=T) })
# Chromosomes to study for markers density
output$choose_chromo_sheet2<- renderUI({checkboxGroupInput( "chromo_sheet2", legend2[10], choices=MY_chromosome_list() , selected =c(MY_chromosome_list()[1],MY_chromosome_list()[2]) , inline = TRUE ) })
# Map to study for summary table
output$choose_maps_sheet2_bis<- renderUI({ radioButtons("selected_maps_sheet2_bis", legend2[11], choices=MY_map_files(), selected=c(MY_map_files()[1]) , inline=T) })
# ======== sheet3: Compare Positions =========
# Map to study
output$choose_maps3<- renderUI({ checkboxGroupInput("selected_maps", legend3[4], choices=MY_map_files(), selected=c(MY_map_files()[1],MY_map_files()[2]) , inline=T) })
# Chromosomes to study
output$choose_chromo_sheet3<- renderUI({ radioButtons( "chromo", legend3[5], choices=MY_chromosome_list() , selected =MY_chromosome_list()[1] , inline=T ) })
# ======== sheet4: Interchromosomal Analyse =========
# First map to study :
output$map1<- renderUI({ radioButtons("map1", legend4[4], choices=MY_map_files(), selected=MY_map_files()[1] ) })
# Second map to study :
output$map2<- renderUI({ radioButtons("map2", legend4[5], choices=MY_map_files(), selected=MY_map_files()[2] ) })
# Chromosomes to study
output$choose_chromo_sheet4<- renderUI({ selectInput( "chromo_sheet4", legend4[6], choices=c("all", MY_chromosome_list()) , selected =c("all") ) })
# ======== sheet5: Rough Map vizualisation =========
# MAP to study
output$choose_maps5<- renderUI({ radioButtons("selected_maps_sheet5", legend5[3], choices=MY_map_files(), selected=MY_map_files()[1] ) })
# Chromosomes to study
output$choose_chromo_sheet5<- renderUI({ checkboxGroupInput( "chromo_sheet5", legend5[4], choices=c("all", MY_chromosome_list()) , selected =c(MY_chromosome_list()[1],MY_chromosome_list()[2]) , inline = TRUE ) })
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------
# --- SHEET 2 : SUMMARY STATISTICS PAGE - BARPLOT !
#-----------------------------------------------------------------------------
output$my_barplot=renderPlot({
# Get the needed reactive objects:
summary_stat=MY_summary_stat()
my_map_files=unlist(MY_map_files())
# Selected variable ?
selected_var=which(c("# markers","map size","average gap size","biggest gap size","# unique positions")%in%input$var_for_barplot)
# Selected Maps ?
selected_maps=which(my_map_files%in%input$selected_maps_sheet2)
nb_selected_maps=length(selected_maps)
# Create a table which gives this selected_variable for every selected maps and every chromosomes.
barplot_table=summary_stat[[selected_maps[1]]] [,c(1,selected_var+1)]
for(i in selected_maps[-1]){
barplot_table=merge(barplot_table , summary_stat[[i]] [,c(1,selected_var+1)] , by.x=1 , by.y=1 , all=T)
}
rownames(barplot_table)=barplot_table[,1]
barplot_table=barplot_table[-nrow(barplot_table) , ]
barplot_table=t(as.matrix(barplot_table[,-1]))
# Make the barplot !
par(mar=c(3,3,3,8))
barplot(barplot_table , beside=T , col=my_colors[1:length(selected_maps)])
#mtext(legend[23] , col="#3C3C3C" , line=-3 , at=ncol(barplot_table)*nb_selected_maps+8)
#Close the render-barplot
})
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------
# --- SHEET 2 : SUMMARY STATISTICS PAGE - DONUT-PLOT !
#-----------------------------------------------------------------------------
output$my_pieplot=renderPlot({
# Get the needed reactive objects:
summary_stat=MY_summary_stat()
map_files=MY_map_files()
# Avoid bug when loading
if (is.null(input$var_for_barplot) | is.null(input$selected_maps_sheet2) ) {return(NULL)}
# Selected variable ?
all_var=c("# markers","map size","average gap size","biggest gap size","# unique positions")
selected_var=which(all_var%in%input$var_for_barplot)
# Selected Maps ?
selected_maps=which(map_files%in%input$selected_maps_sheet2)
nb_selected_maps=length(selected_maps)
# Create a table which gives this selected_variable for every selected maps and every chromosomes.
barplot_table=summary_stat[[selected_maps[1]]] [,c(1,selected_var+1)]
for(i in selected_maps[-1]){
barplot_table=merge(barplot_table , summary_stat[[i]] [,c(1,selected_var+1)] , by.x=1 , by.y=1 , all=T)
}
rownames(barplot_table)=barplot_table[,1]
barplot_table=barplot_table[nrow(barplot_table) , ]
barplot_table=t(as.matrix(barplot_table[,-1]))
# Make the donut-plot !
par(mar=c(3,3,3,10))
my_labels=paste(map_files[selected_maps],"\n",all_var[selected_var]," : ",barplot_table,sep="")
doughnut(barplot_table, col=my_colors , border="white" , inner.radius=0.5, labels=my_labels )
#Close the render-barplot
})
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------
# --- SHEET 2 : SUMMARY STATISTICS PAGE - SUMMARY TABLE OF SELECTED MAP
#-----------------------------------------------------------------------------
observe({
# Selected Map ?
selected_map=which(MY_map_files()%in%input$selected_maps_sheet2_bis)
# bug if no map (loading)
if ( length(selected_map)==0 ) {return(NULL)}
# Avoid bug when loading
if (is.null(input$selected_maps_sheet2_bis) ) {return(NULL)}
# Get the desired summary stat
toprint=MY_summary_stat()[[selected_map]]
output$sum_table <- DT::renderDataTable(
DT::datatable( toprint , rownames = FALSE , options = list(pageLength = 40, dom = 't' ))
)
# Close observer
})
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------
# --- SHEET 2 : SUMMARY STATISTICS PAGE - PLOT FOR DENSITY !
#-----------------------------------------------------------------------------
# Make the circular plot. See https://cran.r-project.org/web/packages/circlize/vignettes/circlize.pdf to understand how circular plot works.
output$circular_plot <- renderPlot({
# Get the needed reactive objects:
summary_stat=MY_summary_stat()
map_files=MY_map_files()
my_maps=MY_maps()
nb_de_carte=length(map_files)
# Avoid bug when loading
if (is.null(input$var_for_barplot) | is.null(input$selected_maps_sheet2) ) {return(NULL)}
# Which maps have been selected ?
selected_maps=which(map_files%in%input$selected_maps_sheet2)
nb_selected_maps=length(selected_maps)
# Fichier nécessaire
data_circ=data.frame()
for(i in selected_maps){
current_map=my_maps[[i]]
current_map$map_name=map_files[i]
current_map$group_and_name=paste(map_files[i] , current_map[,1] , sep="_")
data_circ=rbind(data_circ , current_map)
}
# If the "all" option is not selected, then I keep only the chosen chromosomes
if(!("all"%in%input$chromo_sheet2)){
take=which(data_circ[,1]%in%input$chromo_sheet2)
data_circ=data_circ[take , ]
data_circ[,1]=droplevels(data_circ[,1])
}
# Réalisation du graph
par(mfrow=c(nb_de_carte ,1) , mar=c(0.3,4,0,0) )
for( map in levels(as.factor(data_circ$map_name))){
# Reset x positions
vecX=c()
vecY=c()
vecSep=c(0)
my_data=data_circ[which(data_circ$map_name==map) , ]
for( chromo in levels(as.factor(my_data$group)) ){
don=my_data[which(my_data$group==chromo) , ]
a=density(don$position)
a$x=a$x + abs(min(a$x))
if(length(vecX)>0){a$x=a$x+max(vecX) }
vecX=c(vecX , a$x)
vecY=c(vecY , a$y)
vecSep=c(vecSep, max(vecX))
}
# print the plot
plot(1,1,col="transparent" , xlim=c(0,max(vecX)) , ylim=c(0,max(vecY)) , xlab="" , xaxt="n" , ylab="" , yaxt="n" , bty="n" )
rect( vecSep[-length( vecSep)], rep(-2,length( vecSep)) , vecSep[-1] , rep(1 , length( vecSep)) , col=my_colors , border=F )
lines( vecX , vecY , col="black" , lwd=3 )
mtext( map , at=max(vecY)/2 , col="orange" , cex=2 , line=0, side=2 )
#fin du plot
}
#Ajout des labels de l'axe des x?
mtext( levels(as.factor(my_data$group)) , at=(vecSep[-1]+vecSep[-length(vecSep)]) /2 , col="orange" , cex=2 , line=5, side=1 )
})
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------
# --- SHEET 3 : MAP COMPARISON FOR A CHOSEN CHROMOSOME
#-----------------------------------------------------------------------------
# define session specific variable
# visible from all functions but session/user specific
my_global_old_choice<-c();
liste_of_map_to_compare<-c();
# liste_of_map_to_compare is an object with the genetic maps to compare, in the good order. I initialize it with the 2 first maps, like in the radiobutton.
MY_liste_of_map_to_compare=reactive({
map_files=MY_map_files()
liste_of_map_to_compare=c(map_files[1],map_files[2])
return(liste_of_map_to_compare)
})
output$plot1 <- renderPlotly({
# ========== PART 0 : INITIALISE OBJECTS
#Get the needed reactive objects:
summary_stat=MY_summary_stat()
map_files=MY_map_files()
my_maps=MY_maps()
nb_de_carte=length(map_files)
data=MY_data()
# We need to remember the old choice
old_choice <- my_global_old_choice;
# I get the current choice of maps to show (this is not ordered, we have to order it):
current_choice=input$selected_maps
# ========== PART 1 : DETERMIN WHICH MAP HAS BEEN ADDED / REMOVED + CREATE THE ORDERED SELECTED MAP LIST
# If the user has added a map, I determine which, and add it to the map to compare:
if(is.null(old_choice) | is.null(current_choice) ){
liste_of_map_to_compare=current_choice
}else{
intersection=which(old_choice%in%current_choice)
if( length(intersection)==0 ){
to_del=old_choice
}else{
to_del=old_choice[-intersection]
}
if(length(to_del)>0)
{liste_of_map_to_compare=old_choice[ - which(old_choice%in%to_del) ]}
intersection=which(current_choice%in%old_choice)
if( length(intersection)==0 ){
to_add= current_choice
}else{
to_add= current_choice[-intersection]
}
if(length(to_add)>0)
liste_of_map_to_compare=c(liste_of_map_to_compare,to_add)
}
# I save the current choice as old_choice for next change:
my_global_old_choice<<-liste_of_map_to_compare
liste_of_map_to_compare<<-liste_of_map_to_compare
# ========== PART 2 : IF NO SELECTED MAP, I RETURN A MESSAGE!
validate(
need(length(liste_of_map_to_compare)!=0, "Please select at least one map!")
)
# ========== PART 3 : CREATE A TABLE WITH MAPS FEATURES, IN THE GOOD ORDER. ex:for mapB and mapA i keep column: 1,4,5, 2,3:
# --- Make an input table with columns in the corresponding order:
selected_maps=match(liste_of_map_to_compare , map_files)
selected_col=rep(selected_maps , each=2)*2
selected_col=c(1,selected_col+rep(c(0,1) , length(selected_col)/2))
dat=data[ , selected_col ]
nb_selected_maps=length(selected_maps)
# --- Subset of the dataset with only the good chromosome
my_fun=function(x){ a=length(which(x==input$chromo)) ; return( a ) }
nb_good_chromo=apply(dat , 1 , my_fun)
don=dat[ which(nb_good_chromo>0 ) , ]
# Put NA when a marker is attributed to another chromosome
if(length(selected_maps)>1){for(i in seq(2,100,2)[1:nb_selected_maps] ){
tmp=don[,i]
tmp=which( tmp!=input$chromo )
don[tmp, c(i,i+1)]=NA
}}
# --- If the "normalize box" is choosen, I normalize length
if(input$ask_for_normalize==TRUE){
for(i in seq(3,ncol(don),2)){
don[,i]=don[,i]*100/max(don[,i],na.rm=T)
}}
# ========== PART 4 : IF ONE MAP IS SELECTED ONLY, I GIVE A CERTAIN TYPE OF PLOT
if(nb_selected_maps<2){
return(
plot_ly(x=rep(1,nrow(don)),y=don[,3], type="scatter", mode="marker", hoverinfo="text", text=paste(don[,1], "<br>", "position: ",don[,3],sep="") , marker=list(size=10) )%>%
layout(hovermode="closest",
xaxis=list(title = "", zeroline = FALSE, showline = FALSE, showticklabels = FALSE, showgrid = FALSE , range=c(0.5,1.5) ),
yaxis=list( autorange = "reversed", title = "Position (cM)", zeroline = F, showline = T, showticklabels = T, showgrid = FALSE , tickfont=list(color="grey", size=15) , titlefont=list(color="grey", size=15) , tickcolor="grey" , linecolor="grey")
))
}
# ========== PART 5 : COMPARISON PLOT IF I HAVE AT LEAST 2 MAPS SELECTED
# --- PART 5.1: CREATE THE Y AXIS OF LINK BETWEEN MAPS
# Je fais une fonction qui me fait 2 vecteurs de positions pour 2 cartes données : AXE des Y
# There is one vector for the problematic vectors, and one for the not problematic markers.
function_pos=function(x,y){
#Récupération de 2 carte seulement:
pos=na.omit(don[,c(1,x,y)])
# Find the non-problematic markers and count them
M1=pos$marker[order(pos[,2], pos[,3])]
M2=pos$marker[order(pos[,3], pos[,2])]
my_notprobmarkers=LCS(as.character(M1),as.character(M2))$LCS
pos_not_prob=pos[which(pos$marker%in%my_notprobmarkers) , ]
pos_prob=pos[-which(pos$marker%in%my_notprobmarkers) , ]
nb_not_prob=nrow(pos_not_prob)
nb_prob=nrow(pos_prob)
#Il faut que je fasse 2 vecteurs avec les valeur en cM dans l'ordre
# --> NOT PROBLEMATIC MARKERS
my_vect=as.vector(t(as.matrix(pos_not_prob[,c(2,3)])))
correctif=seq(1:length(my_vect)) + rep(c(0,0,1,-1) , length.out=length(my_vect) )
my_vect=my_vect[correctif]
#Mais attention probleme! si je fini sur la carte de gauche, il faut que je revienne a la carte de droite avant de passer a la paire de carte suivante!
if(length(my_vect)%%4 == 0){ my_vect=c(my_vect , my_vect[length(my_vect)] , my_vect[length(my_vect)-1]) }
my_vect_not_prob=my_vect
# --> PROBLEMATIC MARKERS
my_vect=as.vector(t(as.matrix(pos_prob[,c(2,3)])))
correctif=seq(1:length(my_vect)) + rep(c(0,0,1,-1) , length.out=length(my_vect) )
my_vect=my_vect[correctif]
#Mais attention probleme! si je fini sur la carte de gauche, il faut que je revienne a la carte de droite avant de passer a la paire de carte suivante!
if(length(my_vect)%%4 == 0){ my_vect=c(my_vect , my_vect[length(my_vect)] , my_vect[length(my_vect)-1]) }
my_vect_prob=my_vect
# Return the non problematic and problematic marker vectors
return( list(my_vect_not_prob, my_vect_prob, nb_not_prob, nb_prob) )
}
# Apply the function to the selected maps.
pos_final_not_prob=c()
pos_final_prob=c()
nb_of_not_prob=c()
nb_of_prob=c()
for(v in c(1:(nb_selected_maps-1))){
col_x=v*2+1
col_y=v*2+3
a=function_pos( col_x , col_y)
pos_final_not_prob=c(pos_final_not_prob,a[[1]])
pos_final_prob=c(pos_final_prob,a[[2]])
nb_of_not_prob=c(nb_of_not_prob,a[[3]])
nb_of_prob=c(nb_of_prob,a[[4]])
}
# --- PART 5.2: CREATE THE X AXIS OF LINK BETWEEN MAPS
# Once more I do 2 vectors: one for the good markers, one for the problematic ones
xaxis_not_prob=c()
xaxis_prob=c()
num=0
for(i in c(1:(nb_selected_maps-1))){
num=num+1
# not problematic markers
my_nb=nb_of_not_prob[num]
if(my_nb==1){ to_add=c(num,num+1) }else{ to_add=rep(c(num,num+1,num+1,num),my_nb/2) }
if(length(to_add)%%4 == 0){ to_add=c(to_add , to_add[length(to_add)] , to_add[length(to_add)-1]) }
xaxis_not_prob=c(xaxis_not_prob,to_add)
# problematic markers
my_nb=nb_of_prob[num]
if(my_nb==1){ to_add=c(num,num+1) }else{ to_add=rep(c(num,num+1,num+1,num),my_nb/2) }
if(length(to_add)%%4 == 0){ to_add=c(to_add , to_add[length(to_add)] , to_add[length(to_add)-1]) }
xaxis_prob=c(xaxis_prob,to_add)
}
# --- PART 5.3: MAKE THE GRAPH WITH PLOTLY
p=plot_ly()%>%
add_trace(x=xaxis_not_prob , y=pos_final_not_prob, hoverinfo="none" , type="scatter", mode="lines", line=list(width=input$thickness, color=input$my_color , opacity=0.1), showlegend=FALSE )%>%
# Add problematic markers
add_trace(x=xaxis_prob , y=pos_final_prob , hoverinfo="none" , type="scatter", mode="lines", line=list(width=input$thickness, color=input$my_color_bad , opacity=0.1) , showlegend=F)%>%
# Custom the layout
layout(
#Gestion du hovermode
hovermode="closest" ,
# Gestion des axes
xaxis=list(title = "", zeroline = FALSE, showline = FALSE, showticklabels = FALSE, showgrid = FALSE , range=c(0.5,nb_selected_maps+0.5) ),
yaxis=list(range=c(0,500), autorange = "reversed", title = "Position (cM)", zeroline = F, showline = T, showticklabels = T, showgrid = FALSE , tickfont=list(color="grey", size=15) , titlefont=list(color="grey", size=15) , tickcolor="grey" , linecolor="grey")
)
# Add vertical lines to represent chromosomes.
for(m in c(1:nb_selected_maps)){
p=add_trace(p, x=c(m,m), y=c(0, max(don[,m*2+1],na.rm=T)) , type="scatter", mode="lines" , line=list(width=7, color="black", opacity=1),showlegend=F )%>%
layout( yaxis=list(range=c(0,max(don[,m*2+1],na.rm=T))) )
}
# Add markers
for(m in c(1:nb_selected_maps)){
obj2=don[,c(1,m*2+1)]
obj2$text=paste(obj2[,1],"\npos: ",obj2[,2],sep="")
p=add_trace(p, x=rep(m,nrow(obj2) ) , y=obj2[,2] , type="scatter", mode="markers+lines", line=list(color="black", width=8), marker=list(color="black" , size=12 , opacity=0.5,symbol=24) , text=obj2$text , hoverinfo="text", showlegend=F)%>%
layout( yaxis=list(range=c(0,max(pos_final_not_prob))) )
}
# Add maps names
p=add_trace(p, x=seq(1:nb_selected_maps) , y=rep(-10,nb_selected_maps) , text=unlist(liste_of_map_to_compare) , type="scatter" , mode="lines+text" , textfont=list(size=20 , color=input$my_color_name), line=list(color="transparent"), showlegend=F )
# --- PART 5.4: IF THE USER NEED THE PROBLEMATIC MARKERS
list_prob_print=c()
for(i in seq(3,(ncol(don)-2),2 ) ){
for(v in seq(5,ncol(don),2)){
if(v>i){
pos=na.omit(don[,c(1,i,v)])
M1=pos$marker[order(pos[,2], pos[,3])]
M2=pos$marker[order(pos[,3], pos[,2])]
my_notprobmarkers=LCS(as.character(M1),as.character(M2))$LCS
my_probmarkers=pos$marker[-which(pos$marker%in%my_notprobmarkers)]
list_prob_print=c(list_prob_print, as.character(my_probmarkers))
}}}
list_prob_print=data.frame(problematic_markers=unique(list_prob_print))
output$downloadID <- downloadHandler(
filename = function() { paste('Prob_markers_GenMapComp', Sys.Date(), '.csv', sep='') },
content = function(file) { write.table(list_prob_print, file, row.names=FALSE)}
)
#print plotly graph
p
})
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------
# --- SHEET 4 : INTER CHROMOSOME ANALYSIS
#-----------------------------------------------------------------------------
output$plot2 <- renderPlotly({
# Get the needed reactive objects:
summary_stat=MY_summary_stat()
map_files=MY_map_files()
my_maps=MY_maps()
nb_de_carte=length(map_files)
# Avoid bug when loading
if (is.null(input$map1) | is.null(input$map2) | is.null(input$chromo_sheet4) ) {return(NULL)}
# Get the first selected map
selected=which(map_files%in%input$map1)
map1=my_maps[[selected]]
name1=map_files[selected]
# Get the second selected map
selected=which(map_files%in%input$map2)
map2=my_maps[[selected]]
name2=map_files[selected]
# Select the choosen chromosome, the user can choose "all" !
if(input$chromo_sheet4=="all"){map1=map1}else{map1=map1[map1[,1]==input$chromo_sheet4 , ] ; map2=map2[map2[,1]==input$chromo_sheet4 , ]}
# a little function: I remake the x axis to add chromosomes beside each others.
my_fun=function(a){
last=0
to_add=0
out=c()
for (i in a){
if(i>=last) { sortie=i+to_add }
if(i<last) {to_add=to_add+last ; sortie=i+to_add } # +0.05*last
last=i
out=c(out,sortie)
}
return(out)
}
map1$pos_cum_map1=my_fun(map1[,3])
map2$pos_cum_map2=my_fun(map2[,3])
don=merge(map1,map2,by.x=2,by.y=2)
# error message if no common marker:
validate(
need(nrow(don)!=0, "Sorry, no common marker between your 2 maps! ")
)