-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.R
More file actions
1821 lines (1629 loc) · 63.6 KB
/
app.R
File metadata and controls
1821 lines (1629 loc) · 63.6 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
library(shiny)
library(bslib)
library(shinyjs)
library(yaml)
library(SLIDE)
library(DT)
library(plotly)
library(rmarkdown)
library(dplyr)
ui <- page_navbar(
theme = bs_theme(version = 5, bootswatch = "minty"),
useShinyjs(),
title = tags$a(
"SLIDE Analysis",
href = "https://www.nature.com/articles/s41592-024-02175-z#Abs1",
target = "_blank",
style = "color: inherit; text-decoration: none; hover: {text-decoration: underline;}"
),
header = tags$head(
tags$style(HTML("
/* Remove toggle switch styles */
/* Path input field styling */
.path-input input {
width: 100%;
font-family: monospace;
}
/* Input group styling */
.input-group {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 8px;
}
.input-group .form-control {
flex: 1;
}
.input-group .btn-upload {
background-color: #4CAF50;
color: white;
border: none;
padding: 6px 12px;
border-radius: 4px;
cursor: pointer;
transition: all 0.3s ease;
}
.input-group .btn-upload:hover {
background-color: #45a049;
transform: translateY(-2px);
}
.input-group .btn-upload i {
margin-right: 4px;
}
/* Validation icons */
.validation-icon {
display: inline-block;
margin-left: 4px;
vertical-align: middle;
}
.validation-icon.valid {
color: #28a745;
}
.validation-icon.invalid {
color: #dc3545;
}
/* Path input container */
.path-input-container {
position: relative;
width: 100%;
}
/* Label with validation icon */
.label-with-validation {
display: flex;
align-items: center;
gap: 4px;
margin-bottom: 4px;
}
/* Shape info text */
.shape-info {
margin-top: 2px;
margin-bottom: 8px;
}
/* Adjust spacing for file inputs */
.shiny-input-container {
margin-bottom: 8px;
}
/* Path input with truncation */
.path-input-truncate {
position: relative;
width: 100%;
}
.path-input-truncate input {
width: 100%;
font-family: monospace;
}
.path-input-truncate.overflow::after {
content: attr(data-path);
visibility: visible;
position: absolute;
top: 0;
left: 0;
right: 0;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
direction: rtl;
padding: 6px 12px;
pointer-events: none;
background: transparent;
}
.path-input-truncate.overflow input:focus,
.path-input-truncate.overflow input:hover {
position: relative;
z-index: 1;
}
/* Wrapped path input styling */
.path-input-wrap input {
width: 100%;
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
}
.path-input-wrap input:focus,
.path-input-wrap input:hover {
white-space: pre-wrap;
word-wrap: break-word;
height: auto;
}
/* Button hover animations */
.btn {
transition: all 0.3s ease !important;
}
.btn:hover {
transform: translateY(-2px);
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
/* Save Configuration button */
.btn-save-config {
background-color: #607D8B !important;
border: none !important;
color: white !important;
}
.btn-save-config:hover {
background-color: #546E7A !important;
}
/* Run SLIDE button */
.btn-success:hover {
filter: brightness(0.85);
}
/* Run SLIDEcv button */
.btn-slidecv {
background-color: #619CFF !important;
border: none !important;
color: white !important;
opacity: 0.5;
cursor: not-allowed;
}
.btn-slidecv.enabled {
opacity: 1;
cursor: pointer;
}
.btn-slidecv.enabled:hover {
filter: brightness(0.85);
}
/* Load Results button */
.btn-info:hover {
filter: brightness(0.85);
}
/* Disabled button styles */
.btn-disabled {
opacity: 0.5 !important;
cursor: not-allowed !important;
pointer-events: none !important;
}
/* Progress bar animation */
@keyframes progress-bar-stripes {
from { background-position: 1rem 0; }
to { background-position: 0 0; }
}
.progress-bar {
background-image: linear-gradient(45deg,
rgba(255, 255, 255, 0.15) 25%,
transparent 25%,
transparent 50%,
rgba(255, 255, 255, 0.15) 50%,
rgba(255, 255, 255, 0.15) 75%,
transparent 75%,
transparent);
background-size: 1rem 1rem;
}
.progress.active .progress-bar {
animation: progress-bar-stripes 1s linear infinite;
}
/* Add active class to progress bar container when running */
.shiny-progress.active .progress {
height: 0.5rem;
background-color: #e9ecef;
border-radius: 0.25rem;
margin: 0.5rem 0;
}
.shiny-progress.active .progress .progress-bar {
height: 100%;
border-radius: 0.25rem;
transition: width 0.6s ease;
}
/* Submit job button */
.btn-submit-job {
background-color: #FFA500 !important;
border: none !important;
color: white !important;
opacity: 0.5;
cursor: not-allowed;
}
.btn-submit-job.enabled {
opacity: 1;
cursor: pointer;
}
.btn-submit-job.enabled:hover {
filter: brightness(0.85);
}
")),
tags$script(HTML("
$(document).ready(function() {
function getFileName(path) {
if (!path) return '';
const parts = path.split('/');
return parts[parts.length - 1] || path;
}
// Add functions to manage button states
window.enableButton = function(buttonId) {
$('#' + buttonId).removeClass('btn-disabled');
}
window.disableButton = function(buttonId) {
$('#' + buttonId).addClass('btn-disabled');
}
// Add functions to manage progress bar animation
window.startProgressAnimation = function() {
$('.shiny-progress').addClass('active');
$('.progress').addClass('active');
}
window.stopProgressAnimation = function() {
$('.shiny-progress').removeClass('active');
$('.progress').removeClass('active');
}
// Observe Shiny progress events
$(document).on('shiny:progressing', function(event) {
startProgressAnimation();
});
$(document).on('shiny:idle', function(event) {
stopProgressAnimation();
});
window.disableAllRunButtons = function() {
$('#run_slide, #run_slidecv').addClass('btn-disabled');
}
window.enableAllRunButtons = function() {
$('#run_slide, #run_slidecv').removeClass('btn-disabled');
}
function updatePathDisplay() {
$('.path-input input, .path-input-truncate input').each(function() {
const $input = $(this);
const $container = $input.parent();
const fullPath = $input.val();
if (this.scrollWidth > this.clientWidth) {
$container.addClass('overflow');
if (!$input.is(':focus')) {
const fileName = getFileName(fullPath);
$input.attr('data-full-path', fullPath);
$input.val(fileName);
}
} else {
$container.removeClass('overflow');
}
// Store full path for hover
$input.attr('title', fullPath);
});
}
// Update on input change
$(document).on('input', '.path-input input, .path-input-truncate input', function() {
const $input = $(this);
$input.attr('data-full-path', $input.val());
setTimeout(updatePathDisplay, 0);
});
// Show full path on focus
$(document).on('focus', '.path-input input, .path-input-truncate input', function() {
const $input = $(this);
const fullPath = $input.attr('data-full-path');
if (fullPath) {
$input.val(fullPath);
}
});
// Show filename on blur
$(document).on('blur', '.path-input input, .path-input-truncate input', function() {
const $input = $(this);
const fullPath = $input.attr('data-full-path');
if (fullPath && this.scrollWidth > this.clientWidth) {
$input.val(getFileName(fullPath));
}
});
// Initial check
setTimeout(updatePathDisplay, 100);
// Update on window resize
$(window).on('resize', updatePathDisplay);
});
"))
),
nav_panel("", icon = icon("home"),
layout_sidebar(
sidebar = sidebar(
width = 350,
div(class = "input-group",
div(style = "flex: 1;",
tags$div(class = "path-input-truncate",
div(class = "path-input-container",
div(class = "label-with-validation",
"X data file path (CSV)",
tags$i(id = "x_path_icon", class = "fas validation-icon")
),
textInput("x_path", NULL, value = "")
)
)
),
fileInput("x_file", NULL, accept = ".csv",
buttonLabel = list(icon("upload"), "Upload"),
width = "auto"
)
),
div(class = "shape-info",
uiOutput("x_shape_info")
),
div(class = "input-group",
div(style = "flex: 1;",
tags$div(class = "path-input-truncate",
div(class = "path-input-container",
div(class = "label-with-validation",
"Y data file path (CSV)",
tags$i(id = "y_path_icon", class = "fas validation-icon")
),
textInput("y_path", NULL, value = "")
)
)
),
fileInput("y_file", NULL, accept = ".csv",
buttonLabel = list(icon("upload"), "Upload"),
width = "auto"
)
),
tags$div(class = "path-input-truncate",
textInput("out_path", "Output Directory", value = "slide_results")
),
div(
style = "margin-top: -15px; margin-bottom: 15px;",
checkboxInput("override_output", "Override existing output directory", value = FALSE)
),
hr(),
accordion(
open=FALSE,
accordion_panel(
"Parameters",
open = FALSE,
multiple = FALSE,
div(
"Delta values (comma-separated)",
tags$small(class = "text-muted d-block mb-2", "Controls the number of latent factors. Higher values = fewer factors. Default: 0.01,0.1"),
textInput("delta", NULL, value = "0.01")
),
div(
"Lambda values (comma-separated)",
tags$small(class = "text-muted d-block mb-2", "Controls latent factor sparsity. Higher values = fewer features per factor. Default: 0.5,1"),
textInput("lambda", NULL, value = "0.5")
),
div(
"Spec",
tags$small(class = "text-muted d-block mb-2", "Controls number of significant latent factors. Aim for 5-12 LFs. Default: 0.1"),
numericInput("spec", NULL, value = 0.1, min = 0, max = 1, step = 0.01)
),
div(
"Threshold FDR",
tags$small(class = "text-muted d-block mb-2", "False discovery rate threshold for feature selection. Default: 0.2"),
numericInput("thresh_fdr", NULL, value = 0.2, min = 0, max = 1, step = 0.01)
),
div(
"Knockoff FDR",
tags$small(class = "text-muted d-block mb-2", "False discovery rate threshold for knockoff procedure. Default: 0.1"),
numericInput("fdr", NULL, value = 0.1, min = 0, max = 1, step = 0.01)
),
div(
"Y Factor",
tags$small(class = "text-muted d-block mb-2", "Set TRUE if Y is binary, FALSE otherwise"),
checkboxInput("y_factor", NULL, value = TRUE)
),
div(
"Y Levels (comma-separated)",
tags$small(class = "text-muted d-block mb-2", "For binary Y only: specify level order (e.g. 0,1). Leave empty for continuous/ordinal Y"),
textInput("y_levels", NULL, value = "0,1")
),
div(
"Evaluation Type",
tags$small(class = "text-muted d-block mb-2", "Use 'correlation' for continuous Y, 'auc' for binary Y"),
selectInput("eval_type", NULL, choices = c("auc", "correlation"))
),
div(
"SLIDE Iterations",
tags$small(class = "text-muted d-block mb-2", "Higher iterations = more stable performance. Default: 1000"),
numericInput("SLIDE_iter", NULL, value = 1000, min = 100)
),
div(
"Top Features",
tags$small(class = "text-muted d-block mb-2", "Number of top features to plot from each latent factor"),
numericInput("SLIDE_top_feats", NULL, value = 10, min = 1)
),
div(
"Sample CV Iterations",
tags$small(class = "text-muted d-block mb-2", "Number of iterations for cross-validation approximation. Default: 500"),
numericInput("sampleCV_iter", NULL, value = 500, min = 100)
),
div(
"Sample CV K",
tags$small(class = "text-muted d-block mb-2", "Number of folds for cross-validation. Default: 4"),
numericInput("sampleCV_K", NULL, value = 4, min = 2)
),
div(
"Do Interactions",
tags$small(class = "text-muted d-block mb-2", "Set FALSE to disable interacting latent factors"),
checkboxInput("do_interacts", NULL, value = TRUE)
),
div(
class = "d-flex justify-content-end mt-3",
downloadButton("download_yaml", "Download YAML", class = "btn-default")
)
)
),
hr(),
div(
style = "margin-top: 10px;",
actionButton("run_slide", "Run SLIDE", class = "btn-success w-100 btn-disabled")
),
div(
style = "margin-top: 10px;",
actionButton("run_slidecv", "Run SLIDEcv",
class = "btn-slidecv w-100"
)
),
div(
style = "margin-top: 10px;",
actionButton("submit_job", "Submit SLIDEcv Job",
class = "btn-submit-job w-100"
)
),
tags$div(id = "status_message", class = "mt-2 text-muted small"),
fileInput("config_upload", "Or Upload YAML Config", accept = ".yaml")
),
# Replace the existing results section with the dynamic one
uiOutput("results_section")
)
)
)
server <- function(input, output, session) {
# Initialize all reactive values at the start of server
config <- reactiveVal(NULL)
results <- reactiveValues(
summary_table = NULL,
current_output_path = NULL
)
# Add reactive values for directory navigation
current_dir <- reactiveVal(NULL)
dir_contents <- reactiveVal(NULL)
# Add reactive value to track analysis state
analysis_running <- reactiveVal(FALSE)
# Add reactive value to track if analysis should be canceled
should_cancel <- reactiveVal(FALSE)
# Add reactive value to store the current R process
current_process <- reactiveVal(NULL)
# Add reactive values for file validation
x_file_valid <- reactiveVal(FALSE)
y_file_valid <- reactiveVal(FALSE)
# Create a reactive value to store the temp directory path
temp_dir <- reactiveVal(NULL)
# Add reactive value to store script details
script_details <- reactiveValues(
content = NULL,
path = NULL,
name = NULL
)
# Function to clean up old temp files
cleanup_temp_files <- function() {
# Clean up files older than 1 hour
temp_base <- "www/temp"
if (dir.exists(temp_base)) {
files <- list.files(temp_base, full.names = TRUE)
for (f in files) {
if (difftime(Sys.time(), file.info(f)$mtime, units="hours") > 1) {
unlink(f)
}
}
}
}
# Create temp directory if it doesn't exist
observe({
if (is.null(temp_dir())) {
temp_base <- "www/temp"
if (!dir.exists(temp_base)) {
dir.create(temp_base, recursive = TRUE, showWarnings = FALSE)
}
temp_dir(temp_base)
# Clean up old temp files
cleanup_temp_files()
}
})
# Initialize JavaScript functions
js <- list(
enableButton = function(buttonId) {
shinyjs::removeClass(buttonId, "btn-disabled")
},
disableButton = function(buttonId) {
shinyjs::addClass(buttonId, "btn-disabled")
},
disableAllRunButtons = function() {
shinyjs::addClass("run_slide", "btn-disabled")
shinyjs::addClass("run_slidecv", "btn-disabled")
},
enableAllRunButtons = function() {
shinyjs::removeClass("run_slide", "btn-disabled")
shinyjs::removeClass("run_slidecv", "btn-disabled")
}
)
# Observer to update button states based on file validation and analysis state
observe({
if (analysis_running()) {
updateActionButton(session, "run_slide", label = "Cancel")
js$disableAllRunButtons()
} else {
updateActionButton(session, "run_slide", label = "Run SLIDE")
if (x_file_valid() && y_file_valid()) {
js$enableButton("run_slide")
} else {
js$disableButton("run_slide")
}
}
})
# Function to clean up after analysis stops
cleanup_analysis <- function() {
analysis_running(FALSE)
should_cancel(FALSE)
current_process(NULL)
# Re-enable buttons based on validation state
if (x_file_valid() && y_file_valid()) {
js$enableButton("run_slide")
} else {
js$disableButton("run_slide")
}
# Enable SLIDEcv button if results are available
if (!is.null(results$summary_table) && !is.null(input$summary_table_rows_selected)) {
js$enableButton("run_slidecv")
} else {
js$disableButton("run_slidecv")
}
}
output$x_shape_info <- renderUI({
input_type <- if (isTRUE(input$input_type)) "upload" else "path"
if (input_type == "upload") {
req(input$x_file)
file_path <- input$x_file$datapath
} else {
req(input$x_path)
if (!file.exists(input$x_path)) {
return(tags$small(
class = "text-danger d-block mb-2",
"File not found at specified path"
))
}
file_path <- input$x_path
}
tryCatch({
x <- as.matrix(utils::read.csv(file_path, row.names = 1, check.names = F))
tags$small(
class = "text-muted d-block mb-2",
sprintf("Shape: %d samples × %d features", nrow(x), ncol(x))
)
}, error = function(e) {
tags$small(
class = "text-danger d-block mb-2",
"Error reading file. Please ensure it has row names and column names."
)
})
})
create_yaml_config <- reactive({
input_type <- if (isTRUE(input$input_type)) "upload" else "path"
# Get X file path
if (input_type == "upload") {
req(input$x_file)
x_path <- normalizePath(input$x_file$datapath, winslash = "/", mustWork = TRUE)
} else {
req(input$x_path)
if (!file.exists(input$x_path)) {
showNotification("X data file not found at specified path", type = "error")
return(NULL)
}
x_path <- normalizePath(input$x_path, winslash = "/", mustWork = TRUE)
}
# Get Y file path
if (input_type == "upload") {
req(input$y_file)
y_path <- normalizePath(input$y_file$datapath, winslash = "/", mustWork = TRUE)
} else {
req(input$y_path)
if (!file.exists(input$y_path)) {
showNotification("Y data file not found at specified path", type = "error")
return(NULL)
}
y_path <- normalizePath(input$y_path, winslash = "/", mustWork = TRUE)
}
config_list <- list(
x_path = x_path,
y_path = y_path,
out_path = input$out_path,
delta = as.numeric(strsplit(input$delta, ",")[[1]]),
lambda = as.numeric(strsplit(input$lambda, ",")[[1]]),
spec = input$spec,
thresh_fdr = input$thresh_fdr,
fdr = input$fdr,
y_factor = input$y_factor,
y_levels = as.numeric(strsplit(input$y_levels, ",")[[1]]),
eval_type = input$eval_type,
SLIDE_iter = input$SLIDE_iter,
SLIDE_top_feats = input$SLIDE_top_feats,
sampleCV_iter = input$sampleCV_iter,
sampleCV_K = input$sampleCV_K,
do_interacts = input$do_interacts
)
# Create output directory if it doesn't exist and normalize path
if (!dir.exists(config_list$out_path)) {
dir.create(config_list$out_path, recursive = TRUE, showWarnings = FALSE)
} else if (isolate(input$override_output)) {
# Delete directory and recreate if override is checked
unlink(config_list$out_path, recursive = TRUE)
dir.create(config_list$out_path, recursive = TRUE, showWarnings = FALSE)
}
config_list$out_path <- normalizePath(config_list$out_path, winslash = "/", mustWork = TRUE)
return(config_list)
})
observeEvent(input$config_upload, {
req(input$config_upload)
tryCatch({
uploaded_config <- yaml::read_yaml(input$config_upload$datapath)
if (!file.exists(uploaded_config$x_path)) {
stop("X data file not found: ", uploaded_config$x_path)
}
if (!file.exists(uploaded_config$y_path)) {
stop("Y data file not found: ", uploaded_config$y_path)
}
uploaded_config$x_path <- normalizePath(uploaded_config$x_path, winslash = "/", mustWork = TRUE)
uploaded_config$y_path <- normalizePath(uploaded_config$y_path, winslash = "/", mustWork = TRUE)
if (!dir.exists(uploaded_config$out_path)) {
dir.create(uploaded_config$out_path, recursive = TRUE, showWarnings = FALSE)
}
uploaded_config$out_path <- normalizePath(uploaded_config$out_path, winslash = "/", mustWork = TRUE)
config(uploaded_config)
showNotification(sprintf("Loaded configuration from: %s", input$config_upload$name), type = "message")
}, error = function(e) {
showNotification(sprintf("Error loading configuration: %s", e$message), type = "error")
})
})
observeEvent(input$save_yaml, {
tryCatch({
yaml_config <- isolate(create_yaml_config())
yaml_file <- file.path(yaml_config$out_path, "yaml_params.yaml")
dir.create(dirname(yaml_file), showWarnings = FALSE, recursive = TRUE)
yaml::write_yaml(yaml_config, yaml_file)
config(yaml_config)
showNotification("Configuration saved successfully!", type = "message")
}, error = function(e) {
showNotification(sprintf("Error saving configuration: %s", e$message), type = "error")
})
})
output$current_config <- renderPrint({
req(config())
yaml::as.yaml(config())
})
output$download_yaml <- downloadHandler(
filename = function() {
"yaml_params.yaml"
},
content = function(file) {
tryCatch({
yaml_config <- isolate(create_yaml_config())
yaml::write_yaml(yaml_config, file)
}, error = function(e) {
showNotification(sprintf("Error downloading configuration: %s", e$message), type = "error")
})
}
)
observeEvent(input$run_slide, {
if (analysis_running()) {
# If analysis is running, cancel it
should_cancel(TRUE)
# Get the current process
proc <- current_process()
if (!is.null(proc)) {
# Try to terminate the process gracefully
tools::pskill(proc$get_pid(), signal = 15) # SIGTERM
Sys.sleep(0.5) # Give it a moment to terminate
# Force kill if still running
if (proc$is_alive()) {
tools::pskill(proc$get_pid(), signal = 9) # SIGKILL
}
}
html("status_message", "Analysis canceled.")
cleanup_analysis()
} else {
# If analysis is not running, start new analysis
should_cancel(FALSE)
analysis_running(TRUE)
js$disableAllRunButtons() # Disable buttons while analysis is running
# First save the configuration
tryCatch({
yaml_config <- isolate(create_yaml_config())
if (is.null(yaml_config)) {
showNotification("Please check your input parameters", type = "error")
cleanup_analysis()
return()
}
yaml_file <- file.path(yaml_config$out_path, "yaml_params.yaml")
dir.create(dirname(yaml_file), showWarnings = FALSE, recursive = TRUE)
yaml::write_yaml(yaml_config, yaml_file)
config(yaml_config)
shinyjs::addClass(selector = "#status_message", class = "status-running")
html("status_message", "Analysis in progress...")
withProgress(message = 'Running SLIDE analysis...', value = 0, {
tryCatch({
# Create a custom optimizeSLIDE function with progress updates
optimizeSLIDE_with_progress <- function(input_params, sink_file = F) {
# Initial setup progress
if (dir.exists(input_params$out_path)){
if (input$override_output) {
updateProgressText("Overriding existing directory...")
unlink(input_params$out_path, recursive = TRUE)
dir.create(file.path(input_params$out_path), showWarnings = F, recursive = T)
} else {
updateProgressText("Populating outputs to existing directory...")
}
} else{
updateProgressText("Creating output directory...")
dir.create(file.path(input_params$out_path), showWarnings = F, recursive = T)
}
# Check for early cancellation
if (should_cancel()) {
cleanup_analysis()
return(NULL)
}
# Load and process data
incProgress(0.2, detail = "Loading data matrices...")
x <- as.matrix(utils::read.csv(input_params$x_path, row.names = 1, check.names = F))
colnames(x) = stringr::str_replace_all(colnames(x), pattern = " ", replacement = "_")
y <- as.matrix(utils::read.csv(input_params$y_path, row.names = 1))
x_std <- scale(x, T, T)
# Initialize parameters
delta = if(is.null(input_params$delta)) c(0.01, 0.1) else input_params$delta
lambda = if(is.null(input_params$lambda)) c(0.5, 1.0) else input_params$lambda
alpha_level = if(is.null(input_params$alpha)) 0.05 else input_params$alpha
thresh_fdr = if(is.null(input_params$thresh_fdr)) 0.2 else input_params$thresh_fdr
fdr = if(is.null(input_params$fdr)) 0.1 else input_params$fdr
spec = if(is.null(input_params$spec)) 0.1 else input_params$spec
do_interacts = if(is.null(input_params$do_interacts)) TRUE else input_params$do_interacts
SLIDE_iter = if(is.null(input_params$SLIDE_iter)) 1000 else input_params$SLIDE_iter
SLIDE_top_feats = if(is.null(input_params$SLIDE_top_feats)) 10 else input_params$SLIDE_top_feats
sampleCV_iter = if(is.null(input_params$sampleCV_iter)) 500 else input_params$sampleCV_iter
# Initialize summary table
total_iterations <- length(delta) * length(lambda)
current_iteration <- 0
summary_table <- as.data.frame(matrix(NA, nrow = total_iterations, ncol = 10))
colnames(summary_table) <- c('delta', 'lambda', 'f_size', 'Num_of_LFs', 'Num_of_Sig_LFs', 'Num_of_Interactors', 'sampleCV_Performance', 'spec', 'fdr', 'thresh_fdr')
for (d in delta) {
for (l in lambda) {
# Check for cancellation at each iteration
if (should_cancel()) {
cleanup_analysis()
return(NULL)
}
current_iteration <- current_iteration + 1
progress_pct <- 0.2 + (0.8 * current_iteration / total_iterations)
incProgress(progress_pct / total_iterations,
detail = sprintf("🏃♂️️ delta=%.3f, lambda=%.3f (%d/%d)",
d, l, current_iteration, total_iterations))
loop_outpath = paste0(input_params$out_path, '/', d, '_', l, '_', 'out/')
dir.create(file.path(loop_outpath), showWarnings = F, recursive = T)
# Save run-specific YAML for this iteration
run_yaml <- input_params
run_yaml$delta <- d
run_yaml$lambda <- l
run_yaml$out_path <- loop_outpath
yaml::write_yaml(run_yaml, paste0(loop_outpath, "yaml_params.yaml"))
updateProgressText(sprintf("Getting latent factors for delta=%.3f, lambda=%.3f...", d, l))
if (input_params$y_factor) {
y_temp <- SLIDE::toCont(y, input_params$y_levels)
saveRDS(y_temp, file = paste0(input_params$out_path, "/binary_y_mapping.rds"))
orig_y <- as.matrix(y_temp$cat_y)
y <- as.matrix(y_temp$cont_y)
row.names(y) <- row.names(y_temp$cat_y)
}
all_latent_factors <- SLIDE::getLatentFactors(
x = x,
x_std = x_std,
y = y,
sigma = NULL,
delta = d,
lambda = l,
rep_cv = input_params$rep_cv,
alpha_level = alpha_level,
thresh_fdr = thresh_fdr,
out_path = loop_outpath
)
saveRDS(all_latent_factors, paste0(loop_outpath, 'AllLatentFactors.rds'))
updateProgressText("Calculating Z matrix...")
z_matrix <- tryCatch({
SLIDE::calcZMatrix(x_std, all_latent_factors, x_path = NULL,
lf_path = NULL, loop_outpath)
}, error = function(e) {
updateProgressText("Error calculating Z matrix, skipping...")
return(NULL)
})
if (is.null(z_matrix)) {
next
}
updateProgressText("Running SLIDE analysis...")
SLIDE_res <- tryCatch({
SLIDE::runSLIDE(
y,
y_path = NULL,
z_path = NULL, z_matrix,
all_latent_factors,
lf_path = NULL,
niter = SLIDE_iter,
spec = spec,
fdr = fdr,
do_interacts = do_interacts
)
}, error = function(e) {
updateProgressText("Error running SLIDE analysis, skipping...")
return(NULL)
})
if (is.null(SLIDE_res)) {
next
}
saveRDS(SLIDE_res, paste0(loop_outpath, 'SLIDE_LFs.rds'))
if(length(SLIDE_res$SLIDE_res$marginal_vars) != 0) {
updateProgressText("Processing top features...")
SLIDE_res <- SLIDE::getTopFeatures(x, y, all_latent_factors, loop_outpath,
SLIDE_res, num_top_feats = SLIDE_top_feats,
condition = input_params$eval_type)
saveRDS(SLIDE_res, paste0(loop_outpath, 'SLIDE_LFs.rds'))
SLIDE::plotSigGenes(SLIDE_res, plot_interaction = do_interacts, out_path = loop_outpath)
if(length(SLIDE_res$SLIDE_res$marginal_vars) != 0) {
updateProgressText("Calculating control performance...")
performance = SLIDE::sampleCV(y, z_matrix, SLIDE_res,
sampleCV_K = input_params$sampleCV_K,
condition = input_params$eval_type,
sampleCV_iter = sampleCV_iter,
logistic = FALSE,
out_path = loop_outpath)
SLIDE::calcControlPerformance(z_matrix = z_matrix, y, do_interacts,
SLIDE_res, condition = input_params$eval_type,
loop_outpath)
updateProgressText("Calculating sample CV performance...")
performance = SLIDE::sampleCV(y, z_matrix, SLIDE_res,
sampleCV_K = input_params$sampleCV_K,
condition = input_params$eval_type,
sampleCV_iter = sampleCV_iter,
logistic = FALSE,
out_path = loop_outpath)
if (do_interacts == TRUE) {
interactors = c(SLIDE_res$interaction$p1, SLIDE_res$interaction$p2)
interactors = interactors[!(interactors %in% SLIDE_res$marginal_vals)]
interactors = unique(interactors)
loop_summary = c(d, l, SLIDE_res$SLIDE_param['f_size'],
all_latent_factors$K, length(SLIDE_res$marginal_vals),
length(interactors), performance, spec, fdr, thresh_fdr)
} else {
loop_summary = c(d, l, SLIDE_res$SLIDE_param['f_size'],
all_latent_factors$K, length(SLIDE_res$marginal_vals),
'NA', performance, spec, fdr, thresh_fdr)
}
} else {
loop_summary = c(d, l, SLIDE_res$SLIDE_param['f_size'],
all_latent_factors$K, "NA", "NA", "NA", spec, fdr, thresh_fdr)
}
} else {
loop_summary = c(d, l, SLIDE_res$SLIDE_param['f_size'],
all_latent_factors$K, "NA", "NA", "NA", spec, fdr, thresh_fdr)