-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.R
2062 lines (1494 loc) · 75.9 KB
/
app.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
# File name: app.R (https://github.com/markdunning/SpheroidAnalyseR)
# Author: Yichen He
# Date: May-2021
# This is a Shiny web app that :
# 1. Allows users to upload spheroid raw files, plate layout and Treatment files
# 2. Removes outliers on raw files based on thresholds and Robust Z-score. Users can download the outlier analysis report
# 3. Merges outlier analysis reports into the final merged file
# Project: Spheroid Analysis
# Rhiannon Barrow, Joe Wilkinson, Mark Dunning, Dr Lucy Stead
# Glioma Genomics
# Leeds Institute of Medical Research
# St James's University Hospital, Leeds LS9 7TF
library(tidyverse)
library(ggthemes)
library(gridExtra)
library(readxl)
library(openxlsx)
library(plotrix)
library(writexl)
library(ggpubr)
library(shiny)
library(shinyjs)
library(DT)
source('SpheroidAnalyseR_lib.R')
manual_outlier_selections = outer(LETTERS[1:8], paste0(1:12,'.'), FUN = "paste")
dim(manual_outlier_selections) =NULL
value_selections = list("Area", "Diameter", "Volume", "Perimeter" , "Circularity")
####################
##### Shiny App ####
####################
# Define UI for application that draws a histogram
ui <- navbarPage(#"SpheroidAnalyseR",
# Title
title=div(img(src="leeds_logo.png",style = "margin:-30px 10px"),"SpheroidAnalyseR"),
windowTitle = HTML("SpheroidAnalyseR"),
## tab panels
# Data input
# Outlier removal
# Merging
# Plotting
# Help
tabPanel("Data Input",
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
# Style
tags$head(
tags$style(
HTML('
* {
font-family: Arial, sans-serif !important;
}
.navbar {min-height:58px !important;}
.navbar-nav {
font-size: 18px;
text-align: center;
}
.navbar-nav > li > a, .navbar-brand {
min-height:58px
}
.navbar-brand{
font-size: 24px;
font-weight: bold;
}')
)),
#Side bar layout
fileInput(inputId = "raw_data","Choose Raw Data",accept=".xlsx",buttonLabel = "Browse", multiple = TRUE),
textOutput("text_raw"),
fileInput(inputId = "layout","Choose Plate Layout",accept=".csv",buttonLabel="Browse"),
textOutput("text_layout"),
fileInput(inputId = "treat_data","Choose Treatment Definitions",accept=".csv",buttonLabel="Browse"),
textOutput("text_treat"),
downloadButton("downloadRawTemplate_btn", "Download the raw data template 1"),
downloadButton("downloadRawTemplate_2_btn", "Download the raw data template 2"),
downloadButton("downloadLayoutTemplate_btn", "Download the plate layout template"),
downloadButton("downloadTreatTemplate_btn", "Download the treatment template")
),
# Show a plot of the generated distribution
mainPanel(
DT::dataTableOutput('x1'),
h2("Preview the data"),
selectInput("select_file_preview",label="Choose a raw file to preview",
list()),
# tableOutput("data_preview"),
DT::dataTableOutput("data_preview"),
h2("Show the treatment groups on the plate"),
selectInput("select_treatment",label="Choose the value to view the layout",
list()),
plotOutput("show_layout")
)
)
),
tabPanel("Outlier Removal",
sidebarPanel(
useShinyjs(),
selectInput("select_file",label="Choose a raw file",
list()),
selectInput("select_view_value",label="Choose a value to plot the outliers",
value_selections),
downloadButton("downloadData_btn", "Download"),
textOutput("textStatus"),
helpText("Please run the outlier removal before downloading the report."),
actionButton("outlier_btn", "Remove outliers"),
helpText("The remove outlier button will plot the data based
on the metric selected above. If you are happy to proceed
with default settings which will remove outliers based on
the pre-set thresholds in the blue box then click remove outliers.
Please use the blue box settings below if
you would like to manually adjust settings prior to outlier removal
(this can be done any number of times)"),
selectInput("manual_outliers",label="Toggle cells status normal/outliers",
manual_outlier_selections,
multiple=TRUE,selectize=TRUE),
actionButton("manual_outliers_btn", "apply manual adjustment"),
helpText("Once you have performed outlier removal,
if you are unhappy with any of the automated choices
you have an option here to manually change the status of any given well
and then go to the top and press remove outliers again"),
textOutput("manualStatus"),
fluidRow(
column(12,
# style = "background-color:#c0ecfa;",
style = "background-color:#F6F1E4",
numericInput("z_score","Robust z-score",value = 1.96, step=0.01, min=0),
helpText("Robust-Z-Score looks at the spread of the data and
removes things that are classed as outliers by a Robust-Z-Score
[1]"),
checkboxInput("pre_screen","Apply Pre-screen thresholds?",value = TRUE),
helpText("Pre-screen thresholds are to allow you to say that you will only include spheroids that lie within a range.
This is because there could be an empty well,
or an error with imaging that has produced a value that you don’t want to be included in any analysis."),
# checkboxInput("override","Apply Manual overrides?",value = FALSE),
conditionalPanel(condition ="input.pre_screen==1",
#- Values above zero
numericInput("area_threshold_low","Area lower limit",value=1,min=0),
numericInput("area_threshold_high","Area higher limit",value=1630000,min=0),
numericInput("diam_threshold_low","Diameter lower limit",value=100,min=0),
numericInput("diam_threshold_high","Diameter higher limit",value=1440,min=0),
numericInput("vol_threshold_low","Volume lower limit",value=1000,min=0),
numericInput("vol_threshold_high","Volume higher limit",value=1567543610,min=0),
numericInput("perim_threshold_low","Perimeter lower limit",value=100,min=0),
numericInput("perim_threshold_high","Perimeter higher limit",value=6276,min=0),
numericInput("circ_threshold_low","Circularity lower limit",value=0.01,min=0),
numericInput("circ_threshold_high","Circularity higher limit",value=1,min=0)
)
)
)
),
# Show a plot of the generated distribution
mainPanel(
useShinyjs(),
# strong("Plate layout after pre-sreen outlier removal (if applied)",id='title_pre'),
#
# plotOutput("outlierPlot"),
strong("Plate layout after robust Z-score outlier removal"),
plotOutput("resultPlot"),
strong("Plot 1"),
plotOutput("plot1Plot"),
strong("Plot 2"),
plotOutput("plot2Plot")
# selectInput("select_z_scores",label="Choose the value to view result plots",
# list("Area", "Diameter", "Volume", "Perimeter" , "Circularity")),
)
),
tabPanel("Merging",
sidebarPanel(
# h4("Only available when all files have been processed"),
helpText("Click merge button to generate merged report. Plots can be added to the report. "),
actionButton("merge_btn", "Merge"),
textOutput("text_create_merge"),
textInput("mergeName_text", "Merged file name", value = paste0("merge_file_", Sys.Date(),".xlsx")),
helpText("Files can only be downloaded if all selected raw data have been processed"),
downloadButton("downloadMerge_btn", "Download the merged file")
# strong(""),
# textInput("configName_text", "Config file name", value = paste0("config_file_", Sys.Date(),".csv")),
# downloadButton("downloadConfig_btn", "Download the config file")
),
mainPanel(
h4("Raw files"),
DT::dataTableOutput("merge_file"),
h4("Previous reports"),
helpText("Previous report can be uploaded for merging"),
checkboxInput("processed_file_chk","Use previous reports",value = FALSE),
# checkboxInput("override","Apply Manual overrides?",value = FALSE),
conditionalPanel(condition ="input.processed_file_chk==1",
#- Values above zero
fileInput(inputId = "processed_data","Choose previous reports",accept=".xlsx",buttonLabel = "Browse", multiple = TRUE),
textOutput("text_processed")
),
DT::dataTableOutput("processed_data_table")
# tableOutput("merge_file")
)
),
tabPanel("Plotting",
sidebarPanel(
h4("Choose plot configuration and add plot"),
selectInput("sel_plot",label="Choose plot types",
c("Bar","Point","Dot","Box")),
selectInput("sel_y",label="Choose value for y axis",
c()),
selectInput("sel_x",label="Choose value for x axis",
c()),
selectInput("sel_gp_1",label="Choose value for colouring",
c()),
selectInput("sel_gp_2",label="Choose value 2 for colouring",
c()),
textInput("plotName_text", "Name of the plot", value = "Plot"),
checkboxInput("bw_plot_chk","Black & white plot",value = FALSE),
actionButton("plt_m_plt_btn", "Plot"),
actionButton("add_m_plt_btn", "Add to the report"),
textOutput("text_merge_plt"),
h2(""),
textInput("plotsName_text", "Plot file name", value = paste0("plots_", Sys.Date(),".xlsx")),
downloadButton("downloadPlots_btn", "Download the report of plots")
),
mainPanel(
h4("Plot"),
plotOutput("mergePlot"))
),
tabPanel("Help",
mainPanel(
includeHTML("help_file_page.html")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output,session) {
shinyjs::disable("downloadMerge_btn")
shinyjs::disable("downloadPlots_btn")
shinyjs::disable("downloadConfig_btn")
shinyjs::disable("downloadData_btn")
use_previous_report <-FALSE
df_output <- NULL
df_origin<-NULL
global_wb <-NULL
df_plot_treat <-NULL
df_plot_layout <-NULL
###preparing for the generate the excel
global_rawfilename <-NULL
global_platesetupname <-NULL
global_df_setup <-NULL
global_df_treat <-NULL
global_Spheroid_data <-NULL
global_RobZ_LoLim <-NULL
global_RobZ_UpLim <-NULL
global_TF_apply_thresholds <-NULL
global_TF_outlier_override <-NULL
global_TF_copytomergedir <-NULL
global_TH_Area_min <-NULL
global_TH_Area_max <-NULL
global_TH_Diameter_min <-NULL
global_TH_Diameter_max <-NULL
global_TH_Volume_min <-NULL
global_TH_Volume_max <-NULL
global_TH_Perimeter_min <-NULL
global_TH_Perimeter_max <-NULL
global_TH_Circularity_min <-NULL
global_TH_Circularity_max <-NULL
TF_apply_thresholds <-TRUE
df_batch_detail <-data.frame()
df_prev_report_detail<-data.frame()
n_cb_raw<-0
n_cb_prev<-0
df_output_list <- FALSE
df_origin_list <- FALSE
df_spheroid_list <- FALSE
raw_file_error = FALSE
layout_file_error = FALSE
treat_file_error = FALSE
# help function for creating checkbox input in table
shinyInput = function(FUN, len, id, value, ...) {
if (length(value) == 1) value <- rep(value, len)
inputs = character(len)
for (i in seq_len(len)) {
inputs[i] = as.character(FUN(paste0(id, i), label = NULL, value = value[i]))
}
inputs
}
# obtain the values of inputs
shinyValue = function(id, len) {
unlist(lapply(seq_len(len), function(i) {
value = input[[paste0(id, i)]]
if (is.null(value)) TRUE else value
}))
}
#### input panel ####
## Read the raw file (first file if multiple files have been uploaded)
## event: Upload raw file
output$text_raw <- reactive({
file <- input$raw_data
## validate the file path is correct
if(!is.null(file)){
for (datapath in file$datapath){
ext <- tools::file_ext(datapath)
req(file)
validate(need(ext == "xlsx","Please upload an xlsx file"))
}
##Iterate through the file and validate the file is correct
by(file, seq_len(nrow(file)), function(row) {
sheet_check = tryCatch( {read_excel(row$datapath, "JobView",col_names=TRUE, .name_repair = "universal")
TRUE}
, error = function(e){F})
validate(
need(sheet_check,paste("The data of", row$name, "should be saved in a sheet named JobView"))
)
# df_raw_check <- readxl::read_xlsx(row$datapath)
df_raw_check <- read_excel(row$datapath, "JobView",col_names=TRUE, .name_repair = "universal")
print(colnames(df_raw_check))
error_list = check_raw(df_raw_check)
if(all(error_list)==FALSE){
raw_file_error<<-TRUE
}else{
raw_file_error<<-FALSE
}
validate(
need(error_list[1],paste("Error file:" , row$name, " Errors: Column names error\nplease refer to the raw file template")),
need(error_list[2],paste("Error file:" , row$name, " Errors: Value error\nCheck values in the raw file"))
)
})
# get the original file names
ori_filename = input$raw_data$name
# Create selections for raw files in both input and outlier removal panels.
updateSelectInput(session, "select_file_preview",
choices = ori_filename,
selected = head(ori_filename, 1))
updateSelectInput(session, "select_file",
choices = ori_filename,
selected = head(ori_filename, 1))
n_cb_raw <<- length(ori_filename)
##initial the variables and UI for merging
df_batch_detail<<-data.frame(
Use = shinyInput(checkboxInput, n_cb_raw, 'cb_raw_', value = TRUE, width='1px'),
File_name=ori_filename, Processed=rep(c(FALSE), times = length(ori_filename)),
Robust_Z_Low_Limit=NA,
Robust_Z_Upper_Limit= NA,
Threshold_Applied = NA,
Threshold_Area_Min =NA,
Threshold_Area_Max =NA,
Threshold_Diameter_Min =NA,
Threshold_Diameter_Max =NA,
Threshold_Volume_Min =NA,
Threshold_Volume_Max =NA,
Threshold_Perimeter_Min =NA,
Threshold_Perimeter_Max =NA,
Threshold_Circularity_Min =NA,
Threshold_Circularity_Max =NA
)
df_output_list <<- vector("list", length = length(ori_filename))
df_origin_list <<- vector("list", length = length(ori_filename))
df_spheroid_list <<- vector("list", length = length(ori_filename))
## update file list in merge tab
#Display table with checkbox buttons
# output$merge_file <-
# DT::renderDataTable({
# DT::datatable(
# cbind(cb_raw = shinyInput(checkboxInput, n_cb_raw, 'cb_raw_', value = TRUE, width='1px'),
# df_batch_detail),
# # df_batch_detail,
# options = list(scrollX = TRUE))})
##
# Init the table for merging
output$merge_file <-
DT::renderDataTable({
DT::datatable(
df_batch_detail,
# df_batch_detail,
escape = FALSE, selection = 'none',
options = list(
pageLength = 5,
scrollY = TRUE,
scrollX = TRUE,
preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } ')
)
)
})
}
""
})
# observeEvent(input$raw_data, {
#
# file <- input$raw_data
#
# ## validate the file path is correct
# if(!is.null(file)){
# for (datapath in file$datapath){
#
# ext <- tools::file_ext(datapath)
# print(datapath)
# print(ext)
# req(file)
# validate(need(ext == "xlsx","Please upload an xlsx file"))
# }
#
# ## validate the file is correct
# for (datapath in file$datapath){
#
# df_raw_check <- readxl::read_xlsx(datapath)
#
# error_list = check_raw(df_raw_check)
#
# if(all(error_list)==FALSE){
# raw_file_error<<-TRUE
# }else{
# raw_file_error<<-FALSE
# }
#
# validate(
# need(error_list[1] == TRUE,"Column names error\nplease refer to the raw file template"),
# need(error_list[2] == TRUE,"Value error\nCheck values in the raw file"))
#
# }
#
#
#
# # get the original file names
# ori_filename = input$raw_data$name
#
# # Create selections for raw files in both input and outlier removal panels.
# updateSelectInput(session, "select_file_preview",
# choices = ori_filename,
# selected = head(ori_filename, 1))
#
# updateSelectInput(session, "select_file",
# choices = ori_filename,
# selected = head(ori_filename, 1))
#
# n_cb_raw <<- length(ori_filename)
# ##initial the variables and UI for merging
# df_batch_detail<<-data.frame(
#
# Use = shinyInput(checkboxInput, n_cb_raw, 'cb_raw_', value = TRUE, width='1px'),
# File_name=ori_filename, Processed=rep(c(FALSE), times = length(ori_filename)),
# Robust_Z_Low_Limit=NA,
# Robust_Z_Upper_Limit= NA,
# Threshold_Applied = NA,
# Threshold_Area_Min =NA,
# Threshold_Area_Max =NA,
# Threshold_Diameter_Min =NA,
# Threshold_Diameter_Max =NA,
# Threshold_Volume_Min =NA,
# Threshold_Volume_Max =NA,
# Threshold_Perimeter_Min =NA,
# Threshold_Perimeter_Max =NA,
# Threshold_Circularity_Min =NA,
# Threshold_Circularity_Max =NA
# )
#
# df_output_list <<- vector("list", length = length(ori_filename))
# df_origin_list <<- vector("list", length = length(ori_filename))
# df_spheroid_list <<- vector("list", length = length(ori_filename))
#
# ## update file list in merge tab
#
# #Display table with checkbox buttons
#
# # output$merge_file <-
# # DT::renderDataTable({
# # DT::datatable(
# # cbind(cb_raw = shinyInput(checkboxInput, n_cb_raw, 'cb_raw_', value = TRUE, width='1px'),
# # df_batch_detail),
# # # df_batch_detail,
# # options = list(scrollX = TRUE))})
# ##
#
# # Init the table for merging
# output$merge_file <-
# DT::renderDataTable({
# DT::datatable(
# df_batch_detail,
# # df_batch_detail,
# escape = FALSE, selection = 'none',
# options = list(
# pageLength = 5,
# scrollY = TRUE,
# scrollX = TRUE,
# preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
# drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } ')
# )
# )
# })
#
# }
# })
## update the raw data preview in the input panel
## event: After uploading the raw data
output$data_preview <- DT::renderDataTable(
{
updateNumericInput(session, "z_score", value = 1.96)
file <- input$raw_data
name_id = which(file$name == input$select_file_preview)
# print(input$select_file_preview)
# print(file$datapath[name_id])
if(!is.null(file)){
ext <- tools::file_ext(file$datapath[name_id])
req(file)
print(file$datapath[name_id])
print(ext)
validate(need(ext == "xlsx","Please upload an xlsx file"))
data <- readxl::read_xlsx(file$datapath[name_id])
DT::datatable(
data,
options = list(scrollX = TRUE,
scrollY = TRUE,
pageLength = 5))
}
}
)
## read layout file
## If treament file has been uploaded:
## draw layout vs treament variables plot in layout & treatment preview
## else:
## only draw the layout in layout & treatment preview
## event: After uploading the layout file
output$text_layout <- reactive({
layout_file <- input$layout
if(!is.null(layout_file)){
ext <- tools::file_ext(layout_file$datapath)
req(layout_file)
validate(need(ext == "csv","Please upload a layout in csv format"))
df_check = read.csv(layout_file$datapath,
row.names = 1,header=TRUE, check.names = FALSE)
error_list = check_layout(df_check)
if(all(error_list)==FALSE){
layout_file_error<<-TRUE
}else{
layout_file_error<<-FALSE
}
validate(need(error_list[1] == TRUE,"Dimension error\nCheck if the file is 8x12 (row names and column names excluded)"),
need(error_list[2] == TRUE,"Column names error\nplease refer to the template"),
need(error_list[3] == TRUE,"Row names error\nplease refer to the template"),
need(error_list[4] == TRUE,"Value error\nCheck values in the layout file"))
layout <- readr::read_csv(layout_file$datapath) %>%
# #layout <- readr::read_csv("layout_example.csv") %>%
dplyr::rename("Row"=X1) %>%
tidyr::pivot_longer(-Row,names_to="Col",
values_to="Index") %>%
mutate(Index = as.factor(Index),Col=as.numeric(Col)) %>%
filter(!is.na(Row))
df_plot_layout <<- layout
layout
}
output$show_layout <- renderPlot(
{
if(!is.null(df_plot_layout)){
if(!is.null(df_plot_treat)){
draw_layout_with_treat(df_plot_layout, df_plot_treat, input$select_treatment)
}
else{
draw_layout(df_plot_layout)
}
}
}
)
""
}
)
## read treament file
## update the treatment variable selections
## If layout file has been uploaded:
## draw layout vs treament variables plot in layout & treatment preview
## event: After uploading the treatment file
output$text_treat<- reactive({
treat_file <- input$treat_data
## TO DO: Need to check that 1st column is named Index
if(!is.null(treat_file)){
ext <- tools::file_ext(treat_file$datapath)
req(treat_file)
validate(need(ext == "csv","Please upload a treatment in csv format"))
df_check = read.csv(treat_file$datapath,
header=TRUE)
error_list = check_treatment(df_check)
if(all(error_list)==FALSE){
treat_file_error<<-TRUE
}else{
treat_file_error<<-FALSE
}
validate(need(error_list[1] == TRUE,"Dimension error\nCheck if the file has 6 rows and at least 8 columns"),
need(error_list[2] == TRUE,"Column names error\nplease refer to the template"),
need(error_list[3] == TRUE,"Row names error\nplease refer to the template"),
need(error_list[4] == TRUE,"Value error\nCheck values in the treatment file"))
treatments <- readr::read_csv(treat_file$datapath) %>%
mutate_all(as.factor)
# update the value for treatment
selections = colnames(treatments)
updateSelectInput(session, "select_treatment",
choices = selections,
selected = head(selections, 1))
df_plot_treat<<-treatments
treatments
}
output$show_layout <- renderPlot(
{
if(!is.null(df_plot_layout)){
if(!is.null(df_plot_treat)){
draw_layout_with_treat(df_plot_layout, df_plot_treat, input$select_treatment)
}
else{
draw_layout(df_plot_layout)
}
}
}
)
""
})
### Functions for plotting layout & treatment preview
draw_layout<-function(df_layout){
df_layout$Col = as.factor(df_layout$Col)
df_layout$Well.Name = paste0(df_layout$Row,df_layout$Col)
ggplot(df_layout, aes(x = Col, y = Row, label=Well.Name)) +
geom_tile() +
geom_text() +scale_y_discrete(limits = rev) +scale_x_discrete(position = "top")
}
draw_layout_with_treat <-function(df_layout, df_treat, value){
layout <- left_join(df_layout,df_treat)
layout$Col = as.factor(layout$Col)
layout$Well.Name = paste0(layout$Row,layout$Col)
ggplot(layout, aes_string(x = "Col", y = "Row",fill=value,label="Well.Name")) +
geom_tile() +
geom_text() + scale_y_discrete(limits = rev)+scale_x_discrete(position = "top")
}
#### outlier removal panel ####
## remove outliers of the selected raw file in the outlier removal panel
## event: click the outlier removal button
output_report <- eventReactive(input$outlier_btn, {
print("file errors")
print(treat_file_error)
print(layout_file_error)
validate(
need(is.numeric(input$z_score) & input$z_score>0, "Please input a positive Z score (numeric)"),
# need(is.numeric(input$z_low), "Please check if the low limit of the Z score is numeric"),
# need(is.numeric(input$z_high), "Please check if the high limit of the Z score is numeric"),
need(is.numeric(input$area_threshold_low) & input$area_threshold_low>0, "Please input a positive area threshold (numeric)"),
need(is.numeric(input$area_threshold_high) & input$area_threshold_high>0, "Please input a positive area threshold (numeric)"),
need(is.numeric(input$diam_threshold_low) & input$diam_threshold_low>0, "Please input a positive diameter threshold (numeric)"),
need(is.numeric(input$diam_threshold_high) & input$diam_threshold_high>0, "Please input a positive diameter threshold (numeric)"),
need(is.numeric(input$vol_threshold_low) & input$vol_threshold_low>0, "Please input a positive volume threshold (numeric)"),
need(is.numeric(input$vol_threshold_high) & input$vol_threshold_high>0, "Please input a positive diameter threshold (numeric)"),
need(is.numeric(input$perim_threshold_low) & input$perim_threshold_low>0, "Please input a positive Perimeter threshold (numeric)"),
need(is.numeric(input$perim_threshold_high) & input$perim_threshold_high>0, "Please input a positive Perimeter threshold (numeric)"),
need(is.numeric(input$circ_threshold_low) & input$circ_threshold_low>0, "Please input a positive Circularity threshold (numeric)"),
need(is.numeric(input$circ_threshold_high) & input$circ_threshold_high>0, "Please input a positive Circularity threshold (numeric)"),
need(input$raw_data, "please upload the raw data"),
need(input$layout, "please upload the layout file"),
need(input$treat_data, "please upload the treatment file"),
need(treat_file_error==FALSE, "Treatment file has errors"),
need(layout_file_error==FALSE, "Layout file has errors"),
need(raw_file_error == FALSE, "Raw file has errors")
)
#- after validating, use the thresholding to remove outliers
#- do the thresholding and generate the wells
#- read from the input
name_id = which(input$raw_data$name == input$select_file)
rawfilename = input$raw_data$datapath[name_id]
ori_rawfilename = input$select_file
# rawfilename = input$raw_data$datapath
platesetupname<- input$layout$datapath
treat_file <- input$treat_data
#
#
df_setup =read.csv(platesetupname)
df_treat = read.csv(treat_file$datapath)
#- import raw data
Spheroid_data <- suppressMessages(read_excel(rawfilename, "JobView",col_names=TRUE, .name_repair = "universal"))
## Used in testing the outlier removal method
# setup_file = "layout_example.csv"
# treatment_file = "treatment_example.csv"
#
# input_file = "GBM58 - for facs - day 3.xlsx"
#
# df_setup =read.csv(setup_file)
# df_treat = read.csv(treatment_file)
# #- import raw data
# Spheroid_data <- suppressMessages(read_excel(input_file, "JobView",col_names=TRUE, .name_repair = "universal"))
RobZ_LoLim <- -(input$z_score)
RobZ_UpLim <- input$z_score
# RobZ_LoLim <- input$z_low
# RobZ_UpLim <- input$z_high
TF_apply_thresholds <<- input$pre_screen
TF_outlier_override <- FALSE
TF_copytomergedir <- FALSE
merge_output_file = "temp_merge_file.xlsx"
report_output_file = "report_file.xlsx"
colnames(df_treat)[1] <- "T_I"
Ccount <- c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
for (j in 1:length(Ccount)){
Ccount[j] <- length(which(df_setup[,1+j] >= 1))
}
checksum <- sum(Ccount)
df_lookup <- data.frame("Row"= 1:96, "Col" = 1:96,"T_I" =0)
for (i_row in 1:8)
{
for (i_col in 1:12)
{
idx = ((i_row-1)*12)+i_col
df_lookup$Row[idx]<- df_setup[i_row,1]
df_lookup$Col[idx] <- i_col
df_lookup$T_I[idx] =df_setup[i_row , i_col+1]
}
}
df_merge <- merge(df_lookup,df_treat, by="T_I")
datalength <- nrow(Spheroid_data)
checksumOK <- TRUE
if (checksum != datalength)
{checksumOK <- FALSE}
validate(
need(checksumOK, paste0("Number of rows of data in raw file (",
datalength,
") does not match the plate setup checksum ("
,checksum,") \nPlease upload "))
)
# #- do the check
# if (checksumOK == "FALSE")
# {
# message("#### Warning : plate setup checksum mismatch. ####","\n")
# message("Number of rows of data in raw file (",datalength ,") does not match the plate setup checksum (",checksum,") \n")
# message("Output file corruption may occur - please recheck your plate setup","\n")
# message("Processing halted","\n")
# message("\n")
# sink()
# stop()
# }
# #- do the check
# if (checksumOK == "TRUE")
#
# {
# message("** Plate setup checksum is valid for raw dataset ","\n")
# message("Number of rows of data in raw file (",datalength ,") matches the checksum (",checksum,") \n")
# }
# deprecated not used in the
# extract job information
# Job_Info_data <- select(Spheroid_data, Project.Folder, Project.ID, Project.Name, Jobdef.ID, Jobdef.Name, Jobrun.Finish.Time,
# Jobrun.Folder, Jobrun.ID, Jobrun.Name, Jobrun.UUID)
#Job_Info_data <- Job_Info_data[1:1,]
# extract relevant columns and create new dataset Spheroid_data_1
Spheroid_data_1 <- select(Spheroid_data, Well.Name, Spheroid_Area.TD.Area, Spheroid_Area.TD.Perimeter.Mean,
Spheroid_Area.TD.Circularity.Mean, Spheroid_Area.TD.Count, Spheroid_Area.TD.EqDiameter.Mean, Spheroid_Area.TD.VolumeEqSphere.Mean)
colnames(Spheroid_data_1) <- c("Well.Name", "Area", "Perimeter", "Circularity","Count", "Diameter", "Volume" )
# replace any zero values with null value to calculate median values properly
Spheroid_data_1$Area <- ifelse(Spheroid_data_1$Area==0, NA, Spheroid_data_1$Area)
Spheroid_data_1$Perimeter <- ifelse(Spheroid_data_1$Perimeter==0, NA, Spheroid_data_1$Perimeter)
Spheroid_data_1$Circularity <- ifelse(Spheroid_data_1$Circularity==0, NA, Spheroid_data_1$Circularity)
Spheroid_data_1$Diameter <- ifelse(Spheroid_data_1$Diameter==0, NA, Spheroid_data_1$Diameter)
Spheroid_data_1$Volume <- ifelse(Spheroid_data_1$Volume==0, NA, Spheroid_data_1$Volume)
Spheroid_data_1$Area<- as.numeric(Spheroid_data_1$Area)
if (TF_apply_thresholds == TRUE) {
TH_Area_min <- input$area_threshold_low
TH_Area_max <- input$area_threshold_high
TH_Diameter_min <- input$diam_threshold_low
TH_Diameter_max <- input$diam_threshold_high
TH_Volume_min <- input$vol_threshold_low
TH_Volume_max <- input$vol_threshold_high
TH_Perimeter_min <- input$perim_threshold_low
TH_Perimeter_max <- input$perim_threshold_high
TH_Circularity_min <- input$circ_threshold_low
TH_Circularity_max <- input$circ_threshold_high
pre_threshold_cond<-Spheroid_data_1$Area < TH_Area_max & Spheroid_data_1$Area > TH_Area_min &
Spheroid_data_1$Diameter<TH_Diameter_max & Spheroid_data_1$Diameter>TH_Diameter_min &
Spheroid_data_1$Circularity<TH_Circularity_max & Spheroid_data_1$Circularity>TH_Circularity_min &
Spheroid_data_1$Volume<TH_Volume_max & Spheroid_data_1$Volume>TH_Volume_min &
Spheroid_data_1$Perimeter<TH_Perimeter_max & Spheroid_data_1$Perimeter>TH_Perimeter_min
# AND version
Spheroid_data_1$Area <- ifelse(pre_threshold_cond, Spheroid_data_1$Area, NA)
Spheroid_data_1$Diameter <- ifelse(pre_threshold_cond, Spheroid_data_1$Diameter, NA)
Spheroid_data_1$Circularity <- ifelse(pre_threshold_cond, Spheroid_data_1$Circularity, NA)
Spheroid_data_1$Volume <- ifelse(pre_threshold_cond, Spheroid_data_1$Volume, NA)
Spheroid_data_1$Perimeter <- ifelse(pre_threshold_cond, Spheroid_data_1$Perimeter, NA)
# Previous OR version
# Spheroid_data_1$Area <- ifelse(Spheroid_data_1$Area < TH_Area_max & Spheroid_data_1$Area > TH_Area_min, Spheroid_data_1$Area, NA)
# Spheroid_data_1$Diameter <- ifelse(Spheroid_data_1$Diameter<TH_Diameter_max & Spheroid_data_1$Diameter>TH_Diameter_min, Spheroid_data_1$Diameter, NA)
# Spheroid_data_1$Circularity <- ifelse(Spheroid_data_1$Circularity<TH_Circularity_max & Spheroid_data_1$Circularity>TH_Circularity_min, Spheroid_data_1$Circularity, NA)
# Spheroid_data_1$Volume <- ifelse(Spheroid_data_1$Volume<TH_Volume_max & Spheroid_data_1$Volume>TH_Volume_min, Spheroid_data_1$Volume, NA)