-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.R
More file actions
3047 lines (2570 loc) · 115 KB
/
Copy pathapp.R
File metadata and controls
3047 lines (2570 loc) · 115 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
# Set maximum file size limit (e.g., 10MB = 10*1024^2)
options(shiny.maxRequestSize = 40*1024^2) # Set to 40MB
# LIBRARY SETUP ----
library(shiny)
library(shinyjs)
library(readr)
library(dplyr)
library(ggplot2)
library(ggtext)
library(colourpicker)
library(ggrepel)
library(arrow)
library(DT)
library(plotly)
# Cairo Graphics Library - Conditional Loading
# Cairo provides high-quality graphics rendering and is especially beneficial for:
# - Publication-quality plot output with better anti-aliasing
# - Consistent cross-platform graphics rendering
# - Enhanced PDF/PNG export capabilities
# - Better font rendering and Unicode support
#
# macOS Installation Issues:
# Cairo can be problematic on macOS due to:
# - Complex system dependencies (X11, fontconfig, freetype)
# - Conflicts between Homebrew Intel/ARM installations
# - Xcode Command Line Tools version mismatches
# - Different Cairo versions in system vs. Homebrew paths
#
# The app functions without Cairo using R's default graphics devices,
# but users may experience slightly lower quality plot rendering.
if (requireNamespace("Cairo", quietly = TRUE)) {
library(Cairo)
message("✓ Cairo graphics library loaded - enhanced plot rendering available")
} else {
message("ℹ Cairo not available - using default graphics (install Cairo for enhanced rendering)")
}
library(gt)
library(shiny.semantic)
library(semantic.dashboard)
library(gridExtra)
# WebShot2 - Conditional Loading
# WebShot2 enables web page screenshots and may depend on Cairo availability
# Falls back gracefully if not available
# This version of the app exports GT tables as HTML files and does not depend on
# webshot2. PDF export depends on webshot2 which is not working in the posit connect cloud - that is why
# export was changed to HTML export. You can enable
#pdf export by modifying the downloadHandler() code for gt tables before installation in your private server
if (requireNamespace("webshot2", quietly = TRUE)) {
library(webshot2)
message("✓ WebShot2 loaded - screenshot capabilities available")
} else {
message("ℹ WebShot2 not available - some export features may be limited")
}
library(shinyalert)
library(tidyr)
library(data.table)
# TELEMETRY ----
# This telemetry module uses REST API to connect to supabase and send the data to Postgres database
# If you want to use this module, you need to set up the supabase (or similar database) account and get the API key and URL
# If you want to use the app locally this should be commented out
#source("./Scripts_R/Telemetry_module_API.R")
message("------TELEMETRY INFO---------")
message("Telemetry module is commented out for your convenient local use -
no data is being collected. Uncomment and add API key to .Renviron file if you want to use your own telemetry. The default variables used by telemetry module are SUPABASE_URL=[url for you database] and
SUPABASE_KEY=[API_key]. You can set them in .Renviron file. You can also use direct connection
to database - check optional module in telemetry_modules folder. If you just want to use the app locally, the code should stay commented out.")
message("----------------------------")
# Loading the GO data once globally
# The preparation of this file is described in https://github.com/DatViseR/Vivid-GO-data and in the script
# Parquet_GO_source_data_preparation_script.R
# The file is also available in the data folder of this repository
# This newfile contains around 8000 non-obsolete unique GO categories with at least 6 annotated genes in the category
GO <- arrow::read_parquet("GO.parquet2")
# This is the structure of the one main "source of truth" file for GO
# Classes ‘spec_tbl_df’, ‘tbl_df’, ‘tbl’ and 'data.frame': 693408 obs. of 4 variables:
# $ id : chr "GO:0003723" "GO:0005515" "GO:0046872" "GO:0005829" ...
# $ name : chr "RNA binding" "protein binding" "metal ion binding" "cytosol" ...
# $ gene : chr "NUDT4B" "NUDT4B" "NUDT4B" "NUDT4B" ...
# $ ontology: chr "F" "F" "F" "C" ...
# - attr(*, "spec")=List of 3
# ..$ cols :List of 4
# .. ..$ id : list()
# .. .. ..- attr(*, "class")= chr [1:2] "collector_character" "collector"
# .. ..$ name : list()
# .. .. ..- attr(*, "class")= chr [1:2] "collector_character" "collector"
# .. ..$ gene : list()
# .. .. ..- attr(*, "class")= chr [1:2] "collector_character" "collector"
# .. ..$ ontology: list()
# .. .. ..- attr(*, "class")= chr [1:2] "collector_character" "collector"
# ..$ default: list()
# .. ..- attr(*, "class")= chr [1:2] "collector_guess" "collector"
# ..$ delim : chr "\t"
# ..- attr(*, "class")= chr "col_spec"
# SOURCING CUSTOM FUNCTIONS FOR VIVID VOLCANO APP----
# source file with custom functions for Vivid Volcano
source("./Scripts_R/vivid_functions.R")
#------UI----------------------------------------------------------------------
ui <- semanticPage(
useShinyjs(),
## full screen loader for GSEA ----
div(
id = "gsea-loader-overlay",
style = "display: none; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 200px; height: 200px; background: rgba(0,0,0,0.7); z-index: 9999;",
div(
class = "ui active big text loader",
style = "color: white !important;",
"Running GSEA analysis..."
)
),
## full screen loader for draw volcano ----
div(
id = "volcano-loader-overlay",
style = "display: none; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 200px; height: 200px; background: rgba(0,0,0,0.7); z-index: 9999;",
div(
class = "ui active big text loader",
style = "color: white !important;",
"Creaing volcano plots and GO analysis tables..."
)
),
## Includes custom CSS and JS files ----
tags$head(
tags$link(rel = "stylesheet",
type = "text/css",
href = paste0("custom.css?v=", Sys.time())),
tags$link(rel = "stylesheet",
href = "https://cdn.jsdelivr.net/npm/fomantic-ui@2.9.3/dist/semantic.min.css"),
tags$script(src = "telemetry.js"),
tags$script(HTML(
"
// Send the current client width to the server
$(document).on('shiny:connected', function() {
Shiny.setInputValue('clientWidth', window.innerWidth);
});
$(window).on('resize', function() {
Shiny.setInputValue('clientWidth', window.innerWidth);
});
// Toggle behavior for annotations - including click events on labels
$(document).on('change', '#hide_annot', function() {
toggleAnnotationState($(this).is(':checked'));
});
// Add click handlers for the text labels
$(document).on('click', '#show-text, #hide-text', function() {
var isHideText = $(this).attr('id') === 'hide-text';
var checkbox = $('#hide_annot');
// Update checkbox state
checkbox.prop('checked', isHideText);
// Trigger change event for Shiny
checkbox.trigger('change');
// Update visual state
toggleAnnotationState(isHideText);
// Send value to Shiny explicitly
Shiny.setInputValue('hide_annot', isHideText);
});
// Function to handle state changes
function toggleAnnotationState(isHidden) {
if (isHidden) {
$('#show-text').removeClass('green').addClass('basic');
$('#hide-text').removeClass('basic').addClass('green');
} else {
$('#hide-text').removeClass('green').addClass('basic');
$('#show-text').removeClass('basic').addClass('green');
}
}
"
))
),
## navbar ----
segment(class = "navbar",
img(src = "Vivid_volcano_logo.png", alt = "Logo", class = "logo"),
div(class = "left-section",
h1("Vivid Volcano", class = "title"),
h4("Publication-ready volcano plots and GO analysis with ease", class = "subtitle")
),
div(class = "social-buttons",
h5("Source Code", class = "icon-header"),
a(href = "https://github.com/DatViseR",
icon("github big"),
class = "github",
target = "_blank"
),
h5("Developer", class = "icon-header"),
a(href = "https://www.linkedin.com/in/tomasz-st%C4%99pkowski/",
icon("linkedin big"),
class = "linkedin",
target = "_blank"
),
h5("Buy me a coffee?", class = "icon-header"),
a(href = "https://buymeacoffee.com/datviser",
icon("fa-solid fa-mug-hot"),
class = "coffe",
target = "_blank"
),
)
),
## sidebar and main layout ----
div(class = "ui fluid container",
# Main layout using sidebar
sidebar_layout(
# Sidebar panel with controls
sidebar_panel(
width = 3,
### Data Upload Segment ----
div(class = "ui raised segment",
header(title = "Upload your data", description = "", icon = "upload"),
div(class = "ribbon-container",
div(class = "ui grey ribbon label",
"Upload a CSV or TSV file"),
),
div(class = "tooltip-container",
tags$i(class = "info circle icon info-icon"),
div(class = "tooltip-text",
HTML("
<div style='line-height: 1.4; max-width: 400px;'>
<strong style='color: #2185D0;'>Accepted file formats:</strong><br>
- CSV (comma or semicolon separated values)<br>
- TSV (tab-separated values)<br>
<strong style='color: #2185D0;'>Upload an omics dataset in which a single gene/protein is an observation</strong><br>
(must contain gene names!)<br>
<strong style='color: #2185D0;'>Performs many data curations</strong><br>
(always displays an info in case data is modified!)<br>
</div>
")
)
),
div(class = "ui file input",
file_input("file1",
label = paste0("Maximum file size: 40MB"),
accept = c(".csv", ".tsv"))
),
#### download link for demo data ----
div(class = "download-demo",
style = "display: flex; justify-content: center; align-items: center;", # Removed padding here as it's handled in CSS
tags$a(
href = "demo_data.csv",
download = NA,
class = "ui labeled icon button compact",
style = "box-shadow: 0 2px 4px rgba(0,0,0,0.1); transition: all 0.2s ease;",
tags$i(class = "download icon",
style = "margin-right: 0.5em !important;"),
span(
"Download demo data",
style = "margin-right: 0.5em;"
),
span(
"(separator:tab,decimal:comma)",
style = "font-size: 0.9em; opacity: 0.8;"
)
)
),
#### layout for checkbox and radio buttons ----
div(class = "ui form",
style = "margin: 0.2rem 0;", # Reduced vertical margin
div(class = "three fields",
style = "margin: 0.2rem !important; gap: 0.5rem !important;", # Reduced margin and gap between fields
# Header Checkbox
div(class = "field",
style = "margin: 0 !important;", # Remove default field margin
div(style = "display: flex; flex-direction: column; gap: 10px;", # Reduced gap
div(style = "font-weight: bold; margin-bottom: 1px;", "Header"), # Reduced margin
shiny.semantic::toggle("header", "", is_marked = TRUE)
)
),
# Separator Radio Buttons
div(class = "field",
style = "margin: 0 !important;", # Remove default field margin
multiple_radio(class = "radio compact",
"sep",
"Separator",
choices = list("Comma" ,
"Semicolon",
"Tab"),
choices_value = c(",", ";", "\t"),
selected = ",")
),
# Decimal Point Radio Buttons
div(class = "field",
style = "margin: 0 !important;", # Remove default field margin
multiple_radio("dec",
"Decimal Point",
choices = list("Dot" ,
"Comma"),
choices_value = c(".", ","),
selected = ".")
)
)
),
actionButton("upload", label = HTML('<i class="upload icon"></i> Upload'),
class = "ui primary button")
),
### Column Selection Segment ----
uiOutput("column_select_ui"),
### Analysis Options ----
div(class = "ui raised segment",
# ribbon
header(title = "Analysis Options", description = "Customize GSEA and volcano plot options",icon = "cogs"),
div(class = "ui grey ribbon label", "Customize p value adjustment"),
div(class = "tooltip-container",
style = "display: inline-block;",
tags$i(class = "info circle icon info-icon"),
div(class = "tooltip-text",
style = "position: absolute; z-index: 100;",
HTML("
<div style='line-height: 1.4; max-width: 400px;'> <!-- Add max-width to control tooltip size -->
<strong style='color: #2185D0;'>Why Adjust P-values?</strong>
<div style='margin: 8px 0; font-size: 0.9em;'>
Multiple testing increases false positive risk - when testing many hypotheses, some will appear significant by chance alone.
</div>
<strong style='color: #2185D0;'>Available Methods:</strong>
<ul style='margin: 8px 0; padding-left: 20px;'>
<li><strong>Benjamini-Hochberg (BH)</strong>: Controls false discovery rate (FDR), balances power and false positives</li>
<li><strong>Benjamini-Yekutieli (BY)</strong>: More conservative than BH, makes no assumptions about dependencies</li>
<li><strong>Hochberg</strong>: Less conservative than Bonferroni, controls family-wise error rate</li>
<li><strong>Bonferroni</strong>: Most conservative, strongly controls family-wise error rate</li>
<li><strong>None</strong>: Unadjusted p-values, high false positive risk</li>
</ul>
<div style='font-size: 0.9em; color: #666; margin-top: 8px;'>
<i>Recommendation:</i> BH is suitable for most analyses. BY provides more conservative control but at the cost of statistical power.Use BY if you have, for example, RNA‐sequencing data from heterogeneous tumor samples where unpredictable, complex gene co-expression patterns create unknown dependencies among tests, necessitating robust FDR control despite reduced power. </div>
</div>
")
)
),
#### p value adjustment controls ----
dropdown_input("adj",
choices = c("None",
"Bonferroni",
"Hochberg",
"Benjamini-Hochberg",
"Benjamini-Yekutieli"),
choices_value = c("none", "bonferroni", "hochberg", "BH", "BY"),
value = "BH"),
numericInput("alpha", "Significance Threshold", value = 0.050, min = 0.0001, max = 1, step = 0.0001,
),
div(class = "ui grey ribbon label", "GSEA analysis controls"),
div(class = "tooltip-container",
tags$i(class = "info circle icon info-icon"),
div(class = "tooltip-text",
HTML("
<div style='line-height: 1.4;'>
<strong style='color: #2185D0;'>GO Term Selection Criteria for Gene Set Enrichment analysis (GSEA):</strong>
<ul style='margin: 8px 0; padding-left: 20px;'>
<li>Terms must contain 5-500 genes detected in your experiment</li>
<li>At least 5% of genes in each term must be detected in your data</li>
<li>Filtered by selected ontology category</li>
</ul>
<div style='font-size: 0.9em; color: #666;'>
This ensures meaningful and statistically relevant GO terms for your analysis.
</div>
</div>
")
)
),
div(class = "ui form",
toggle("GSEA_acvited", "I want to run GSEA", FALSE)
#### GSEA controls ----
), uiOutput("gsea_controls_ui"),
#### Plot Options Card ----
div(class = "ui grey ribbon label", "Customize volcano plot annotations") ,
toggle("color_highlight", "Color significantly regulated genes", FALSE),
uiOutput("color_highlight_ui"),
toggle("show_go_category", "Visualize GO Categories", FALSE),
uiOutput("go_category_ui"),
uiOutput("color_picker_ui"),
numericInput("num_labels", "Number of Gene Labels (0-100)",
value = 10, min = 0, max = 100),
toggle("trim_gene_names", "Trim Multiplied Gene Names to First Occurrence", TRUE),
toggle("select_custom_labels", "Label your choosen genes", FALSE),
uiOutput("custom_gene_labels_ui"),
div(class = "ui grey ribbon label",
style = "margin-bottom: 0rem !important;", # Reduced margin for first ribbon
"Customize plot title"),
textInput("plot_title", "", "Vivid Volcano"),
div(class = "ui grey ribbon label",
style = "margin-bottom: 0rem !important;", # Reduced margin for second ribbon
"Customize X -axis label"),
textInput("x_axis_label", "",
"Log2 Fold Change (Condition X vs. Condition Y)"),
actionButton("draw_volcano", "Draw Volcano Plot",
class = "ui primary button",
icon = icon("chart line icon")),
uiOutput("download_log_ui")
),
),
## Main panel ----
main_panel(
width = 12,
## Dataset preview ----
segment(
class = "raised",
div(class = "ui grey ribbon label", "State of data source preview"),
semantic_DTOutput("dataset_summary", height = "auto")
),
## Results ----
segment(
class = "placeholder",
header(title = "Results", description = "", icon = "fa-solid fa-square-poll-vertical"),
uiOutput("dynamic_tabset")
)
)
)
)
)
# SERVER----
server <- function(input, output, session) {
## Telemetry ----
# If you want to use telemetry - uncomment the code below and create a local
# .Renviron file with your API key and URL for database or credential for direct connection
# If you just want to use the app locally, the code below should stay commented out
# # Initialize telemetry
# user_agent <- session$request$HTTP_USER_AGENT
# telemetry <- create_telemetry(user_agent)
#
# # When visit information is received from browser local storage
# observeEvent(input$telemetry_visit_count, {
# req(input$telemetry_visit_count)
#
# if (!is.null(telemetry)) {
# telemetry$update_visitor_info(
# visit_count = input$telemetry_visit_count
# )
# }
# })
#
# # Track button clicks
# observeEvent(input$telemetry_button_click, {
# req(input$telemetry_button_click)
#
# if (!is.null(telemetry)) {
# button_type <- input$telemetry_button_click$button
# telemetry$increment_counter(button_type)
# }
# })
#
# # End session tracking when user leaves
# session$onSessionEnded(function() {
# if (!is.null(telemetry)) {
# telemetry$end_session()
# }
# })
#
## Reactive values----
# Data source and plots
uploaded_df <- reactiveVal()
regulated_sets <- reactiveVal(NULL)
volcano_plot_rv <- reactiveVal()
volcano_plot_original <- reactiveVal()
# logging system
log_messages <- reactiveVal("")
#display
is_mobile <- reactiveVal(FALSE)
#analysis
gsea_results <- reactiveVal(NULL)
gsea_filtered_results <- reactiveVal(NULL)
# chosen ontology used for creation of non-reactive title after GSEA was run
plotOntologyValue <- reactiveVal("P")
# State management
column_select_module_state <- reactiveVal("initial")
# to prevent multiple triggers of cancel button
reset_input <- debounce(reactive(input$reset_columns), 500)
#Creates session variables at server start
session_id <- substr(digest::digest(session$token), 1, 6)
session_start_time <- Sys.time()
# Creates the logging functions with session context
log_event <- create_logger(session)
log_structure <- create_structure_logger(session)
## Screen width observer ----
# Immediate logging of initial display state
observeEvent(input$clientWidth, {
req(input$clientWidth) # Ensure the value is available
current_is_mobile <- input$clientWidth <= 800
is_mobile(current_is_mobile)
log_event(log_messages,
sprintf("Browser window size: %dpx (%s view)",
input$clientWidth,
if(current_is_mobile) "MOBILE" else "DESKTOP"),
"INFO display initialization")
}, once = TRUE)
# Monitor for changes in window size
observeEvent(input$clientWidth, {
req(input$clientWidth)
current_is_mobile <- input$clientWidth <= 800
previous_is_mobile <- isolate(is_mobile())
if (current_is_mobile != previous_is_mobile) {
is_mobile(current_is_mobile)
log_event(log_messages,
sprintf("Display changed to %s view (width: %dpx)",
if(current_is_mobile) "MOBILE" else "DESKTOP",
input$clientWidth),
"INFO display change")
}
})
# Upload observer ----
observeEvent(input$upload, {
req(input$file1)
in_file <- input$file1
# Instaed of read_delim which was slow I introduced fread from data.table but to maintain consistency with the rest
#of the code the df is saved as standard data frame not data.table. Also multithreading for upload was introduced.
df <- data.table::fread(
in_file$datapath,
sep = input$sep,
header = input$header,
dec = input$dec,
data.table = FALSE,
na.strings = c("NA", ""), # I added this after testing as fread parsed some of the test trailing columns as empty strings...
nThread = min(4, parallel::detectCores()-1) # Use multiple cores, but not all
)
uploaded_df(df)
# create log event for successful initialization of reactive values
log_event(log_messages, "Reactive value uploaded_df initialized successfully", "INFO from upload observer")
# Log the structure of the uploaded dataset
log_structure(log_messages, df, "The structure of the uploaded dataset is:", "INFO from upload observer")
log_event(log_messages, "Dataset uploaded successfully", "SUCCESS from upload observer")
# Run combined diagnostic and cleaning
df_cleaned <- diagnose_and_clean_data(
df = df,
log_messages_rv = log_messages,
log_event = log_event,
log_structure = log_structure
)
# Update if cleaning returns result
if (!is.null(df_cleaned)) {
uploaded_df(df_cleaned)
}
log_structure(log_messages, df, "The structure of the uploaded dataset after 1st diagnostic preprocesing:", "INFO from upload observer")
column_select_module_state("reseted")
## Reactive column select UI ----
output$column_select_ui <- renderUI({
if (is.null(df)) return(NULL)
# Log event to indicate that the UI has been rendered
log_event(log_messages, "Reactive UI for column selection rendered", "INFO from output$column_select_ui")
div(class = "ui raised segment",
div(class = "ui grey ribbon label", "Select Data"),
div(class = "tooltip-container",
tags$i(class = "info circle icon info-icon"),
div(class = "tooltip-text",
HTML("
<div style='line-height: 1.4; max-width: 400px;'>
<h4 style='color: #2185D0; margin-bottom: 2px;'><strong>Upload crucial columns for all observations:</strong></h4>
<ul style='margin: 8px 0; padding-left: 20px;'>
<li style='margin-bottom: 12px;'>
<i class='circle icon' style='color: #2185D0;'></i>
<strong>Raw p-values</strong>
<div style='margin-left: 20px; color: #2185D0; font-size: 0.9em;'>
Automatically detects and handles log-transformed values
</div>
</li>
<li style='margin-bottom: 12px;'>
<i class='circle icon' style='color: #2185D0;'></i>
<strong>Log2 fold expression difference</strong>
</li>
<li style='margin-bottom: 12px;'>
<i class='circle icon' style='color: #2185D0;'></i>
<strong>Gene names</strong>
<div style='margin-left: 20px; color: #2185D0; font-size: 0.9em;'>
Supports both human and mice nomenclature
</div>
</li>
</ul>
<div style='margin-top: 20px; padding: 10px; border-left: 3px solid #2185D0; border-radius: 3px;'>
<strong>Additional Features:</strong>
<div style='color: #2185D0; margin-top: 5px; font-size: 0.9em;'>
Handles missing data and provides notifications for dataset modifications
</div>
</div>
</div>
")
)
),
selectInput("pvalue_col", "Select p-value column", choices = names(df)),
selectInput("fold_col", "Select regulation column - log2(fold)", choices = names(df)),
selectInput("annotation_col", "Select gene symbols column", choices = names(df)),
# Add buttons in a button group
div(class = "ui two buttons",
div(
id = "upload_check",
class = "ui animated fade button primary",
type = "button",
onclick = "Shiny.setInputValue('upload_check', Math.random(), {priority: 'event'})", # Use random value to ensure new trigger
div(class = "visible content", "Upload and Check Columns"),
div(class = "hidden content", icon("check"))
),
div(
id = "reset_columns",
class = "ui animated fade button negative",
type = "button",
onclick = "Shiny.setInputValue('reset_columns', true, {priority: 'event'})",
div(class = "visible content", "Reset Selection"),
div(class = "hidden content", icon("undo"))
)
)
)
})
#test
## Column upload observer ----
# 2. COLUMN CHECK OBSERVER
observeEvent(input$upload_check, {
req(input$upload_check)
req(input$pvalue_col, input$fold_col, input$annotation_col)
# Only proceed if state allows validation
if (column_select_module_state() %in% c("initial", "reseted")) {
log_event(log_messages,
sprintf("Starting column check at %s - State: %s",
format(Sys.time(), "%H:%M:%S.%OS3"),
column_select_module_state()),
"DEBUG")
results <- isolate({
diagnose_input_columns_and_remove_NA(
df = uploaded_df(),
pvalue_col = input$pvalue_col,
fold_col = input$fold_col,
annotation_col = input$annotation_col,
log_messages_rv = log_messages,
log_event = log_event
)
})
# Update data and state
uploaded_df(results$cleaned_data)
column_select_module_state("validated")
# Update UI
runjs('
document.getElementById("upload_check").classList.remove("primary");
document.getElementById("upload_check").classList.add("positive");
document.querySelector("#upload_check .visible.content").textContent = "Columns Checked ✓";
')
# Log results
log_event(log_messages,
sprintf("Columns selected and checked. Removed %d rows with NAs",
results$statistics$dropped_rows),
"SUCCESS from upload_check")
} else {
log_event(log_messages,
sprintf("Column check not needed - Columns already validated (current state: %s)",
column_select_module_state()),
"DEBUG")
}
}, ignoreInit = TRUE)
# 3. IMPROVED RESET COLUMNS OBSERVER
observeEvent(reset_input(), {
req(reset_input())
isolate({
current_state <- column_select_module_state()
# Log start of reset
log_event(log_messages,
sprintf("Column selection reset initiated from state: %s",
current_state),
"INFO from reset_columns")
# Update state
column_select_module_state("reseted")
# Reset UI elements
updateSelectInput(session, "pvalue_col", selected = character(0))
updateSelectInput(session, "fold_col", selected = character(0))
updateSelectInput(session, "annotation_col", selected = character(0))
runjs('
document.getElementById("upload_check").classList.remove("positive");
document.getElementById("upload_check").classList.add("primary");
document.querySelector("#upload_check .visible.content").textContent = "Upload and Check Columns";
')
# Log completion
log_event(log_messages,
sprintf("Column selections reset completed (from %s to reseted)",
current_state),
"SUCCESS from reset_columns")
})
}, ignoreInit = TRUE)
# 4. STATE MONITOR
observeEvent(column_select_module_state(), {
log_event(log_messages,
sprintf("State transition: %s at %s",
column_select_module_state(),
format(Sys.time(), "%H:%M:%S.%OS3")),
"DEBUG state_monitor")
}, ignoreInit = TRUE)
# 5. NEW DATA UPLOAD HANDLER
observeEvent(input$upload, {
column_select_module_state("initial")
reset_timer(NULL)
log_event(log_messages,
"State reset to initial due to new data upload",
"INFO")
}, ignoreInit = TRUE)
## Render DT data preview ----
output$dataset_summary <- renderDT({
log_event(log_messages, "Rendering dataset summary table", "INFO from output$dataset_summary")
table <- semantic_DT(
data.frame(uploaded_df(), check.names = FALSE), # Convert to data.frame if not already
options = list(
responsive = TRUE,
pageLength = 3,
dom = 'lftp',
lengthMenu = list(c(1, 3, 5, 10), c('1','3', '5', '10')),
rownames = FALSE,
scrollX = TRUE,
columnDefs = list(list(
targets = '_all', # Apply to all columns
className = 'dt-nowrap' # Add nowrap class
))
),
style = "semanticui",
class = "ui small compact table",
selection = 'none' # Disable row selection if needed
)
if (!is.null(table)) {
log_event(log_messages, "Dataset summary table created successfully", "INFO from output$dataset_summary")
# check the structure of the table
log_structure(log_messages, table, "The structure of the dataset summary table is:\n")
} else {
log_event(log_messages, "Failed to create dataset summary table", "ERROR from output$dataset_summary")
}
table
})
})
# REACTIVE UI FOR OPTIONAL GSEA ANALYSIS ----
output$gsea_controls_ui <- renderUI({
if (input$GSEA_acvited) {
div(class = "ui segment custom-segment",
div(class = "ui stackable grid",
div(class = "row",
# First column: Gene Set Selection with Multiple Radio Buttons
div(class = "eight wide column",
div(class = "field",
multiple_radio(
"gsea_ontology",
label = HTML("<strong>Ontology</strong>"),
choices = list(
"Cellular Component",
"Molecular Function",
"Biological Process"
),
choices_value = c(
"C", # Changed from "CC"
"F", # Changed from "MF"
"P" # Changed from "BP"
),
selected = "P"
)
)
),
# Second column: Action Button (Centered)
div(class = "eight wide column",
div(class = "ui container", style = "position: relative; min-height: 50px;",
# Button
actionButton(
inputId = "run_gsea",
label = HTML('<i class="play icon"></i> Run GSEA'),
class = "ui primary button"
),
)
)
)
)
)
}
})
## Reactive 4 tabset appearing if GSEA is activated and 3 tabset if not ----
# Add these to your server function
tab_list <- reactive({
# Define base tabs that are always present
base_tabs <- list(
list(
menu = "Static Volcano Plot and GO enrichment table",
id = "static_volcano",
content = div(
div(class = "ui two column grid",
# First column (50%) - Plot and Downloads
div(class = "column",
segment(
class = "basic",
plotOutput("volcano_plot", width = "100%", height = "600px")
),uiOutput("x_limits_ui"),
segment(
class = "basic",
h4(class = "ui header", "Download Plots"),
div(
class = "ui tiny fluid buttons",
downloadButton("download_plot1", "85x85mm (1 col)", class = "ui button"),
downloadButton("download_plot2", "114x114mm (1.5 col)", class = "ui button"),
downloadButton("download_plot3", "114x65mm (landscape)", class = "ui button")
),
div(
style = "margin-top: 10px;",
class = "ui tiny fluid buttons",
downloadButton("download_plot4", "174x174mm (square)", class = "ui button"),
downloadButton("download_plot5", "174x98mm (landscape)", class = "ui button")
)
)
),
# Second column (50%) - GO Table
div(class = "column",
segment(
class = "basic",
h4(class = "ui header", "Download GO Enrichment Table"),
div(
class = "ui tiny fluid buttons",
downloadButton("download_go_enrichment", "Download GO enrichment table", class = "ui button")
),
gt_output("go_enrichment_gt")
)
)
)
)
),
list(
menu = "Interactive Volcano Plot",
id = "interactive_volcano",
content = div(
plotlyOutput("volcano_plotly", width = "800px", height = "740px")
)
),
list(
menu = "GO Category Details",
id = "go_category",
content = div(
segment(
class = "basic",
h4(class = "ui header", "Download GO Gene List Table"),
div(
class = "ui tiny fluid buttons",
downloadButton("download_go_gene_list", "Download GO gene lists", class = "ui button")
),
gt_output("go_gene_list_gt")
)
)
)
)
## Add GSEA tab conditionally ----
if (isTRUE(input$GSEA_acvited)) {
gsea_tab <- list(
menu = "GSEA Results",
id = "gsea_results_tab",
content = div(
segment(
class = "basic",
h4(class = "ui header", "GSEA Analysis Results"),
div(
class = "ui tiny fluid buttons",
downloadButton("reg_gene_list", "Download regulated genes lists", class = "ui button"),
downloadButton("download_full_gsea", "Full GSEA Results" , class = "ui button"),
downloadButton("download_top_gsea", "Top 10 significant GSEA results", class = "ui button"),
downloadButton("download_top10_gsea", "Top 10 GSEA Results(inc. nonsig)", class = "ui button")
),
div(class = "ui grid stackable mobile reversed",
# First column (9/16)
div(class = "nine wide computer wide tablet sixteen wide mobile column",
div(class = "ui segment basic",
div(class = "segment-header",
h4(class = "ui header", "GSEA Enrichment Plot"),
downloadButton("download_gsea_plot", "Download GSEA Plot", class = "ui tiny button")
),
# Responsive controls aligned together in a single row using a semantic stackable grid.
div(
class = "ui stackable grid",
div(
class = "row",
# Column for radio buttons (Which category to show)
div(
class = "four wide computer four wide tablet sixteen wide mobile column",
multiple_radio(
input_id = "plot_category",
label = "Which category to show:",
choices = c(
"bidirectional" = "bidirectional",
"upregulated" = "up",
"downregulated" = "down"
),
selected = "up"
)
),
# Column for toggle: Hide non-significant results
div(
class = "three wide computer three wide tablet sixteen wide mobile column",
div(style = "margin-top: 22px;",