-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.R
More file actions
3360 lines (2712 loc) · 166 KB
/
server.R
File metadata and controls
3360 lines (2712 loc) · 166 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
shinyServer(function(input, output, session) {
timeinput <- function(a) {
# b=paste0('in(', paste0(a, collapse=","),")")
b=paste0('(', paste0(a, collapse=","),")")
return(b)
}
websiteLive <- getOption("enrichR.live")
datQuery <- paste0("SELECT * FROM bsb_chip_histopath_duration;")
dat <- dbGetQuery(pobj, datQuery)
gQuery <- paste0("Select DISTINCT concat(symbol, ' | ', gene_name) gene_name from all_gene_fc;")
df_pgQuery <- dbGetQuery(pobj, gQuery)
gene <- df_pgQuery$gene_name
## chemEnrichQuery <- paste0("SELECT * FROM bsb_chemical_enricher_menu;")
chemEnrichQuery <- paste0("SELECT compound_name, time, dose, chip_name,
CASE
WHEN tissue =5 THEN 'HEART'::text
WHEN tissue =8 THEN 'LIVER'::text
WHEN tissue =7 THEN 'KIDNEY'::text
WHEN tissue =11 THEN 'SPLEEN'::text
WHEN tissue =1 THEN 'BONE MARROW'::text
WHEN tissue =16 THEN 'THIGH MUSCLE'::text
WHEN tissue =3 THEN 'HEPATOCYTE'::text
WHEN tissue =6 THEN 'INTESTINE'::text
WHEN tissue =2 THEN 'BRAIN'::text
ELSE NULL::text
END AS tissue_name
FROM bsb_chemical_enricher_menu_vu; ")
chem_enrich_dat <- dbGetQuery(pobj, chemEnrichQuery)
################################### cpdatQuery: For Genes to Clinical Pathology #####################################################################
tissuelist2 <- c("1", "2", "5", "6", "8", "7", "11", "16") # This is for Clinical Pathology to Genes tab
######################################################## gwdatQuery: For Genes to Organ Weight ########################################################
gwdatQuery <- paste0("SELECT chip_name, organ, status, duration, signature FROM bsb_gene_weight_change_list;")
gwdat <- dbGetQuery(pobj, gwdatQuery)
################################################# Global Functions to swap tissue number and tissue name ###############################################
timeinput <- function(a) {
# b=paste0('in(', paste0(a, collapse=","),")")
b=paste0('(', paste0(a, collapse=","),")")
return(b)
}
########### The following tissue_num2name() is to convert tissue numbers to tissue names
tissue_num2name <- function(num) {
name = c()
for (i in 1:length(num)) {
if (num[i] == 8) {
name[i] = 'LIVER'
} else if (num[i]== 7) {
name[i] = 'KIDNEY'
} else if (num[i] == 6) {
name[i] = 'INTESTINE'
} else if (num[i] == 5) {
name[i] = 'HEART'
} else if (num[i] == 1) {
name[i] = 'BONE MARROW'
} else if (num[i] == 2) {
name[i] = 'BRAIN'
} else if (num[i] == 11) {
name[i] = 'SPLEEN'
} else {
name[i] = 'THIGH MUSCLE'
}
}
return (name)
}
########### The following tissue_name2num() is to convert tissue names to tissue numbers
tissue_name2num <- function(name) {
num = c()
# num = list()
for(i in 1:length(name)) {
if (name[i] == 'LIVER') {
num[i] = 8
} else if (name[i] == 'KIDNEY') {
num[i] = 7
} else if (name[i] == 'INTESTINE') {
num[i] = 6
} else if (name[i] == 'HEART') {
num[i] = 5
} else if (name[i] == 'BONE MARROW') {
num[i] = 1
} else if (name[i] == 'BRAIN') {
num[i] = 2
} else if (name[i] == 'SPLEEN') {
num[i] = 11
} else {
num[i] = 16 # 'THIGH MUSCLE' is 16
}
}
return(num)
}
########################################################################################################################################################
assaylistQuery <-paste0("SELECT assay_name, tablename, stat_tablename, type from bsb_clin_pathology_list;")
df_assaylistQuery <-dbGetQuery(pobj, assaylistQuery)
assaylist<- df_assaylistQuery$assay_name ### Retrieve assay_name from table bsb_clin_pathology_list and store as a vector
tablelist<- df_assaylistQuery$stat_tablename ### Retrieve stat_tablename from table bsb_clin_pathology_list and store as a vector
detailtablelist <- df_assaylistQuery$tablename ### Retrieve tablename with detail information including experiment bsb_clin_pathology_list and store as a vector
typelist <- c("BLOOD_CHEM", "HEMATOLOGY")
# doselistQuery <- paste0("SELECT distinct dose FROM all_transcript_vu_fc order by 1;")
# df_doselist <-dbGetQuery(pool, doselistQuery)
# doselist <- df_doselist$dose
################################################# End of Defining Variables for Clinical Pathology to Genes ###################################################
dfharmony <- read_excel("harmonizome.xlsx")
# the following hlink() tends todata:get the dfharmony dataframe imported from Excel as input
# x inside the hlink() is the input from a pathology associated entrezid. It could be the gene probe you selected.
hlink <- function (dfharmony, x) {
# initialize harlink as a vector to catch the web link addresses
harlink <- vector (mode = "character", length = length(x))
for (n in 1:length(x)) {
dfharmony %>% filter(entrezid %in% x[n]) -> harmonizelink
#cat("\n******** harmonizelink\n")
#print(harmonizelink)
mylink <- harmonizelink$harmanizome
#cat("\n******** mylink\n")
#print(mylink)
hplink <- vector (mode = "character", length = length(mylink))
if(length(mylink)<1){
hplink[0] <- c( paste0 (paste0('<a href=', paste0(paste0('"', mylink[0]), '"')), paste0(', target="_blank">', paste0(" No Harmonize", "</a>")) ))
}else if (length(mylink)==1) {
hplink[1] <- c( paste0 (paste0('<a href=', paste0(paste0('"', mylink[1]), '"')), paste0(', target="_blank">', paste0(" Harmonize", "</a>")) ) )
}else{
for (i in 1:length(mylink)) {
hplink[i] <- c( paste0 (paste0('<a href=', paste0(paste0('"', mylink[i]), '"')), paste0(', target="_blank">', paste0(paste0(" Harmonize", i), "</a>")) ) )
}
}
hl <- paste(hplink, collapse=', ' )
harlink[n] <- hl
}
#cat("\n******** harlink\n")
harlink
}
# hlink2() is similar to the hlink() except that it only returns the Human gene symbols
hlink2 <- function (dfharmony, x) {
# initialize harlink as a vector to catch the web link addresses
harlink <- vector (mode = "character", length = length(x))
for (n in 1:length(x)) {
dfharmony %>% filter(entrezid %in% x[n]) -> harmonizelink
#cat("\n******** harmonizelink\n")
#print(harmonizelink)
mylink <- harmonizelink$harmanizome
#cat("\n******** mylink\n")
#print(mylink)
hplink <- vector (mode = "character", length = length(mylink))
if(length(mylink)<1){
hplink[0] <- substring(mylink[0], instr (mylink[0], 'gene')+5)
}else if (length(mylink)==1) {
hplink[1] <- substring(mylink[1], instr (mylink[1], 'gene')+5)
}else{
for (i in 1:length(mylink)) {
hplink[i] <- substring(mylink[i], instr (mylink[i], 'gene')+5)
}
}
hl <- paste(hplink, collapse=', ' )
harlink[n] <- hl
}
#cat("\n******** harlink\n")
harlink
}
###########################################################################################################################
################################### The Code for Genes to Pathology Tab ###################################################
###########################################################################################################################
cpdatQuery <- paste0("SELECT assay_name, category, time, tissue, tissue_num, chip_name, type FROM bsb_clinical_assay_list;")
cpdat <- dbGetQuery(pobj, cpdatQuery)
gwdatQuery <- paste0("SELECT chip_name, organ, status, duration, signature FROM bsb_gene_weight_change_list;")
gwdat <- dbGetQuery(pobj, gwdatQuery)
# choose chip name from in1
f_in1 <- reactive({
filter(dat, chip %in% input$in1)
}) # filter out the "chip" information. the in1 is for chip choices. f_in1 is the data frame when you decide to choose a chip.
observeEvent(f_in1(), {
freezeReactiveValue(input, "in2")
print("######### Print f_in1()")
print(f_in1())
choices<-unique(f_in1()$tissue_name)
updateSelectInput(inputId = "in2", choices = choices)
}) # when you have the f_in1 database with a chip. You filter in a tissue_name.
# choose tissue name from in2
f_in1_in2 <- reactive({
req(input$in2)
filter(f_in1(), tissue_name %in% input$in2)
})
observeEvent(f_in1_in2(), {
freezeReactiveValue(input, "in3")
print("######### Print f_in1_in2()")
print(f_in1_in2())
choices <- unique(f_in1_in2()$time)
updateSelectInput(inputId = "in3", choices = choices, selected = 5)
})
# choose time from in3
f_in1_in2_in3 <-reactive({
req(input$in3)
filter(f_in1_in2(), time %in% input$in3)
#choices <- unique(f_in1_in2()$histopathology_name)
})
observeEvent(f_in1_in2_in3(), {
print("######### Print f_in1_in2_in3()")
print(f_in1_in2_in3())
})
# choose pathology from in4()
observeEvent(f_in1_in2_in3(), {
freezeReactiveValue(input, "in4")
print("######### Print f_in1_in2_in3()")
print(f_in1_in2_in3())
choices <- unique(f_in1_in2_in3()$histopathology_name)
updateSelectInput(inputId = "in4", choices = choices, selected = choices)
})
observeEvent(f_in1_in2(), {
freezeReactiveValue(input, "in5")
choices <- unique(gene)
#updateSelectInput(inputId = "in5", choices = choices, selected = choices)
updateSelectizeInput(inputId = "in5", choices = gene, server = TRUE, selected = 'Havcr1 | hepatitis A virus cellular receptor 1 (286934,1387965_at,AF035963_PROBE1)') #this line populates dropdown
})
f_in5 <- reactive({
req(input$in5)
unique(filter(df_pgQuery, gene_name %in% input$in5))
})
observeEvent(f_in5(), {
print("######### Print f_in5()")
print(f_in5())
})
############ The following is the eventReactive to take the input values from the menu choices (Genes to Pathology)
pathology_table = eventReactive(
input$bu1,
{
input$in1 # chip
input$in2 # tissue
input$in3 # time
input$in5 # gene
input$selectSensivity # add tissue specificity and sensitivity of having severity in Control groups
#},
#{
withProgress(message = 'Retrieving affected genes from drugmatrix database in progress',
detail = 'This may take up to 1 minute ...', value = 0.2, { ##Start progress at 0
if (input$selectSensivity == 'Specificity') {
pQuery <- paste0("SELECT DISTINCT his.histopathology_name histopathology_name, his.tissue_name tissue_name, liver.chip_name chip_name, liver.compound_name compound, liver.experiment_name,
liver.dose dose, liver.time timelength, his.average_severity_total severity_total, liver.log_ratio log_ratio, liver.entrezid, liver.annotation
FROM all_transcript_vu_fc liver left join bsb_histopathology_exp_fc his
ON his.experiment=liver.experiment
AND his.tissue = liver.tissue
WHERE his.tissue_name = '", input$in2, "'
AND liver.time IN ", timeinput(input$in3), "
AND liver.chip_name IN ('", input$in1, "')
AND liver.annotation = substr('", input$in5, "', position ('|' IN '", input$in5, "')+2)
;")
} else {
pQuery <- paste0("SELECT DISTINCT his.histopathology_name histopathology_name, his.tissue_name tissue_name, liver.chip_name chip_name, liver.compound_name compound, liver.experiment_name,
liver.dose dose, liver.time timelength, his.average_severity_total severity_total, liver.log_ratio log_ratio, liver.entrezid, liver.annotation
FROM all_transcript_vu_fc liver inner join bsb_histopathology_exp_fc his
ON his.experiment=liver.experiment
AND his.tissue = liver.tissue
INNER JOIN bsb_summary_apical_endpoint b
ON his.experiment = b. experiment AND b.tissue_name = his.tissue_name
AND his.signature = b.signature AND his.histopathology_name = b.assay_name
WHERE liver.chip_name = b.chip_name AND liver.time = b.duration
AND his.tissue_name = '", input$in2, "' AND b.signature = '", input$in2, "'
AND liver.time IN ", timeinput(input$in3), "
AND liver.chip_name IN ('", input$in1, "')
AND liver.annotation = substr('", input$in5, "', position ('|' IN '", input$in5, "')+2)
AND b.call = 'above normal'
AND cast(b.measurement as numeric) > 0
AND his.average_severity_total > 0
UNION
SELECT DISTINCT his.histopathology_name histopathology_name, his.tissue_name tissue_name, liver.chip_name chip_name, liver.compound_name compound, liver.experiment_name,
liver.dose dose, liver.time timelength, his.average_severity_total severity_total, liver.log_ratio log_ratio, liver.entrezid, liver.annotation
FROM all_transcript_vu_fc liver inner join bsb_histopathology_exp_fc his
ON his.experiment=liver.experiment
AND his.tissue = liver.tissue
INNER JOIN bsb_summary_apical_endpoint b
ON his.experiment = b. experiment AND b.tissue_name = his.tissue_name
AND his.signature = b.signature AND his.histopathology_name = b.assay_name
WHERE liver.chip_name = b.chip_name AND liver.time = b.duration
AND his.tissue_name = '", input$in2, "' AND b.signature = '", input$in2, "'
AND liver.time IN ", timeinput(input$in3), "
AND liver.chip_name IN ('", input$in1, "')
AND liver.annotation = substr('", input$in5, "', position ('|' IN '", input$in5, "')+2)
AND b.call <> 'above normal'
AND liver.experiment_name NOT IN (SELECT experiment_name FROM
(SELECT experiment_name, assay_name, compound, measurement, call
FROM bsb_summary_apical_endpoint
WHERE chip_name IN ('", input$in1, "')
AND signature = '", input$in2, "'
AND tissue_name = '", input$in2, "'
) mno
WHERE mno.call = 'above normal'
)
AND cast(b.measurement as numeric) = 0
AND his.average_severity_total = 0
;")
}
print(pQuery)
df_pgPQuery <- dbGetQuery(pobj, pQuery)
print("######################## The following is the queryoutput.################")
print(df_pgPQuery)
print("################# The number of rows of df_pgPQuery.######################")
print(nrow(df_pgPQuery))
tissue_name_display <- df_pgPQuery$tissue_name
mytissue_name <- function() {
return(tissue_name_display[1])
} # Ouptut the tissue name in order to pass into the Summary Table
rowSelected <- function() {
return(nrow(df_pgPQuery))
}
df_pgPQuery <- filter(df_pgPQuery, !is.na(severity_total))
df_pgPQuery <- filter(df_pgPQuery, !is.na(histopathology_name)) # adding this line does not help to get rid of null value of histopathology_name
severity_total <- df_pgPQuery$severity_total
lpathology <- df_pgPQuery$histopathology_name
log_ratio <- df_pgPQuery$log_ratio
chip_name <- df_pgPQuery$chip_name
compound <- df_pgPQuery$compound
experiment_name <- df_pgPQuery$experiment_name
timelength <- df_pgPQuery$timelength
dose <- df_pgPQuery$dose
# gene_name <- df_pgPQuery$gene_name
gene_name <- df_pgPQuery$annotation
print("###########Removing the NULL data and print the df_pgQuery Again! ##############")
print("################################################################################")
print(df_pgPQuery)
incProgress(0.5, message = "Data Retrieved! Now Summarizing data ...",
detail = "This may take up to 30 seconds to 2 minutes")
if(nrow(df_pgPQuery) > 0){
tempDF <- df_pgPQuery %>%
filter(!is.na(severity_total)) %>%
mutate(average_severity_total_cat = ifelse(severity_total > 0, "greater", "zero"))
mydataframe <-tempDF %>%
group_by(histopathology_name, average_severity_total_cat) %>%
spread(average_severity_total_cat, log_ratio) %>%
summarise(count = sum(!is.na(greater)),
count0 = sum(!is.na(zero)),
mean = mean(greater, na.rm=T),
mean0 = mean(zero, na.rm=T),
diff = mean - mean0,
sd = sd(greater, na.rm = T),
sd0 = sd(zero, na.rm = T),
tval = ifelse(count >= 3 & count0 >= 3, wilcox.test(greater, zero, var.equal = F)$statistic, NA),
pval = ifelse(count >= 3 & count0 >= 3, wilcox.test(greater, zero, var.equal = F)$p.val, NA)) %>% filter(!is.na(pval))
# print("############### First time to display mydataframe############")
# print(mydataframe)
d1 = data.frame("Pathology" = lpathology, "Compound" = compound, "Experiment Name" =experiment_name, "Chip Type" = chip_name, "Dose mg per kg" = dose, "Time per day" = timelength, "Average Severity" = severity_total, "Log10 Ratio" = log_ratio)
names(d1) <- c("Pathology" , "Compound", "Experiment Name", "Chip Type", "Dose (mg/kg)", "Time (day)", "Average Severity", "Log10 Ratio")
# Using tidyr package to re-arrange the columns and rows of summary data mydataframe. Use spread(), gather(), and unite()
# keep the first 2 columns and group counts, log10_ratio, std, into type column
incProgress(0.4, message = "Formatting output in progress",
detail = "This step just take 3 seconds ...")
names(mydataframe) <- c("Histopathology Name", "Counts(>0)", "Counts(0)", "Log10 Ratio(>0)", "Log10 Ratio(0)", "Log10 Ratio DIFF", "Std(>0)", "Std(0)", "Tval", "Pval")
tempdf <- data.frame(mydataframe$"Histopathology Name",
mydataframe$"Counts(>0)", mydataframe$"Counts(0)",
round(mydataframe$"Log10 Ratio(>0)", 3), round(mydataframe$"Log10 Ratio(0)", 3),
round(mydataframe$"Log10 Ratio DIFF", 3),
round(mydataframe$"Std(>0)", 3), round(mydataframe$"Std(0)", 3),
round(mydataframe$"Tval", 3),
round(mydataframe$"Pval", 8))
print("############ This is tempdf ###############")
print(tempdf)
names(tempdf) <- c("Histopathology Name", "Counts(>0)", "Counts(0)", "Log10 Ratio(>0)", "Log10 Ratio(0)", "Log10 Ratio DIFF", "Std(>0)", "Std(0)", "Tval", "Pval")
tempdf$pvalcolor1 <- ifelse(tempdf$`Pval` < 0.05, 2, 1) # add a color code to check if P value > 0.05, make it 2, otherwise, make it 1
names(tempdf) <- c("Histopathology Name", "Counts(>0)", "Counts(0)", "Log10 Ratio(>0)", "Log10 Ratio(0)", "Log10 Ratio DIFF", "STD(>0)", "STD(0)", "T-value","P-value", "pvalcolor1")
mydataframe <- tempdf
print("##################### This is my final mydataframe #####################")
print(mydataframe)
}
else
{
d1 = NULL
mydataframe = NULL
}
}) # Progress bar message ended
return(list(mydata = d1, mysummary= mydataframe, outputmytissue_name = mytissue_name(), rowCount=rowSelected()))
}
) # important function to get query and manipulate the pathology table, gene option
output$summaryTable = DT::renderDataTable(
DT::datatable(
pathology_table()$mysummary,
#selection = list(target = 'cell'),
selection = list(mode='single', target = 'cell',
selectable = rbind(cbind(1:nrow(pathology_table()$mysummary), rep(11, nrow(pathology_table()$mysummary))),
cbind(1:nrow(pathology_table()$mysummary), rep(1, nrow(pathology_table()$mysummary))))
), # selection list, ONLY column 1 and column 11 are selectable. But then column 11 will be hidden
rownames = TRUE,
escape = 3,
caption = htmltools::tags$caption(style = 'caption-side: top; text-align: center; color:brown; font-size:150% ;','Table: Summary of Histopathology Counts and Log10 Ratio.'),
# caption = htmltools::tags$caption(style = 'caption-side: top; text-align: center; color:blue; font-size:100% ;','To get the affect details and the boxplots, choose one or more pathologies of your interest.'),
#extensions = 'Buttons',
options=list(
pageLength = 5, info = FALSE,
selector = 'tr>td:nth-child(1)', # only column 1 can be selected
lengthMenu = list(c(5, 10, 25, 500, -1), c("5", "10", "25", "500", "All")),
columnDefs = list(list(className = 'dt-center', targets = c(2,3,4,5,6,7,8,9,10)), list(targets=c(11), visible=FALSE)),
order = list(10, 'asc'),
# dom = 'Bfrtip',
dom = 'Bliftsp',
searchHighlight = TRUE, # When you typy in the Search Box, it will highlight.
buttons=c('copy', 'csv', 'excel', 'pdf', 'print')
),
container = htmltools::withTags(table(class = 'display',
thead(
tr(
th(rowspan=2, ' '),
th(rowspan = 2, 'Histopathology Name'),
th(colspan = 9, paste0('Gene Expression and Pathology Source: ', pathology_table()$outputmytissue_name), class = "dt-center"),
tr(
lapply(rep(
c('# Treatments w/ Pathology', '# Treatments w/o Pathology', 'Avg. Log10 Ratio Treatments w/ Pathology', 'Avg. Log10 Ratio Treatments w/o Pathology',
'Log10 Ratio DIFF', 'STD Treatments w/ Pathology', 'STD Treatments w/o Pathology', 'T-value','P-value'), 1
), th)
))))),
extensions = c("Select"),
#selection = 'none'
) # datatable
%>% formatStyle('Histopathology Name', backgroundColor = '#d4efdf') # Light Green color
%>% formatStyle(columns = "P-value", valueColumns = "pvalcolor1", backgroundColor = styleEqual(levels = c(1, 2), values = c('white', 'pink')) )
) # Summary table output, gene option
countSelection <- function() {
counting <- pathology_table()$rowCount
if (counting > 0){
message = c('There are', counting, 'rows of data retrieved from DrugMatrix')
}else{
#message = c('No matching data found in DrugMatrix')
message = c('Click the Cell that contains Histopathology Name Information. You clicked: ')
# message = c('No matching data found in DrugMatrix')
}
message
} # count for gene option
output$countNum = renderText({
countSelection()
}) # output the count number, gene option
sumSelected <- function() {
cs <- input$summaryTable_cells_selected
ndf <- pathology_table()$mysummary[cs]
ndf
} # gene option
output$summarySelect = renderText({
sumSelected()
}) # output summary table selected cell, gene option
output$pathologyTable = DT::renderDataTable(
pathology_table()$mydata %>% filter(Pathology%in%sumSelected()),
# columnDefs = list(list(className = 'dt-center', targets = 5)),
extensions = 'Buttons',
options = list(
pageLength = 5,
info = FALSE,
lengthMenu = list(c(5, -1), c("First 5 rows", "All")),
dom = 'Bliftsp',
# dom = 'Bfrtip',
buttons = c('copy', 'csv', 'excel', 'pdf', 'print')
),
rownames = TRUE,
caption = htmltools::tags$caption(style = 'caption-side: top; text-align: center; color:brown; font-size:150% ;','Table: Affected Histopathology Detail.')#,
) # gene option
dataPlot <- function()
{
validate (
need(nchar(input$summaryTable_cells_selected) > 0, "Choose one or more pathologies from the summary table above")
)
# cSelectPathology = paste0(sprintf("'%s'", sumSelected()), collapse = ", ")
cSelectPathology = c(sumSelected())
plotData <- filter(pathology_table()$mydata, `Pathology` %in% cSelectPathology)
plotData$`Average Severity` = factor(plotData$`Average Severity`)
###### DEBUG
print("DEBUG: The following data is in the graph.")
print(plotData)
plotData$`Average Severity`[is.na(plotData$`Average Severity`)]
#plotData$`Average Severity`[is.na(plotData$`Average Severity`)] <- 'NULL'
if (input$selectPlot == "0 or >0 Severities") {
plotData$`Average Severity` = as.character(plotData$`Average Severity`)
plotData$`Average Severity`[plotData$`Average Severity` >0] = 'greater than 0'
plotData$`Average Severity` = factor(plotData$`Average Severity`)
}
if (nrow(plotData) > 0) {
# draw the boxplot
plt = ggplot(plotData, aes(x=`Average Severity`, y=`Log10 Ratio`, fill= `Average Severity`)) + xlab("Severity Score") + ylab("Log10 Ratio") + geom_boxplot() + geom_point() + theme_bw() + labs(fill = "Severity Score") + ggtitle("Figure: Box Plot of Severity versus Log10 Ratio") + theme(plot.title = element_text(lineheight=.60, hjust = 0.5, color = "brown", size = 20))
plt + facet_wrap(~ `Pathology`, ncol = 2) + theme(axis.text.x = element_text(face="bold", size=12), axis.text.y = element_text(face="bold", size = 12),
axis.title.x = element_text(color="#993333", size=14, face="bold"),
axis.title.y = element_text(color="#993333", size=14, face="bold")
)
}
else {
plot(c(0, 1), c(0, 1), ann = F, bty = 'n', type = 'n', xaxt = 'n', yaxt = 'n')
text(x = 0.5, y = 0.5, "No Data Found",
cex = 1.6, col = "black")
}
} # algorithm of dataPlot function, gene option
output$boxPlot <- renderPlot(
{
dataPlot()
}) # Ouput the plot, gene option
output$boxplot_download <- downloadHandler(
filename = function()
{
paste(input$"geneprobeplot", paste0('geneprobe_', Sys.time(), '.png'), sep='')
},
content= function(file)
{
# ggsave(file, plot=dataPlot(), width=10, height=10.4)
ggsave(file, plot=dataPlot(), width=8, height=10.4)
}
) # Output the graph - Download button, gene option
################### For Gene Option, in order to get the pathology image, Try to use dataPlot()$cSelectPathology as input. ####################
test <- function() {
ccSelectPathology = paste0(sprintf("'%s'", sumSelected()), collapse = ", ")
print("############### This is gene that I selected ")
print(ccSelectPathology)
gene_path_imageQuery <-paste0("SELECT histopathology_name, severity_name, image_name from bsb_histopathology_image_fc WHERE histopathology_name in (", ccSelectPathology, ");")
print("############## This is the gene_path_imageQuery #################")
print(gene_path_imageQuery)
df_gene_path_imageQuery <-dbGetQuery(pobj, gene_path_imageQuery)
print("############## This is the data frame of df_gene_path_imageQuery ##############")
print(df_gene_path_imageQuery)
gene_img_image_name <- df_gene_path_imageQuery$image_name
gene_img_severity_name <- df_gene_path_imageQuery$severity_name
gene_img_histopathology_name <- df_gene_path_imageQuery$histopathology_name
gene_img_image_name <- paste0(gene_img_image_name, '.JPG_large.jpg')
gene_path_dat <- data.frame(
gene_img_histopathology_name,
gene_img_severity_name,
gene_img_image_name
)
names(gene_path_dat) <- c("Histopathology Name", "Severity", "Image Name")
return(gene_path_dat)
}
output$genePathImagetable = DT::renderDataTable({
DT::datatable(test(), filter = list(position = "top", clear = FALSE),
selection = list(target = 'row'),
options = list(
columnDefs=list(list(visible=FALSE, targets = 3)), # this hids the image name
autowidth = TRUE,
pageLength = -1, # show all the rows. If only 3 row, then type 3
#lengthMenu = c(2, 4)
lengthMenu = list(c(3, -1), c("First 3 rows", "All"))
))
})
gene_path_df <- function() {
gpDF <- test()
gpd <- gpDF[input$genePathImagetable_rows_selected, ]
imgfr <- lapply(gpd$`Image Name`, function(file){ # Image Name used to be gene_img_image_name
tags$div(
tags$img(src=file, width="400", height="310"),
tags$script(src="titlescript.js")
)
})
imgList <- tagList(imgfr)
return(imgList)
}
output$img2 = renderUI({
gene_path_df()
})
###########################################################################################################################
################################### The Code for Pathology to Genes Tab ###################################################
###########################################################################################################################
# choose chip name from in1
f_tab2in1 <- reactive({
filter(dat, chip %in% input$tab2in1)
}) # filter out the "chip" information. the in1 is for chip choices. f_in1 is the data frame when you decide to choose a chip.
observeEvent(f_tab2in1(), {
freezeReactiveValue(input, "tab2in2")
print("######### Print f_tab2in1()")
print(f_tab2in1())
choices<-unique(f_tab2in1()$tissue_name)
updateSelectInput(inputId = "tab2in2", choices = choices)
}) # when you have the f_in1 database with a chip. You filter in a tissue_name.
# choose tissue name from in2
f_tab2in1_in2 <- reactive({
req(input$tab2in2)
filter(f_tab2in1(), tissue_name %in% input$tab2in2)
})
observeEvent(f_tab2in1_in2(), {
freezeReactiveValue(input, "tab2in3")
print("######### Print f_tab2in1_in2()")
print(f_tab2in1_in2())
choices <- unique(f_tab2in1_in2()$time)
updateSelectInput(inputId = "tab2in3", choices = choices, selected = 5)
})
# choose time from in3
f_tab2in1_in2_in3 <-reactive({
req(input$tab2in3)
filter(f_tab2in1_in2(), time %in% input$tab2in3)
#choices <- unique(f_tab2in1_in2()$histopathology_name)
})
# observeEvent(f_tab2in1_in2_in3(), {
# print("######### Print f_tab2in1_in2_in3()")
# print(f_tab2in1_in2_in3())
# })
# choose pathology from in4()
observeEvent(f_tab2in1_in2_in3(), {
freezeReactiveValue(input, "tab2in4")
print("######### Print f_tab2in1_in2_in3()")
print(f_tab2in1_in2_in3())
choices <- unique(f_tab2in1_in2_in3()$histopathology_name)
updateSelectInput(inputId = "tab2in4", choices = choices, selected = choices)
})
############ The following is the eventReactive to take the input values from the menu choices (Genes to Pathology)
gene_table = eventReactive(
input$bu2,
{
# input$selectPathology # in ui section
# input$ptissue # in ui section
# input$pchip # in ui section
# input$ptime
input$tab2in1 # chip
input$tab2in2 # tissue
input$tab2in3 # time
input$tab2in4 # pathology
input$selectSpec # add tissue specificity and sensitivity of having severity in Control groups
# }, # in ui section
# {
withProgress(message = 'Retrieving affected genes from drugmatrix database in progress',
detail = 'This may take 1 ~ 2 minutes.', value = 0, { ##Start progress at 0
if (input$selectSpec == 'Specificity') {
pathologyQuery <- paste0("SELECT DISTINCT concat(liver.symbol, ' | ', liver.annotation) ggene_name, his.tissue_name gtissue_name, liver.compound_name compound_name, liver.experiment_name, avg(liver.log_ratio) glog_ratio,
liver.dose gdose, liver.time gtime, avg(his.average_severity_total) gseverity_total, liver.chip_name gchip_name, liver.entrezid
FROM all_transcript_vu_fc liver
inner JOIN bsb_histopathology_exp_fc his
ON his.experiment=liver.experiment
AND liver.tissue = his.tissue
WHERE his.tissue_name = '", input$tab2in2, "'
AND liver.chip_name IN ('", input$tab2in1, "')
AND his.histopathology_name = '", input$tab2in4, "'
AND liver.time IN ", timeinput(input$tab2in3), "
AND liver.symbol is NOT NULL AND liver.annotation is not NULL
GROUP BY concat(liver.symbol, ' | ', liver.annotation), his.tissue_name, his.tissue_name, liver.compound_name, liver.experiment_name,liver.dose, liver.time, liver.chip_name, liver.entrezid;")
} else {
temptableQuery <- paste0("CREATE TEMP TABLE temp1 (SELECT assay_name, experiment_name, measurement, call
WHERE tissue_name = '", input$tab2in2, "' AND signature = '", input$tab2in2, "'
AND call = 'above normal';
);")
pathologyQuery <- paste0("
SELECT DISTINCT concat(liver.symbol, ' | ', liver.annotation) ggene_name, his.tissue_name gtissue_name, liver.compound_name compound_name, liver.experiment_name,
liver.log_ratio glog_ratio, b.assay_name, liver.dose gdose, liver.time gtime, his.average_severity_total gseverity_total, liver.chip_name gchip_name, liver.entrezid
FROM bsb_histopathology_exp_fc his
INNER JOIN bsb_summary_apical_endpoint b
ON his.experiment = b.experiment AND b.tissue_name = his.tissue_name AND his.signature = b.signature AND his.histopathology_name = b.assay_name
INNER JOIN all_transcript_vu_fc liver
ON liver.experiment = his.experiment AND liver.chip_name = b.chip_name AND liver.time = b.duration AND liver.tissue = his.tissue
WHERE his.tissue_name = '", input$tab2in2, "'
AND his.signature = '", input$tab2in2, "'
AND b.chip_name = '", input$tab2in1, "'
AND b.call <> 'above normal'
AND liver.experiment_name NOT IN (SELECT experiment_name FROM
(SELECT experiment_name, assay_name, compound, measurement, call
FROM bsb_summary_apical_endpoint
WHERE chip_name IN ('", input$tab2in1, "')
AND signature = '", input$tab2in2, "'
AND tissue_name = '", input$tab2in2, "'
) mno
WHERE mno.call = 'above normal'
)
AND b.duration IN ", timeinput(input$tab2in3), "
AND his.histopathology_name = '", input$tab2in4, "'
AND liver.symbol is NOT NULL
AND his.average_severity_total = 0
AND his.average_severity_total IS NOT NULL
UNION
SELECT DISTINCT concat(liver.symbol, ' | ', liver.annotation) ggene_name, his.tissue_name gtissue_name, liver.compound_name compound_name, liver.experiment_name,
liver.log_ratio glog_ratio, b.assay_name, liver.dose gdose, liver.time gtime, his.average_severity_total gseverity_total, liver.chip_name gchip_name, liver.entrezid
FROM bsb_histopathology_exp_fc his
INNER JOIN bsb_summary_apical_endpoint b
ON his.experiment = b.experiment AND b.tissue_name = his.tissue_name AND his.signature = b.signature AND his.histopathology_name = b.assay_name
INNER JOIN all_transcript_vu_fc liver
ON liver.experiment = his.experiment AND liver.chip_name = b.chip_name AND liver.time = b.duration AND liver.tissue = his.tissue
WHERE his.tissue_name = '", input$tab2in2, "'
AND b.signature = '", input$tab2in2, "'
AND b.chip_name = '", input$tab2in1, "'
AND b.call = 'above normal'
AND cast(b.measurement as numeric) > 0
AND his.average_severity_total > 0
AND b.duration IN ", timeinput(input$tab2in3), "
AND his.histopathology_name = '", input$tab2in4, "'
AND liver.symbol is NOT NULL
AND his.average_severity_total IS NOT NULL
;")
}
print("This the df_pathology Query#########################")
print(pathologyQuery)
df_pathologyQuery <- dbGetQuery(pobj, pathologyQuery)
print("this is df_pathology after I pooled it########################")
print(df_pathologyQuery)
print("############ The number of rows the query is: ")
#print(nrow(df_pathologyQuery))
prowSelected <- function() {return(nrow(df_pathologyQuery))}
print(prowSelected())
gtissue_name <- df_pathologyQuery$gtissue_name
mygtissue_name <- function() {
return(gtissue_name[1])
}
print("My tissue selected")
print(mygtissue_name())
print("###########I ONLY NEED THE ABOVE####################")
df_pathologyQuery <- filter(df_pathologyQuery, !is.na(gseverity_total))
ggene_name <- df_pathologyQuery$ggene_name
compound_name <- df_pathologyQuery$compound_name
experiment_name <- df_pathologyQuery$experiment_name
gchip_name <- df_pathologyQuery$gchip_name
gdose <- df_pathologyQuery$gdose
gtime <- df_pathologyQuery$gtime
gseverity_total <- df_pathologyQuery$gseverity_total
glog_ratio <- df_pathologyQuery$glog_ratio
entrezid <- df_pathologyQuery$entrezid
gtissue_name <- df_pathologyQuery$gtissue_name
#increment progress to 50% when dbGetQuery finishes
incProgress(0.5, message = "Data Retrieved! Now Summarizing data ...",
detail = "This may take ~ 4 minutes")
if(nrow(df_pathologyQuery) > 0){
ptempDF <- df_pathologyQuery %>%
# distinct (ggene_name, gtissue_name, compound_name, experiment_name, glog_ratio, gdose, gtime, gseverity_total, gchip_name) %>%
filter(!is.na(gseverity_total)) %>%
mutate(gaverage_severity_total_cat = ifelse(gseverity_total > 0, "greater", "zero"))
ptempDF %>% mutate(index = 1:nrow(.)) %>%
group_by(ggene_name, gaverage_severity_total_cat, entrezid) %>%
spread(gaverage_severity_total_cat, glog_ratio) %>%
mutate(greater = as.numeric(greater),
zero = as.numeric(zero)) %>%
summarise(count = sum(!is.na(greater)),
count0 = sum(!is.na(zero)),
mean = mean(greater, na.rm=T),
mean0 = mean(zero, na.rm=T),
diff = mean - mean0,
sd = sd(greater, na.rm = T),
sd0 = sd(zero, na.rm = T),
tval = ifelse(count >= 3 & count0 >= 3, wilcox.test(greater, zero, var.equal = F)$statistic, NA),
pval = ifelse(count >= 3 & count0 >= 3, wilcox.test(greater, zero, var.equal = F)$p.val, NA)) %>% filter(!is.na(pval)) -> mypathologydataframe
# mypathologydataframe$pgurl <- c(paste0('https://www.ncbi.nlm.nih.gov/gene/', mypathologydataframe$entrezid))
# paste0('<a href="pgurl", target="_blank">', 'Entrez', '</a>')
# mypathologydataframe$pgurl <- c(paste0('<a href="', paste0('https://www.ncbi.nlm.nih.gov/gene/', mypathologydataframe$entrezid), '" , target="_blank">Entrez</a>'))
mypathologydataframe$pgurl <- c( paste0(paste0('<a href="', paste0('https://www.ncbi.nlm.nih.gov/gene/', mypathologydataframe$entrezid), '" , target="_blank">Entrez</a>'), hlink(dfharmony, mypathologydataframe$entrezid)))
print("########### This is the second output of mypathologydataframe")
print(mypathologydataframe) # Finally, I added pgurl into the summary dataframe
# View(mypathologydataframe)
print("########### This prints only 2 columns of mypathologydataframe")
new_df <- mypathologydataframe[,c("pgurl","entrezid")]
print(new_df)
# View(new_df)
d2 = data.frame("Probe" = ggene_name, "Compound" = compound_name, "Experiment Name" = experiment_name, "Chip Type" = gchip_name, "Dose mg per kg" = gdose, "Time per day" = gtime, "Average Severity" = gseverity_total, "Log10 Ratio" = glog_ratio)
#increment progress to 90% when summarise finishes
incProgress(0.4, message = "Formatting output in progress",
detail = "This step just take 3 seconds ...")
names(mypathologydataframe) <- c("Gene Probe Name", "Entrez ID", "Counts(>0)", "Counts(0)", "Log10 Ratio(>0)", "Log10 Ratio(0)", "Log10 Ratio DIFF", "Std(>0)", "Std(0)", "Tval", "Pval", "pgurl")
pathtempdf <- data.frame(mypathologydataframe$"Gene Probe Name",
mypathologydataframe$"pgurl",
mypathologydataframe$"Counts(>0)", mypathologydataframe$"Counts(0)",
round(mypathologydataframe$"Log10 Ratio(>0)", 3), round(mypathologydataframe$"Log10 Ratio(0)", 3),
round(mypathologydataframe$"Log10 Ratio DIFF", 3),
round(mypathologydataframe$"Std(>0)", 3), round(mypathologydataframe$"Std(0)", 3),
round(mypathologydataframe$"Tval", 3),
round(mypathologydataframe$"Pval", 8))
names(pathtempdf) <- c("Gene Probe Name", "pgurl", "Counts(>0)", "Counts(0)", "Log10 Ratio(>0)", "Log10 Ratio(0)", "Log10 Ratio DIFF", "STD(>0)", "STD(0)", "T-value", "P-value")
pathtempdf$pvalcolor2 <-ifelse(pathtempdf$`P-value` < 0.05, 2, 1) # add a color code to check if P value > 0.05, make it 2, otherwise, make it 1
# View(pathtempdf)
mypathologydataframe <- pathtempdf # now the dataframe has 12 columns. The 12th column won't show in the Summary table
}
else
{
d2 = NULL
mypathologydataframe = NULL
}
########################################################################################################################
####################### The following code is for generating the pathology images ######################################
imageQuery <-paste0("SELECT histopathology_name, severity_name, image_name from bsb_histopathology_image_fc
WHERE histopathology_name = '", input$tab2in4, "';")
########## WHERE histopathology_name = 'HEPATOCYTE, CENTRILOBULAR, LIPID ACCUMULATION, MACROVESICULAR';")
df_imageQuery <-dbGetQuery(pobj, imageQuery)
print(df_imageQuery)
img_image_name <- df_imageQuery$image_name
img_severity_name <- df_imageQuery$severity_name
img_histopathology_name <- df_imageQuery$histopathology_name
print(img_histopathology_name)
# the following images are from database
print (img_image_name)
img_image_name <- paste0(img_image_name, '.JPG_large.jpg')
imagedat <- data.frame(
img_histopathology_name,
img_severity_name,
img_image_name
)
names(imagedat) <- c('Histopathology Name', 'Severity', 'Image Name')
}) # Progress bar message ended
return(list(myplotdata = d2, mygenesummary = mypathologydataframe, outputgtissue = mygtissue_name(), mygraph = df_pathologyQuery, prowCount=prowSelected(), imgdat = imagedat))
}
) # important function to get query and maniplate the gene table table, pathology option
output$geneSummaryTable = DT::renderDataTable(
DT::datatable(
# gene_table()$mygenesummary$pgurl <- paste0('<a href="pgurl", target="_blank">', 'Entrez', '</a>'),
{gene_table()$mygenesummary},
selection = list(mode='single', target = 'cell',
selectable = rbind(cbind(1:nrow(gene_table()$mygenesummary), rep(12, nrow(gene_table()$mygenesummary))),
cbind(1:nrow(gene_table()$mygenesummary), rep(1, nrow(gene_table()$mygenesummary))))
), # selection list
rownames = TRUE,
escape = FALSE,
#selection = list(target = 'cell'),
caption = htmltools::tags$caption(style = 'caption-side: top; text-align: center; color:brown; font-size:150% ;','Table: Summary of Histopathology Counts and Log10 Ratio.'),
# caption = htmltools::tags$caption(style = 'caption-side: top; text-align: center; color:blue; font-size:100% ;','To get the affect details and the boxplots, choose one or more gene probes of your interest.'),
extensions = 'Buttons',
options=list(
pageLength = 5, info = FALSE,
lengthMenu = list(c(5, 10, 25, 100, 1000, -1), c("5", "10", "25", "100", "1000", "All")),
columnDefs = list(list(className = 'dt-center', targets = c(2, 3,4,5,6,7,8,9,10, 11)), list(className = 'dt-center', targets = c(12), visible = FALSE) ),
order = list(7, 'desc'),
# dom = 'Bfrtip',
dom = 'Bliftsp',
searchHighlight = TRUE, # When you typy in the Search Box, it will highlight.
buttons=c('copy', 'csv', 'excel', 'pdf', 'print')
),
container = htmltools::withTags(table(class = 'display',
thead(
tr(
th(rowspan=2, ' '),
th(rowspan = 2, 'Gene Probe Name'),
th(rowspan = 2, 'Gene Link'),
th(colspan = 9, paste0('Gene Expression and Pathology Source: ', gene_table()$outputgtissue), class = "dt-center"),
tr(
lapply(rep(
c('# Treatments w/ Pathology', '# Treatments w/o Pathology', 'Avg. Log10 Ratio Treatments w/ Pathology', 'Avg. Log10 Ratio Treatments w/o Pathology',
'Log10 Ratio DIFF', 'STD Treatments w/ Pathology', 'STD Treatments w/o Pathology', 'T-value','P-value'), 1
), th)
))))),
)%>% formatStyle('Gene Probe Name', backgroundColor = '#d4efdf') # Light Green color
#%>% formatStyle('Gene Information', valueColumns="<a href='pgurl'>EntrezID</a>")
%>% formatStyle(columns = "P-value", valueColumns = "pvalcolor2", backgroundColor = styleEqual(levels = c(1, 2), values = c('white', 'pink')) )
) # Summary table output, pathology option