-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain_server.R
More file actions
1799 lines (1647 loc) · 66.1 KB
/
main_server.R
File metadata and controls
1799 lines (1647 loc) · 66.1 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
# Copyright (c) 2016-2020, MetaMorph Software
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# Script: app.R
#
# Author: Timothy Thomas [aut, cre],
# Will Knight [aut],
# Joseph Coombe [aut]
#
# Maintainer: Joseph Coombe <jcoombe@metamorphsoftware.com>
#
# Description: OpenMETA Visualizer
#
# This framework allows for the assembly of selected tabs into a single
# Visualizer session. This allows for the tabs to interact and share
# selection sets, classification variables, and filter settings. It
# also manages the persistence of the design data generated during
# exploration.
#
# URL: https://openmeta.metamorphsoftware.com/
library(shiny)
library(shinyjs)
library(shinyBS)
library(jsonlite)
library(topsis)
library(colourpicker)
source("utils.R")
# Defined Constants ----------------------------------------------------------
ABBREVIATION_LENGTH <- 25
SAVE_DIG_INPUT_CSV <- TRUE
FILTER_WIDTH_IN_COLUMNS <- 2
# Resolve Dataset Configuration ----------------------------------------------
pet_config_present <- FALSE
design_tree_present <- FALSE
saved_inputs <- NULL
filter_divs <- list()
visualizer_config <- NULL
design_tree <- NULL
first_raw_poll <- TRUE
dig_input_csv <- Sys.getenv('DIG_INPUT_CSV')
dig_dataset_config <- Sys.getenv('DIG_DATASET_CONFIG')
if (dig_dataset_config == "") {
if(dig_input_csv == "") {
# Setup one of the test datasets if no input dataset
config_filename=file.path('datasets',
'WindTurbineForOptimization',
'visualizer_config.json',
fsep = "\\\\")
# config_filename=file.path('datasets',
# 'boxpacking',
# 'visualizer_config.json',
# fsep = "\\\\")
} else {
# Visualizer legacy launch format
csv_dir <- dirname(dig_input_csv)
config_filename <- file.path(csv_dir,
sub("\\.csv$",
"_viz_config.json",
tolower(basename(dig_input_csv))),
fsep = "\\\\")
}
} else {
config_filename <- gsub("\\\\", "/", dig_dataset_config)
}
if(file.exists(config_filename)) {
visualizer_config <- fromJSON(file(config_filename, encoding="UTF-8"), simplifyDataFrame=FALSE)
} else {
visualizer_config <- list()
visualizer_config$raw_data <- basename(dig_input_csv)
visualizer_config$pet_config <- "pet_config.json"
visualizer_config$tabs <- c("Explore.R",
"DataTable.R",
"Histogram.R",
"UncertaintyQuantification.R")
}
tab_requests <- visualizer_config$tabs
saved_inputs <- visualizer_config$inputs
launch_dir <- dirname(config_filename)
pet_config_filename <- visualizer_config$pet_config
if (!is.null(pet_config_filename) && pet_config_filename != "") {
pet_config_filename <- file.path(launch_dir, pet_config_filename)
if (file.exists(pet_config_filename)) {
pet_config_present <- TRUE
}
}
design_tree_filename <- file.path(launch_dir, "design_tree.json")
if (file.exists(design_tree_filename)) {
design_tree_present <- TRUE
}
user_default_input_file_directory <- file.path(Sys.getenv("APPDATA"), "\\OpenMETA\\Visualizer")
if (!dir.exists(user_default_input_file_directory)) {
dir.create(user_default_input_file_directory, showWarnings=TRUE, recursive=TRUE)
}
user_default_input_filename <- file.path(user_default_input_file_directory, "\\default_input.json")
if (file.exists(user_default_input_filename)) {
user_default_inputs <- fromJSON(file(user_default_input_filename, encoding="UTF-8"), simplifyDataFrame=FALSE)
} else {
user_default_inputs <- list()
}
default_input_template_filename <- file.path("./default_input.template.json")
default_inputs <- fromJSON(file(default_input_template_filename, encoding="UTF-8"), simplifyDataFrame=FALSE)
merge_lists <- function(default, ..., KEEP.FIRST.TYPE=TRUE) {
lists_to_merge <- list(...)
result <- default
for (list_to_merge in lists_to_merge) {
for (name in names(list_to_merge)) {
if (is.list(list_to_merge[[name]]) && (is.list(result[[name]]) || is.null(result[[name]]))) {
result[[name]] <- merge_lists(result[[name]], list_to_merge[[name]])
} else if (typeof(list_to_merge[[name]]) != typeof(result[[name]]) && !all(c(typeof(list_to_merge[[name]]), typeof(result[[name]])) %in% c("integer", "double"))) {
if (!KEEP.FIRST.TYPE) {
result[[name]] <- list_to_merge[[names]]
}
} else {
result[[name]][1:length(list_to_merge[[name]])] <- list_to_merge[[name]]
result[[name]] <- result[[name]][-(1+length(list_to_merge[[name]])):-(1+length(result[[name]]))]
}
}
}
result
}
default_inputs <- merge_lists(default_inputs, user_default_inputs)
if (!identical(default_inputs, user_default_inputs)) {
tryCatch(
write(toJSON(default_inputs, pretty=TRUE, auto_unbox=TRUE), user_default_input_filename),
error=function(e) { print(e) }
)
}
# Saved Input Functions ------------------------------------------------------
si <- function(id, default) {
# Retrieves saved input state from the previous session for a UI element
# with a given id. This function will most often be called in a 'ui(id)'
# definition when creating a UI input element.
#
# This function deletes the saved value after it is accessed, so each tab
# should take care to persist the value through any regeneration of UI
# elements.
#
# Args:
# id: the 'id' to look up in the saved_inputs list
# default: the value to return if the 'id' isn't found
if(!is.null(saved_inputs) && !is.null(saved_inputs[[id]])) {
value <- saved_inputs[[id]]
saved_inputs[[id]] <<- NULL
value
} else {
default
}
}
si_read <- function(id) {
# Retrieves saved input state from the previous session for a UI element
# with a given id but does not consider it 'applied.'
saved_inputs[[id]]
}
si_clear <- function(id) {
# Clears the saved input state from the previous session for a UI element
# with a given id.
if(!is.null(saved_inputs[[id]])) {
saved_inputs[[id]] <<- NULL
}
}
# Load Tabs and Data ---------------------------------------------------------
# Locate tab files
tab_files <- list()
tab_ids <- list()
for (i in 1:length(tab_requests)) {
request <- tab_requests[i]
if (file.exists(file.path(launch_dir, request))) {
tab_files <- c(tab_files, file.path(launch_dir, request))
tab_ids <- c(tab_ids, sub("\\.R$", "", request))
} else if (file.exists(file.path('tabs', request))) {
tab_files <- c(tab_files, file.path('tabs', request))
tab_ids <- c(tab_ids, sub("\\.R$", "", request))
}
}
# Source tab files
cat("Sourcing Tabs:\n")
tab_environments <- mapply(function(file_name, id) {
env <- new.env()
if(!is.null(visualizer_config$tab_data)) {
env$tab_data <- visualizer_config$tab_data[[id]]
} else {
env$tab_data <- NULL
}
source(file_name, local = env)
# debugSource(file_name, local = env)
cat(paste0(" ", env$title, " (", file_name, ")\n"))
env
},
file_name=tab_files,
id=tab_ids,
SIMPLIFY = FALSE
)
# Read input dataset file
cat("Reading raw data:\n")
raw <- read.csv(file.path(launch_dir, visualizer_config$raw_data), fill=T, stringsAsFactors=TRUE, encoding="UTF-8")
if(!is.null(visualizer_config$augmented_data)) {
augmented_filename <- file.path(launch_dir,
visualizer_config$augmented_data)
augmented <- read.csv(augmented_filename, fill=T, stringsAsFactor=TRUE, encoding="UTF-8")
extra <- raw[!(raw$GUID %in% augmented$GUID),]
if(nrow(extra) > 0) {
cat(paste0(" Added ", nrow(extra), " points.\n"))
}
raw <- rbind(augmented, extra)
}
cat(" Done.\n")
# Locate Artifacts
cat("Locating Artifacts:\n")
guid_folders <- NULL
if(file.exists(file.path(launch_dir, 'metadata.json'))) {
config_folders <- GetConfigFolders(launch_dir)
cat(paste0(" Config Folders: ", length(config_folders), "\n"))
results_dir <- file.path(launch_dir,"..","..","results")
guid_folders <- FindGUIDFolders(results_dir, config_folders)
cat(paste0(" GUID Folders: ", length(guid_folders), "\n"))
} else if(file.exists(file.path(launch_dir, 'exported_metadata.json')) ||
file.exists(file.path(launch_dir, 'artifacts'))) {
config_folders <- list(".")
cat(paste0(" Config Folders: ", length(config_folders), "\n"))
results_dir <- launch_dir
guid_folders <- FindGUIDFolders(launch_dir, config_folders)
cat(paste0(" GUID Folders: ", length(guid_folders), "\n"))
} else {
cat(" No Artifacts Found.\n")
}
cat("Processing Files:\n")
# Process PET Configuration File ('pet_config.json') -------------------------
cat(" 'pet_config.json'\n")
pet <- NULL
if (!is.null(visualizer_config[["pet"]])) {
pet <- visualizer_config$pet
} else if(pet_config_present) {
pet <- BuildPet(pet_config_filename)
}
# Process Design Tree ('design_tree.json') -------------------------
cat(" 'design_tree.json'\n")
if (design_tree_present) {
design_tree <- fromJSON(design_tree_filename, simplifyDataFrame = FALSE)
if (is.empty(design_tree)) {
design_tree <- NULL
design_tree_present <- FALSE
} else {
FILTER_WIDTH_IN_COLUMNS <- 3
}
}
# Process Variables ----------------------------------------------------------
cat("Processing variables...\n")
variables <- NULL
if (!is.null(visualizer_config[["variables"]])) {
variables <- visualizer_config$variables
} else {
variables <- BuildVariables(pet, names(raw))
}
cat("Initial Setup Complete.\n\n")
# Server ---------------------------------------------------------------------
server <- function(input, output, session) {
# Server <- function(input, output, session) {
# Handles the processing of all UI interactions.
#
# Args:
# input: the Shiny list of all the UI input elements.
# output: the Shiny list of all the UI output elements.
# session: a handle for the Shiny session.
observe({
# Read input dataset file
raw <- raw_poll()
if(first_raw_poll) {
first_raw_poll <<- FALSE
} else {
cat("Re-reading raw data... ")
current <- isolate(data$raw$df)
extra <- raw[!(raw$GUID %in% current$GUID),]
if(nrow(extra) > 0) {
cat(paste("Adding", nrow(extra), "points.\n"))
data$raw$df <- rbind(current, extra)
} else {
cat("No new points added.\n")
}
}
})
raw_poll <- reactivePoll(1000, session,
# This function returns the time that raw data file was last modified
checkFunc = function() {
if (file.exists(file.path(launch_dir, visualizer_config$raw_data)))
file.info(file.path(launch_dir, visualizer_config$raw_data))$mtime[1]
else
""
},
# This function returns the content of log_file
valueFunc = function () {
read.csv(file.path(launch_dir, visualizer_config$raw_data), fill=T, encoding="UTF-8")
}
)
# Data Pre-Processing --------------------------------------------------------
var_class <- reactive({
df_class <- sapply(data$raw$df, class)
if (any(names(df_class) %in% c("GUID"))) {
df_class <- df_class[-which(names(df_class) %in% c("GUID"))]
}
df_class
})
var_names <- reactive({names(var_class())})
var_facs <- reactive({
if (any(var_class() == "factor")) {
var_names()[var_class() == "factor"]
} else {
NULL
}
})
var_ints <- reactive({
if (any(var_class() == "integer")) {
var_names()[var_class() == "integer"]
} else {
NULL
}
})
var_nums <- reactive({
if (any(var_class() == "numeric")) {
var_names()[var_class() == "numeric"]
} else {
NULL
}
})
var_nums_and_ints <- reactive({
selected <- var_class() == "integer" | var_class() == "numeric"
if (any(selected)) {
var_names()[selected]
} else {
NULL
}
})
abs_max <- reactive({
if (is.null(var_nums_and_ints())) {
NULL
} else {
apply(data$raw$df[var_nums_and_ints()], 2, max, na.rm=TRUE)
}
})
abs_min <- reactive({
if (is.null(var_nums_and_ints())) {
NULL
} else {
apply(data$raw$df[var_nums_and_ints()], 2, min, na.rm=TRUE)
}
})
var_range_nums_and_ints <- reactive({
if (is.null(var_nums_and_ints()) ||
is.null(abs_min()) ||
is.null(abs_max())) {
NULL
} else {
tentative_vars <- var_nums_and_ints()[(abs_min() != abs_max()) &
(abs_min() != Inf)]
if (length(tentative_vars) == 0) {
NULL
} else {
tentative_vars
}
}
})
var_range_facs <- reactive({
if(is.null(var_facs())) {
NULL
} else {
tentative_vars <- var_facs()[apply(data$raw$df[var_facs()], 2,
function(var_fac) {
length(names(table(var_fac))) > 1
})]
if (length(tentative_vars) == 0) {
NULL
} else {
tentative_vars
}
}
})
var_range_facs_filters <- reactive({
# This is used by the Filters observe to populate the selects
# The 'CfgID' variable is removed if we have a design tree present
if(is.null(var_range_facs())) {
NULL
} else {
tentative_vars <- var_range_facs()
if(design_tree_present && "CfgID" %in% tentative_vars) {
tentative_vars <- tentative_vars[-which(tentative_vars %in% c("CfgID"))]
}
if (length(tentative_vars) == 0) {
NULL
} else {
tentative_vars
}
}
})
var_range <- reactive({c(var_range_facs(), var_range_nums_and_ints())})
var_range_nums_and_ints_list <- reactive({
if (is.null(var_range_nums_and_ints())) {
NULL
} else {
AddCategories(data$meta$variables[var_range_nums_and_ints()])
}
})
var_range_facs_list <- reactive({
if (is.null(var_range_facs())) {
NULL
} else {
AddCategories(data$meta$variables[var_range_facs()])
}
})
var_range_list <- reactive({
if (is.null(var_range())) {
NULL
} else {
AddCategories(data$meta$variables[var_range()])
}
})
var_constants <- reactive({
if(is.null(var_range())) {
var_names()
} else {
subset(var_names(), !(var_names() %in% var_range()))
}
})
pre <- list(var_names=var_names,
var_class=var_class,
var_facs=var_facs,
var_ints=var_ints,
var_nums=var_nums,
var_nums_and_ints=var_nums_and_ints,
abs_min=abs_min,
abs_max=abs_max,
var_range_nums_and_ints=var_range_nums_and_ints,
var_range_facs=var_range_facs,
var_range_facs_filters=var_range_facs_filters,
var_range=var_range,
var_range_nums_and_ints_list=var_range_nums_and_ints_list,
var_range_facs_list=var_range_facs_list,
var_range_list=var_range_list,
var_constants=var_constants)
# Design Configs for Filters -----------------------------------------------
observe({
if(design_tree_present) {
if(is.empty(visualizer_config$config_tree)) {
config_tree <- SelectAllComponents(design_tree[[names(design_tree)[1]]])
} else {
config_tree <- visualizer_config$config_tree
}
session$sendCustomMessage(type = "setup_design_configurations", config_tree)
}
})
# observe({print(paste("SDC:",paste(SelectedDesignConfigs(),collapse=",")))})
SelectedDesignConfigs <- reactive({
# print(input$filter_design_config_tree)
if(!is.null(input$filter_design_config_tree)) {
names <- names(design_tree)
passing <- sapply(names, function(name) {
filter_tree <- input$filter_design_config_tree
current_tree <- design_tree[[name]]
compare_node(current_tree, filter_tree)
})
if(any(passing)) {
names[passing]
} else {
NULL
}
} else {
if ("CfgID" %in% names(data$raw$df) && is.null(design_tree)) {
if(pet_config_present) {
pet$selected_configurations
} else {
unique(data$raw$df[['CfgID']])
}
} else {
NULL
}
}
})
# Filters (Enumerations, Sliders) and Constants ----------------------------
# Lets the UI know if a tab has requested the 'Filters' footer.
footer_preferences <- lapply(tab_environments,
function(tab_env) {tab_env$footer})
names(footer_preferences) <- lapply(tab_environments,
function(tab_env) {tab_env$title})
output$display_footer <- reactive({
req(input$master_tabset)
display <- (footer_preferences[[input$master_tabset]])
})
outputOptions(output, "display_footer", suspendWhenHidden=FALSE)
# Special observe to cover 'footer_collapse'
observe({
if(!is.null(si_read("footer_collapse"))) {
open <- si("footer_collapse")
if(is.empty(open)) {
updateCollapse(session, "footer_collapse", close = "Filters")
} else {
updateCollapse(session, "footer_collapse", open = open)
}
}
})
observe({
cat("Updating Filter UI:\n")
update_select_filter <- function(name) {
id <- paste0("filter_div_",name)
filter_name <- paste0('filter_', name)
items <- names(table(data$raw$df[[name]]))
for(i in 1:length(items)){
items[i] <- paste0(i, '. ', items[i])
}
if (id %in% filter_divs)
{
updateSelectInput(session = session,
inputId = filter_name,
choices = items)
cat(paste0("Updated Select Filter: ", name, "\n"))
}
else
{
selection <- si(paste0('filter_', name), items)
filter_divs <<- c(filter_divs, id)
insertUI(selector = "#filters_div", ui =
tags$div(
column(FILTER_WIDTH_IN_COLUMNS,
selectInput(inputId = paste0('filter_', name),
label = name,
multiple = TRUE,
selectize = FALSE,
choices = items,
selected = selection)
),
id = id))
cat(paste0("Created Select Filter '", name, "'\n"))
}
}
lapply(data$pre$var_range_facs_filters(), update_select_filter)
update_slider_filter <- function(name) {
id <- paste0("filter_div_",name)
filter_name <- paste0('filter_', name)
# Determine the valid range
if(name %in% pre$var_nums()){
min <- as.numeric(pre$abs_min()[name])
max <- as.numeric(pre$abs_max()[name])
step <- signif(max((max-min)*0.01, abs(min)*0.001, abs(max)*0.001),
digits = 4)
slider_min <- signif((min - step*10), digits = 4)
slider_max <- signif((max + step*10), digits = 4)
}
else{
slider_min <- as.numeric(pre$abs_min()[name])
slider_max <- as.numeric(pre$abs_max()[name])
}
# Does the slider exist already?
if (id %in% filter_divs)
{
# Slider exists; just update the range.
updateSliderInput(session = session,
inputId = filter_name,
min = slider_min,
max = slider_max)
cat(paste0("Updated Slider Filter: ", name, "\n"))
}
else
{
# Slider doesn't exist; let's create it.
selection <- si(filter_name, c(slider_min, slider_max))
filter_divs <<- c(filter_divs, id)
insertUI(selector = "#filters_div", ui =
tags$div(
column(FILTER_WIDTH_IN_COLUMNS,
# Hidden well panel for slider tooltip
wellPanel(id = paste0("slider_tooltip_", name),
style = "position: absolute; z-index: 65; box-shadow: 10px 10px 15px grey; width: 20vw; left: 1vw; top: -275%; display: none;",
h4(data$meta$variables[[name]]$name_with_units),
textInput(paste0("tooltip_min_", name), "Min:"),
textInput(paste0("tooltip_max_", name), "Max:"),
actionButton(paste0("submit_", name), "Apply","success")
),
# The slider itself
sliderInput(inputId = filter_name,
label = AbbreviateLabel(name),
min = slider_min,
max = slider_max,
value = selection)),
id = id))
cat(paste0("Created Slider Filter '", name, "'\n"))
}
}
lapply(data$pre$var_nums_and_ints(), update_slider_filter)
})
# Slider abbreviation function based off slider_width
abbreviation_length <- ABBREVIATION_LENGTH
AbbreviateLabel <- function(name) {
if(!is.null(input$slider_width)){
abbreviation_length <<- input$slider_width/8
}
abbreviate(name, abbreviation_length)
}
# Process slider pixel width when opening filters
observeEvent(input$footer_collapse, {
session$onFlushed(function() {
session$sendCustomMessage("update_widths", message = 1);
})
})
# Custom action button for exact entry. This makes a green button
# and can also be accessed to produced different themed buttons
actionButton <- function(inputId, label, btn.style = "" , css.class = "") {
if ( btn.style %in% c("primary","info","success","warning","danger","inverse","link"))
btn.css.class <- paste("btn",btn.style,sep="-")
else btn.css.class = ""
tags$button(id=inputId, type="button", class=paste("btn action-button",btn.css.class,css.class,collapse=" "), label)
}
openSliderToolTip <- function(current) {
# This function calls hide on all slider exact entry windows on a
# 'double click' and then calls 'show' on the opened one.
for(i in 1:length(pre$var_range_nums_and_ints())) {
hide(paste0("slider_tooltip_", pre$var_range_nums_and_ints()[i]))
}
shinyjs::show(paste0("slider_tooltip_", current))
}
observe({
lapply(pre$var_range_nums_and_ints(), function(current) {
# This handles the processing of exact entry back into the slider.
# It reacts to either the submit button OR the enter key
input[[paste0("submit_", current)]]
input$last_key_pressed
isolate({
slider_value = input[[paste0('filter_', current)]]
new_min = input[[paste0("tooltip_min_", current)]]
new_max = input[[paste0("tooltip_max_", current)]]
updateTextInput(session, paste0("tooltip_min_", current), value = "")
updateTextInput(session, paste0("tooltip_max_", current), value = "")
suppressWarnings({ #Suppress warnings from non-numeric inputs
if(!is.null(new_min) && new_min != "" && !is.na(as.numeric(new_min)))
slider_value = as.numeric(c(new_min, slider_value[2]))
if(!is.null(new_max) && new_max != "" && !is.na(as.numeric(new_max)))
slider_value = as.numeric(c(slider_value[1], new_max))
})
updateSliderInput(session, paste0('filter_', current), value = slider_value)
hide(paste0("slider_tooltip_", current))
})
})
})
# This function adds a double click handler to each slider
observe({
lapply(pre$var_range_nums_and_ints(), function(current) {
onevent("dblclick", paste0("filter_", current), openSliderToolTip(current))
inlineCSS(list(.style = "overflow: hidden"))
})
})
output$constants <- renderUI({
fluidRow(
lapply(pre$var_constants(), function(var_constant) {
column(2,
p(strong(paste0(var_constant,":")), unname(raw[1,var_constant]))
)
})
)
})
output$constants_present <- reactive({
length(pre$var_constants()) > 0
})
outputOptions(output, "constants_present", suspendWhenHidden=FALSE)
observeEvent(input$reset_sliders, {
session$sendCustomMessage(type = "select_all_design_configurations", "")
for(column in 1:length(pre$var_names())){
name <- pre$var_names()[column]
switch(pre$var_class()[column],
"numeric" =
{
max <- as.numeric(unname(data$pre$abs_max()[pre$var_names()[column]]))
min <- as.numeric(unname(data$pre$abs_min()[pre$var_names()[column]]))
diff <- (max-min)
if (diff != 0) {
step <- max(diff*0.01, abs(min)*0.001, abs(max)*0.001)
updateSliderInput(session, paste0('filter_', name), value = c(signif(min-step*10, digits = 4), signif(max+step*10, digits = 4)))
}
},
"integer" =
{
max <- as.integer(unname(data$pre$abs_max()[pre$var_names()[column]]))
min <- as.integer(unname(data$pre$abs_min()[pre$var_names()[column]]))
if(min != max) {
updateSliderInput(session, paste0('filter_', name), value = c(min, max))
}
},
"factor" = updateSelectInput(session, paste0('filter_', name), selected = names(table(data$raw$df[pre$var_names()[column]])))
)
}
})
# Data processing ----------------------------------------------------------
FilteredData <- reactive({
# This reactive holds the full dataset that has been filtered
if(input$choose_filter_mode == "Manually Filter") {
# Using the values of the sliders
data_filtered <- data$raw$df
if(input$remove_missing) {
data_filtered <- data_filtered[complete.cases(data_filtered), ]
}
if(input$remove_outliers) {
#Filter out rows by standard deviation
for(column in 1:length(data$pre$var_range_nums_and_ints())) {
a <- sapply(data_filtered[data$pre$var_range_nums_and_ints()[column]],
function(x) {
m <- mean(x, na.rm = TRUE)
s <- sd(x, na.rm = TRUE)
x >= m - input$num_sd*s &
x <= m + input$num_sd*s
}
)
data_filtered <- subset(data_filtered, a)
}
}
if("CfgID" %in% names(data_filtered)) {
data_filtered <- subset(data_filtered, data_filtered$CfgID %in% SelectedDesignConfigs())
}
for(index in 1:length(pre$var_names())) {
name <- pre$var_names()[index]
input_name <- paste("filter_", name, sep="")
selection <- input[[input_name]]
if(length(selection) != 0) {
if(name %in% pre$var_nums_and_ints()) {
isolate({
above <- (data_filtered[[name]] >= selection[1])
below <- (data_filtered[[name]] <= selection[2])
in_range <- above & below
})
}
else if (name %in% pre$var_facs()) {
selection <- unlist(lapply(selection, function(factor){
RemoveItemNumber(factor)
}))
in_range <- (data_filtered[[name]] %in% selection)
}
# Don't filter based on missing values.
in_range <- in_range | is.na(data_filtered[[name]])
data_filtered <- subset(data_filtered, in_range)
}
# print(nrow(data_filtered))
}
} else {
# Using the set selection
data_filtered <- data$raw$df
data_filtered <- subset(data_filtered, data_filtered$GUID %in% SelectedSetGUIDs())
}
data_filtered
})
SelectedSetGUIDs <- reactive({
selected_set <- input$choose_set_to_display
data$meta$sets[[selected_set]]
})
observe({
output$filters_stats <- renderText(
paste0("Current Points: ",nrow(FilteredData()), " / ", nrow(data$raw$df),
" ( ", round(100*nrow(FilteredData())/nrow(data$raw$df), digits = 2),
"% )"))
})
Filters <- reactive({
# This reactive returns a list of all the filter values so a tab can use
# the information for filtering the raw dataset itself.
#
# Each of the variables will have a "type" that is simply the
# pre$var_class() for that variable and either "selection" or "min" and
# "max", e.g.:
# > Filters()$Engine$type
# "factor"
# > Filters()$Engine$selection
# "V6" "V8"
# > Filters()$TopSpeed$type
# "numeric"
# > Filters()$TopSpeed$min
# 130
# > Filters()$TopSpeed$max
# 210
filters <- list()
for(index in 1:length(pre$var_names())) {
name <- pre$var_names()[index]
input_name <- paste("filter_", name, sep="")
selection <- input[[input_name]]
filters[[name]] <- list()
filters[[name]]$type <- pre$var_class()[[name]]
if(pre$var_class()[[name]] == "factor") {
filters[[name]]$selection <- unname(sapply(selection,
RemoveItemNumber))
}
else {
filters[[name]]$min <- selection[1]
filters[[name]]$max <- selection[2]
}
}
filters
})
getFilter <- function(name) {
# This funciton can be used by the tabs to get the selection value for a
# given variable filter. This method offers the same functionality as using
# the data$Filters() reactive.
#
# Args:
# name: The name of the variable to get. Don't include "filter_" in the
# name; this will be appending in the function.
#
# Returns:
# A vector of the selected items if the variable class is "factor" and a
# vector c(min, max) with the min and max value of the filter if it is
# numeric.
input[[paste0("filter_", name)]]
}
setFilter <- function(name, selection) {
# This funciton can be used by the tabs to get the selection value for a
# given variable filter. This method offers the same functionality as using
# the data$Filters() reactive.
#
# Args:
# name: The name of the variable to set. Don't include "filter_" in the
# name.
# selection: The value to set in the Filter. This should be a character
# vector for variables of class "factor" and a vector
# c(min, max) for variables of class "numeric."
#
# Returns:
# A the selection if the operation is successful, and NULL otherwise.
if (name %in% data$pre$var_range())
{
filter_name <- paste0("filter_", name)
if (name %in% data$pre$var_range_nums_and_ints()) {
updateSliderInput(session = session,
inputId = filter_name,
value = selection)
}
else
{
updateSelectInput(session,
filter_name,
value = selection)
}
selection
}
else
{
NULL
}
}
ColoredData <- reactive({
data_colored <- FilteredData()
data_colored$color <- character(nrow(data_colored))
if(nrow(data_colored) > 0) {
data_colored$color <- "black" #input$normColor
if (input$coloring_source != "None") {
if (input$coloring_source == "Live") {
type <- input$live_coloring_type
}
else {
type <- data$meta$colorings[[input$coloring_source]]$type
}
req(type)
current <- list()
current$name <- input$coloring_source
current$type <- type
switch(type,
"Max/Min" =
{
if (input$coloring_source == "Live") {
var <- input$live_coloring_variable_numeric
goal <- input$live_coloring_max_min
}
else {
scheme <- data$meta$colorings[[input$coloring_source]]
var <- scheme$var
goal <- scheme$goal
}
bins <- 30
req(var)
minimum <- min(FilteredData()[[var]])
maximum <- max(FilteredData()[[var]])
divisor <- (maximum - minimum) / bins
cols <- rainbow(bins, 1, 0.875, start = 0, end = 0.325)
if (goal == "Maximize") {
Bin <- function(value) {max(1, ceiling((value - minimum) / divisor))}
} else {
Bin <- function(value) {max(1, ceiling((maximum - value) / divisor))}
}
data_colored$color <- unlist(sapply(data_colored[[var]], function(value) {
if(is.na(value)) {
"grey"
} else {
cols[Bin(value)]
}
}))
current$var <- var
current$goal <- goal
current$colors <- cols
current$max <- maximum
current$min <- minimum
isolate({
data$colorings$current <- current
})
},
"Discrete" =
{
if (input$coloring_source == "Live") {
var <- input$live_color_variable_factor
palette_selection <- input$live_color_palette
if (palette_selection == "Rainbow") {
s_value <- input$live_color_rainbow_s
v_value <- input$live_color_rainbow_v
}