-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.R
More file actions
executable file
·1269 lines (1118 loc) · 49 KB
/
server.R
File metadata and controls
executable file
·1269 lines (1118 loc) · 49 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
# server.R
# Author: Patricia Angkiriwang, University of British Columbia - 2019-2021
# with code initially adapted from FSDM, an open-source R Shiny app by Brian Gregor, Oregon Systems Analytics LLC
## NOTES ON DATA FORMAT:
# > model: A model is a list of 2
# model$concepts: a data frame with columns (chr/string) - name, variable, description, values, group
# model$relations: a list of [# of concepts with incoming links], each a list of 2
# concept_name: (chr - name of affected variable)
# affected_by: (list of[#things that affect it])
## NOTES ON THIS VERSION:
# (2021/02) This version of the model does not use min/max concept values (commented out) -- a relic of the original Logic Laboratory app
# Load packages and necessary scripts ---------------
library(shiny)
library(shinyBS) # bootstrap for formatting
library(plotly) # for interactive plots
library(DT) # data tables
library(grid) # arranging multiple plots (unused?)
library(jsonlite) # for reading in/out data
library(dplyr) # for data wrangling
library(ggplot2) # plots
library(tidyr) # tidying data
library(DiagrammeR) # for visualizing graph
source("helper.R") # load helper.R script (contains necessary functions)
source('fcm.R') # load model algorithm
# source('../../bcfn_seafood_access_modelling/fcm.R')
# SHINY SERVER FUNCTION
shinyServer(function(input, output, session) {
# Define some settings and global variables here --------------
weight_vals_default <- c(VL = 0.1, L = 0.25, ML = 0.375, M = 0.5, MH = 0.625, H = 0.75, VH = 0.9)
#c(VL = 1, L = 1, ML = 1, M = 1, MH = 1, H = 1, VH = 1)
# === CREATE OBJECTS TO STORE MODEL, ETC. ------ ==================
# Reactive object to store current state that interface responds to
model <- reactiveValues(status = NULL, concepts = NULL, relations = NULL, weight_vals = weight_vals_default)
# Reactive object to store model history (unlimited undo)
history <- reactiveValues(status = NULL, concepts = NULL, relations = NULL, weight_vals = NULL)#, previousRowNum = NULL) #note: attempts to keep rows from resetting have failed 2019/05/22
# Global variable that flags whenever a new relationship is defined
flag_newRelation <- FALSE
# Reactive object to keep track of various conditions
is <- reactiveValues(newconcept = FALSE)
# Reactive object to store current selected effects (what are the relations corresponding to the currently selected causal concept?)
# (ie. what is selected in the Edit Relationships tab?)
selectedfx <- reactiveValues(
to = "", # <- a vector
from = "",
direction = "",
strength = "",
grouping = 1,
description = "")
# Reactive object to store the settings for the current model simulation/run
run <- reactiveValues(results = NULL, parameters= NULL, constraints = NULL, sweep_params = NULL, sweep_results = NULL)
# Create a reactive object to store scenario data in
scenarios <- reactiveValues(results = list(), constraints = list(), parameters = list())
# Create a reactive object to handle/ store monte carlo simulations
monte_carlo <- reactiveValues(models = list(), results = NULL)
# === DEFINE COMMON FUNCTIONS FOR MODIFYING REACTIVE VALUES ----- ===================
# Function to save the model in history
saveLastState <- function() {
history$status <- model$status
history$concepts <- model$concepts
history$relations <- model$relations
history$weight_vals <- model$weight_vals
}
# Function to swap model and history (i.e. undo)
swapState <- function(swap = "all") {
if (swap == "concept" || swap == "all"){
concepts <- model$concepts
model$concepts <- history$concepts
history$concepts <- concepts
}
if (swap == "relation" || swap == "all"){
relations <- model$relations
model$relations <- history$relations
history$relations <- relations
}
if (swap == "all"){
weights <- model$weight_vals
model$weight_vals <- history$weight_vals
history$weight_vals <- weights
status <- model$status
model$status <- history$status
history$status <- status
}
}
# Function to undo concept edit
undoConceptEdit <- function() {
swapState("concept")
}
# Function to undo relation edit
undoRelationEdit <- function() {
swapState("relation")
}
# Function to update concept form inputs
updateConceptForm <- function(RowNum) {
updateTextInput(session, "conceptName",
value = model$concepts$name[RowNum])
updateTextInput(session, "conceptID",
value = model$concepts$concept_id[RowNum])
updateTextInput(session, "conceptDesc",
value = model$concepts$description[RowNum])
updateTextInput(session, "conceptCategory",
value = model$concepts$category[RowNum])
}
#Function to update relation form causal and affected variables -- the rest updates based on other observes
updateRelationForm <- function(RowNum) {
causal_vars <- extract_rel(model$relations, "concept_id")
affects_vars <- extract_rel(model$relations, "concept_id", level="affected")
updateSelectInput(session, inputId = "causalConcept",
selected = causal_vars[RowNum]
)
updateSelectInput(session, inputId = "affectedConcept",
selected = affects_vars[RowNum]
)
}
# Function to clear reactive data when when changing model
resetModel <- function(){
history$status = NULL
history$concepts = NULL
history$relations = NULL
history$weight_vals = NULL
model$concepts = NULL
model$relations = NULL
model$status = NULL
model$weight_vals = weight_vals_default
selectedfx$to <- ""
selectedfx$from <- ""
selectedfx$direction <- ""
selectedfx$strength <- ""
selectedfx$description <- ""
selectedfx$grouping <- 1
run$results <- NULL
run$parameters <- NULL
run$constraints <- NULL
run$sweep_params <- NULL
run$sweep_results <- NULL
run$sweep_constraints <- NULL
scenarios$results <- list()
scenarios$constraints <- list()
scenarios$parameters <- list()
}
resetRun <- function(){
run$results <- NULL
run$parameters <- NULL
run$constraints <- NULL
run$sweep_params <- NULL
run$sweep_results <- NULL
run$sweep_constraints <- NULL
updateTextInput(session, "scenarioName", value = "")
}
resetScenarios <- function(){
scenarios$results <- list()
scenarios$constraints <- list()
scenarios$parameters <- list()
}
# === IMPLEMENT INTERFACE FOR INITIALIZING MODEL ------ =========================
# Output: Define GUI element to select model from a list -----------------
output$selectExistingModelFile <- renderUI({
selectInput(
inputId = "modelFileName",
selected = NULL,
label = NULL,
choices = dir(path = "./models")[dir(path = "./models") != "templates"]
)
})
# Define author name -----------------
ModelAuthor <- reactive({
if (input$anonymous){
author <- "Anonymous"
} else{
author <- ifelse(input$organization=="", paste0(input$firstName, " ", input$lastName), paste0(input$firstName, " ", input$lastName, " (", input$organization, ")"))
}
return(author)
})
# Render model status for UI display ---------------
output$modelStatusDisplay <- renderPrint({
model$status
})
# Choose model start option and initialize model -----------------
observeEvent(
input$startModeling,
{
if(input$modelAction == "select_existing") {
model$status <- loadModelStatus(input$modelFileName, ModelAuthor())
model$concepts <- loadModelConcepts(input$modelFileName)
model$relations <- loadModelRelations(input$modelFileName)
weight_vals_loaded <- loadWeightValues(input$modelFileName)
if (is.null(weight_vals_loaded)){
model$weight_vals <- weight_vals_default
} else {
model$weight_vals <- weight_vals_loaded
}
#View(model$relations)
notify("Model loaded from /models folder")
} # end if input$modelAction
if(input$modelAction == "create_new"){
if (input$newModelFileName == ""){
createAlert(session, anchorId="noModelName", append=FALSE,
content="Please enter a new model name-- this will be the name of the new directory created")
return()
}
model$status <- initializeNewModel(input$newModelFileName, ModelAuthor())
if (is.null(model$status)){
notify("Model initialization failed. Please enter a new model name-- this will be the name of the new directory created", type="error")
return()
} else {
model$concepts <- loadModelConcepts(input$newModelFileName)
model$relations <- loadModelRelations(input$newModelFileName)
notify("New model created from /models/templates")
}
}
updateConceptForm(1)
updateRelationForm(1)
saveLastState()
resetRun()
resetScenarios()
}) # end: observeEvent - input$startModeling
# === IMPLEMENT INTERFACE FOR EDITING MODEL CONCEPTS ------ ===============================
# Update concept form based on what is selected in table ------------
observeEvent(
c(input$conceptsTableEditing_rows_selected,input$undoConceptAction), # fixed broken undo by adding additional argument here 2019/05/22
{
if(!is.null(input$conceptsTableEditing_rows_selected)){
RowNum <- input$conceptsTableEditing_rows_selected
updateConceptForm(RowNum)
}
}
)
# Implement the new concept button -----------------
observeEvent(
input$addConcept,
{
if (input$conceptID %in% model$concepts$concept_id) {
createAlert(session = session, anchorId = "duplicateConceptVariable",
title = "Duplicate ID",
content = "New concept ID is the same as an existing concept. Rename before updating.")
return()
} else if (input$conceptID == ""){
createAlert(session = session, anchorId = "blankConceptVariable",
title = "Blank ID",
content = "New concept ID must not be blank.")
return()
}
new_concept <- data.frame(name = input$conceptName,
concept_id = input$conceptID,
description = input$conceptDesc,
category = input$conceptCategory)
model$concepts <- bind_rows(new_concept, model$concepts)
# if (nrow(model$concepts)>0){
# model$concepts <- model$concepts[c(1,1:nrow(model$concepts)),]
# }
# model$concepts$name[1] <- input$conceptName
# model$concepts$concept_id[1] <- input$conceptID
# model$concepts$description[1] <- input$conceptDesc
# model$concepts$category[1] <- input$conceptCategory
RowNum <- input$conceptsTableEditing_rows_selected
updateConceptForm(RowNum)
}
)
# Implement the update concept button -----------------
observeEvent(
input$updateConcept,
{
saveLastState() # save state of current model
# If ID already exists, just update the rest
if (input$conceptID %in% model$concepts$concept_id) {
idx <- model$concepts$concept_id == input$conceptID
# Update model concepts corresponding to that ID
model$concepts[idx,"name"] <- input$conceptName
model$concepts[idx,"description"] <- input$conceptDesc
model$concepts[idx, "category"] <- input$conceptCategory
} else {
# If not, update everything based on the row selected
# Update model concepts
RowNum <- input$conceptsTableEditing_rows_selected
oldID <- model$concepts$concept_id[RowNum]
model$concepts$name[RowNum] <- input$conceptName
model$concepts$concept_id[RowNum] <- input$conceptID
model$concepts$description[RowNum] <- input$conceptDesc
model$concepts$category[RowNum] <- input$conceptCategory
# Also need to update all relationships that have the old conceptID:
tbl <- isolate(relationstable()) # Get relationstable for reference
rename_links_to <- tbl[tbl$From == oldID, "To"]
# Get variables in the model that are affected by something (in relations list)
ExistingAffected <-
unlist(lapply(model$relations, function(x) x$concept_id))
# Update relationships that have this as "from"
for (a_idx in 1:length(ExistingAffected)){
if (ExistingAffected[a_idx] == oldID){
model$relations[[a_idx]]$concept_id <- input$conceptID
View(model$relations)
}
# Update relationships that have this as "to"
for (affectingID in rename_links_to){
if (ExistingAffected[a_idx] == affectingID){
for (g in 1:length(model$relations[[a_idx]]$affected_by)){
links <- model$relations[[a_idx]]$affected_by[[g]]$links
ExistingLinked <- unlist(lapply(links, function(x) x$concept_id)) # All links to the affected concept
c_idx <- which(ExistingLinked == oldID)
if (length(c_idx)>0){
model$relations[[a_idx]]$affected_by[[g]]$links[[c_idx]]$concept_id <- input$conceptID
}
}
}
}
}
}
model$status$lastedit <- as.character(Sys.time())
showNotification(
ui = "Concept updated",
duration = 1,
closeButton = TRUE,
type = "message"
)
}
)
# Implement the undo button ----------------
observeEvent(
input$undoConceptAction,
{
undoConceptEdit()
model$status$lastedit <- as.character(Sys.time())
}
)
# Implement the delete concept button -----------------
observeEvent(
input$deleteConcept,
{
saveLastState() # save last model state
# Get concept to be deleted
RowNum <- input$conceptsTableEditing_rows_selected
Var <- model$concepts$concept_id[RowNum]
# If no rows selected, print a warning
if (is.null(RowNum)){
notify("Select a row in the table to delete", type = "warning")
return(NULL)
}
# Remove concept from model concepts table
model$concepts <- model$concepts[-RowNum,]
model$status$lastedit <- as.character(Sys.time())
# Remove concept from model relations list
tbl <- isolate(relationstable()) # Get relationstable for reference
items_to_delete <- c() # Define vector for deleting items in relations list
# Get variables in the model that are affected by something (in relations list)
ExistingAffected <-
unlist(lapply(model$relations, function(x) x$concept_id))
# Add to delete list: relations where the deleted concept is affected
idx <- which(ExistingAffected == Var) # Find index in relations list that corresponds to the deleted concept
if (length(idx)!=0){
items_to_delete <- c(items_to_delete, idx)
}
# Add to delete list / delete relations where the deleted concept affects something else
c_idxs <- which(tbl$From==Var) # Get indices of relevant rows (where deleted concept affects another)
if (length(c_idxs)>0){
# For each relevant row...
for (i in c_idxs){
# Find the element in the relations list corresponding to the relation to be deleted
g <- tbl[i,"Grouping"] # Get the group number corresponding to the link
LinkTo <- tbl[i,"To"] # What is the affected concept?
a_idx <- which(ExistingAffected == LinkTo) # Get index of the affected concept
links <- model$relations[[a_idx]]$affected_by[[g]]$links # Get links in that grouping
ExistingLinked <- unlist(lapply(links, function(x) x$concept_id)) # All links to the affected concept
c_idx <- which(ExistingLinked == Var) # Which one corresponds to the deleted concept?
# Delete relations where the deleted concept is the causal concept
model$relations[[a_idx]]$affected_by[[g]]$links[[c_idx]] <- NULL
if (length(model$relations[[a_idx]]$affected_by[[g]]$links) == 0){
model$relations[[a_idx]]$affected_by[[g]] <- NULL
# If the affected concept no longer has any more links, them remove the whole thing from the relations list (add to delete list)
if (length(model$relations[[a_idx]]$affected_by) == 0){
items_to_delete <- c(items_to_delete, a_idx)
}
}
}
}
# Now delete primary elements in relations list (do this later and all at once so the indices don't change after each deletion)
if (length(items_to_delete)>0){
model$relations <- model$relations[-items_to_delete]
}
# Update the input form
updateConceptForm(RowNum)
}) #observeEvent: deleteConcept
# Notification when model saved ---------
observeEvent(
c(input$saveModel1,input$saveModel2,input$saveModel3),
{
if (!is.null(model$status$name)){
saveModel(model)
notify("All updates have been saved in the /models folder")
}
})
# === IMPLEMENT INTERFACE FOR EDITING MODEL RELATIONS ------ ===============================
# Update relations form based on what is selected in table ----------------
observeEvent(
c(input$relationsTableEditing_rows_selected,input$undoRelationAction),
{
if(!is.null(input$relationsTableEditing_rows_selected) || flag_newRelation==FALSE){
RowNum <- input$relationsTableEditing_rows_selected
updateRelationForm(RowNum)
}
}
)
# Output: Define dropdown element to select causal concept from a list (for editing) ----------------
output$selectCausalConcept <- renderUI({
selectInput(
inputId = "causalConcept",
label = "Influencing Concept (From)",
choices = sort(model$concepts$concept_id)
#choices = sort(model$concepts$name)
)
})
# Output: Define dropdown element to select affected concept from a list (for editing) ----------------
output$selectAffectedConcept <- renderUI({
selectInput(
inputId = "affectedConcept",
label = "Affected Concept (To)",
choices = sort(model$concepts$concept_id)
#choices = sort(model$concepts$name)
)
})
# Create reactive value that contains a formatted relations table (for internal use, not display) ----------------
relationstable <- reactive({
# Note: right now the only difference (between this and the table that is displayed in the GUI
# is that full names are not used here. If eventually full names are used in the editing relations dropdowns
# then this can be consolidated and used for the GUI too.
if (length(model$relations)!=0){
formatRelationTable(model$relations,model$concepts,use.full.names=FALSE,export=TRUE)
}
})
# Update GUI (text input + dropdowns) and current effect ("selectedfx") to match the relations table ------------------------
observeEvent( # On change of selected causal concept
c(input$causalConcept,input$undoRelationAction),
{
# First deselect rows in relations table
relationsTableEditing_proxy %>% selectRows(NULL)
if (input$causalConcept != "" && length(input$causalConcept)>0){
# Get relations table to find indices
tbl <- isolate(relationstable())
# Get all the relations that stem from this causal concept
Effects_df <- tbl[tbl$From==input$causalConcept,]
if (length(Effects_df) >0 && nrow(Effects_df)>0){
selectedfx$to <- Effects_df$To
selectedfx$from <- Effects_df$From
selectedfx$direction <- Effects_df$Direction
selectedfx$strength <- Effects_df$Weight
selectedfx$description <- Effects_df$Description
selectedfx$grouping <- Effects_df$Grouping
selectedfx$k <- Effects_df$k
selectedfx$type <- Effects_df$Type
# Then, match the one that corresponds to the affected concept selected (if applicable)
if (input$affectedConcept %in% selectedfx$to) {
updateTextInput(session, "causalDirection",
value = selectedfx$direction[selectedfx$to == input$affectedConcept])
updateTextInput(session, "causalStrength",
value = selectedfx$strength[selectedfx$to == input$affectedConcept])
updateTextInput(session, "causalDesc",
value = selectedfx$description[selectedfx$to == input$affectedConcept])
# updateTextInput(session, "relGrouping",
# value = selectedfx$grouping[selectedfx$to == input$affectedConcept])
updateTextInput(session, "relK",
value = selectedfx$k[selectedfx$to == input$affectedConcept])
updateTextInput(session, "relType",
value = selectedfx$type[selectedfx$to == input$affectedConcept])
# and change the selected row in the table to match
r <- which(tbl$From==input$causalConcept & tbl$To == input$affectedConcept)
relationsTableEditing_proxy %>% selectRows(as.numeric(r))
} else {
updateTextInput(session, "causalDirection", value = "")
updateTextInput(session, "causalStrength", value = "")
updateTextInput(session, "causalDesc", value = "")
# note: relations info doesn't reset on purpose
}
} else { # If no pair of concepts are selected in UI
selectedfx$to <- ""
selectedfx$concept <- ""
selectedfx$direction <- ""
selectedfx$strength <- ""
selectedfx$description <- ""
updateTextInput(session, "causalDirection", value = "")
updateTextInput(session, "causalStrength", value = "")
updateTextInput(session, "causalDesc", value = "")
# note: relations info doesn't reset on purpose
}
}
}
)
observeEvent( # On change of selected affected concept
input$affectedConcept,
{
# (Assume causal concept already selected): match the one that corresponds to the affected concept selected (if applicable)
if (input$affectedConcept %in% selectedfx$to) {
flag_newRelation <<- FALSE
updateTextInput(session, "causalDirection",
value = selectedfx$direction[selectedfx$to == input$affectedConcept])
updateTextInput(session, "causalStrength",
value = selectedfx$strength[selectedfx$to == input$affectedConcept])
updateTextInput(session, "causalDesc",
value = selectedfx$description[selectedfx$to == input$affectedConcept])
# updateTextInput(session, "relGrouping",
# value = selectedfx$grouping[selectedfx$to == input$affectedConcept])
updateTextInput(session, "relK",
value = selectedfx$k[selectedfx$to == input$affectedConcept])
updateTextInput(session, "relType",
value = selectedfx$type[selectedfx$to == input$affectedConcept])
# and change the selected row in the table to match
r <- which(isolate(relationstable())$From==input$causalConcept & isolate(relationstable())$To == input$affectedConcept)
relationsTableEditing_proxy %>% selectRows(as.numeric(r))
} else {
flag_newRelation <<- TRUE
updateTextInput(session, "causalDirection", value = "")
updateTextInput(session, "causalStrength", value = "")
updateTextInput(session, "causalDesc", value = "")
relationsTableEditing_proxy %>% selectRows(NULL) # deselect rows in table
}
}
)
# Implement the update relations button --------------------
observeEvent(
input$updateRelation,
{
#Save last model state in redobuffer
saveLastState()
# If there are no concepts in the model, do nothing; same if information missing
if (length(model$concepts$name)==0){
return(NULL)
} else if (is.null(input$causalConcept) || is.null(input$affectedConcept)){
notify("To add/ update a relationship, make sure both causal and affect concepts are specified")
return(NULL)
} else if (is.null(input$relationsTableEditing_rows_selected) && flag_newRelation==FALSE){
notify("To add/ update a relationship, make sure both causal and affect concepts are specified")
return(NULL)
}
#Update Relation
CausalConcept <-
model$concepts$concept_id[model$concepts$concept_id == input$causalConcept]
AffectedConcept <-
model$concepts$concept_id[model$concepts$concept_id == input$affectedConcept]
ExistingAffected<- unlist(lapply(model$relations, function(x) x$concept_id))
NewEffect_ls <-
list(concept_id = CausalConcept,
direction = input$causalDirection,
weight = input$causalStrength,
description = input$causalDesc)
if ((length(ExistingAffected)>0) && (AffectedConcept %in% ExistingAffected)) {
# Find where the new data should go
a_idx <- which(ExistingAffected == AffectedConcept)
if (is.null(input$relGrouping)){
group_idx <- 1
} else {
group_idx <- input$relGrouping
}
links <- model$relations[[a_idx]]$affected_by[[group_idx]]$links
ExistingLinked <- unlist(lapply(links, function(x) x$concept_id))
if (length(ExistingLinked)>0 && CausalConcept %in% ExistingLinked){
c_idx <- which(ExistingLinked == CausalConcept)
} else{
c_idx <- length(ExistingLinked) + 1
}
# Insert new values in existing slot
model$relations[[a_idx]]$affected_by[[group_idx]]$links[[c_idx]] <- NewEffect_ls
model$relations[[a_idx]]$affected_by[[group_idx]]$type <- input$relType
model$relations[[a_idx]]$k <- input$relK
} else {
# Create new slot for new affected concept at the end of the list
model$relations[[length(ExistingAffected) + 1]] <-
list(concept_id = AffectedConcept,
affected_by = list(list(links = list(NewEffect_ls), type = input$relType)),
k = input$relK)
}
# Reset flag for new relation
flag_newRelation <<- FALSE
# Show notification
showNotification(
ui = "Relationship added/ updated",
duration = 1,
closeButton = TRUE,
type = "message"
)
model$status$lastedit <- as.character(Sys.time())
}
)
# Implement the delete relation feature -----------------------------
observeEvent(
input$deleteRelation,
{
# Save last model state and relations inputs
saveLastState()
RowNum <- input$relationsTableEditing_rows_selected
# If no rows selected, print a warning
if (is.null(RowNum)){
notify("Select a row in the table to delete", type = "warning")
return(NULL)
}
# Remove relation from model
CausalConcept <-
model$concepts$concept_id[model$concepts$concept_id == input$causalConcept]
AffectedConcept <-
model$concepts$concept_id[model$concepts$concept_id == input$affectedConcept]
ExistingAffected<- unlist(lapply(model$relations, function(x) x$concept_id))
if ((length(ExistingAffected)>0) && (AffectedConcept %in% ExistingAffected)){
# Find where to delete
a_idx <- which(ExistingAffected == AffectedConcept)
g <- selectedfx$grouping[selectedfx$to == AffectedConcept]
links <- model$relations[[a_idx]]$affected_by[[g]]$links
ExistingLinked <- unlist(lapply(links, function(x) x$concept_id))
if (length(ExistingLinked)>0 && CausalConcept %in% ExistingLinked){
c_idx <- which(ExistingLinked == CausalConcept)
} else{
c_idx <- length(ExistingLinked) + 1
}
# Remove link, and if that was the only link, remove link group or/ and affected concept from the list of relations
model$relations[[a_idx]]$affected_by[[g]]$links[[c_idx]] <- NULL
if (length(model$relations[[a_idx]]$affected_by[[g]]$links) == 0){
model$relations[[a_idx]]$affected_by[[g]] <- NULL
if (length(model$relations[[a_idx]]$affected_by) == 0){
model$relations[[a_idx]] <- NULL
}
}
}
# Update text fields
updateTextInput(session, "causalDirection", value = "")
updateTextInput(session, "causalStrength", value = "")
updateTextInput(session, "causalDesc", value = "")
model$status$lastedit <- as.character(Sys.time())
}
)
# Undo relations edit -----------------------------
observeEvent(
input$undoRelationAction,
{
undoRelationEdit()
updateTextInput(session, "causalDirection",
value = selectedfx$direction[selectedfx$to == input$affectedConcept])
updateTextInput(session, "causalStrength",
value = selectedfx$strength[selectedfx$to == input$affectedConcept])
updateTextInput(session, "causalDesc",
value = selectedfx$description[selectedfx$to == input$affectedConcept])
model$status$lastedit <- as.character(Sys.time())
}
)
# Change edge weight values -----------------------------
observeEvent(
input$updateWeight,
{
model$weight_vals[input$qualWeight] <- input$quantWeight
}
)
# === IMPLEMENT MODEL RUNS ------- ================================================
# Get run parameters from UI -------------
run_params <- reactive({
k_df <- merge(model$concepts["concept_id"],
data.frame(concept_id=sapply(model$relations, "[[", "concept_id"),
k=sapply(model$relations, "[[", "k")), all.x = TRUE)
ks <- as.numeric(k_df$k)
names(ks) <- k_df$concept_id
list(h = input$sliderFCM_h, lambda = input$sliderFCM_lambda, k= ks,
init = input$sliderFCM_init, infer_type = input$selectFCM_fn,
iter = input$numIterations)
})
# Output: Define slider to select initial starting values --------
output$initSlider <- renderUI({
sliderInput("sliderFCM_init", "Initial values for simulation", min=clampSliderMin(), max=1, step = 0.25, value = 1)
})
# Output: Define dropdown element to select concept for constraining / clamping --------------
output$selectScenVar <- renderUI({
selectInput(
inputId = "scenVar",
label = "Select value to constrain/ clamp",
choices = sort(model$concepts$concept_id)
)
})
# Output: Define slider to select clamp value ------------
clampSliderMin <- reactive({
ifelse(input$selectFCM_fn == 'sigmoid-tanh',-1,0)
})
output$clampSlider <- renderUI({
sliderInput(
inputId = "scenVal",
label = "Value (fixed) throughout simulation",
min=clampSliderMin(), max=1, step = 0.5, value = 1)
})
# Save constraint for FCM ------------------
observeEvent(
input$addFCMConstraint,
{
if (length(run$constraints)==0){
run$constraints <- c()
}
run$constraints[input$scenVar] <- input$scenVal
}
)
# Delete constraint ------------------
observeEvent(
input$deleteFCMConstraint,
{
run$constraints <- run$constraints[which(names(run$constraints)!=input$scenVar)]
}
)
# Clear all constraints ------------------
observeEvent(
input$clearAllFCMConstraints,
{
run$constraints <- c()
}
)
# Run model ------------------
observeEvent(
input$runFCMAction,
{
if (is.null(model$relations)){
notify("No model loaded. Please load a model before proceeding.", type="warning")
} else{
run$parameters <- run_params()
run$results <- run_model(model, run$parameters, run$constraints, encode = TRUE)
# Change scenario name text when a new set of constraints/parameters are run
updateTextInput(session, "scenarioName",
value = isolate(scenarioNameString(run$parameters, run$constraints)))
# For reference, parameter list looks like:
# list(h = input$sliderFCM_h, lambda = input$sliderFCM_lambda, k= ks,
# init = input$sliderFCM_init, infer_type = input$selectFCM_fn,
# iter = 30)
}
}
)
# Run model with multiple parameters ------------------
# -Note: Right now this is set to run one set of parameter values-- eventually could do combinations of parameters, perhaps
extract <- function(text) {
text <- gsub(" ", "", text)
split <- strsplit(text, ",", fixed = FALSE)[[1]]
as.numeric(split)
}
# Text to display on the UI
output$sweepText <- renderText({
nums <- extract(input$sweepingVals)
if (anyNA(nums)) {
"Invalid input"
} else {
paste(c(input$sweepingParam,": ", paste(nums, collapse = ", ")), collapse = " ")
}
})
varying_params <- reactive({ # Default: list(lambda = c(0.5, 1, 3, 5)) - matching input$sweepingVals specified in ui.R
l <- list()
l[[input$sweepingParam]] <- extract(input$sweepingVals)
return(l)
})
output$sweepParam <- renderUI({
if (input$selectFCM_fn == "linear"){
param_choices <- c("h", "init")
} else {
param_choices <- c("lambda","h", "init")
}
selectInput("sweepingParam", label = "Parameter to sweep", choices = param_choices)
})
observeEvent(
input$runFCMSweepAction,
{
if (is.null(model$relations)){
notify("No model loaded. Please load a model before proceeding.", type="warning")
} else{
sweep <- run_parameter_sweep(model, isolate(run_params()), isolate(run$constraints),
varying_params = isolate(varying_params()))
run$sweep_params <- sweep$params
run$sweep_results <- sweep$results
run$sweep_constraints <- sweep$constraints
# run$parameters[pn] = "multiple"
}
}
)
# Define UI element to select concepts to constrain for set of runs -----
output$selectConceptsForScenarios <- renderUI({
selectizeInput(
inputId = "conceptsForScenarios",
label = "Test high/low scenarios for these concepts",
choices = sort(model$concepts$concept_id),
multiple = TRUE
)
})
# Run model with multiple constraints -----------
observeEvent(
input$runFCMMultipleConstraints, {
if (is.null(model$relations)){
notify("No model loaded. Please load a model before proceeding.", type="warning")
} else{
newScenarios <- run_auto_scenarios(model, run_params(), isolate(input$conceptsForScenarios), lowVal = clampSliderMin())
for (scenName in names(newScenarios$results)){
scenarios$results[[scenName]] <- newScenarios$results[[scenName]]
scenarios$constraints[[scenName]] <- newScenarios$constraints[[scenName]]
scenarios$parameters[[scenName]] <- newScenarios$parameters[[scenName]]
}
notify(paste0("Set of runs (high/ low for each concept) saved to scenario comparison list"))
run$constraints <- c() # clear constraints again
}
})
# Run monte carlo simulation ------------
observeEvent(
input$launchMonteCarlo, {
if (is.null(model$relations)){
notify("No model loaded. Please load a model before proceeding.", type="warning")
return(NULL)
} else {
mc_list <- run_monte_carlo(model, isolate(run_params()), isolate(run$constraints))
monte_carlo$models <- mc_list$models
monte_carlo$results <- parse_monte_carlo(mc_list$results)
}
}
)
# === SCENARIO SAVE/ LAUNCH COMPARISON VIEW --------- ====================================================
# Add current run to scenario comparison view ----
observeEvent(
input$addScenario,{
if (is.null(model$relations)){
notify("No model loaded. Please load a model before proceeding.", type="warning")
} else if (is.null(run$results)){
notify("Please run the model before proceeding.", type="warning")
} else {
scenarios$results[[input$scenarioName]] <- run$results
if (length(run$constraints)>0){
scenarios$constraints[[input$scenarioName]] <- c(run$constraints)
} else {
scenarios$constraints[[input$scenarioName]] <- "none"
}
scenarios$parameters[[input$scenarioName]] <- run$parameters
notify(paste0("Current run saved to scenario comparison list \n (", input$scenarioName, ")"))
}
}
)
# Add current parameter sweep runs to scenario comparison view ----
observeEvent(
input$addSweep,{
if (is.null(model$relations)){
notify("No model loaded. Please load a model before proceeding.", type="warning")
} else if (length(run$sweep_results)==0){
notify("Please run the model before proceeding.", type="warning")
} else {
if (length(run$sweep_constraints)>0){
constraints <- c(run$constraints)
} else {
constraints <- "none"
}
# Loop over all parameters run/ saved
for (i in 1:length(run$sweep_params)){
scenName <- scenarioNameString(run$sweep_params[[i]], run$sweep_constraints)
scenarios$results[[scenName]] <- run$sweep_results[[i]]
scenarios$constraints[[scenName]] <- constraints
scenarios$parameters[[scenName]] <- run$parameters
}
notify("Runs saved to scenario comparison list")
}
}
)
# Define UI element to select scenarios to plot
output$selectScenariosToPlot <- renderUI({
selectizeInput(
inputId = "scenariosToPlot",
label = "Compare these scenarios",
choices = sort(names(scenarios$results)),
multiple = TRUE
)
})
# Reset scenario view -----
observeEvent(
input$resetScenarios,{
scenarios$results <- list()
scenarios$constraints <- list()
scenarios$parameters <- list()
# Clear output?
}
)
# Save current scenarios into a file ----
observeEvent(
input$saveScenarios,{
if (length(scenarios$results) > 0){
scenarios_save <- list(results = scenarios$results,
constraints = scenarios$constraints,
parameters = scenarios$parameters)
saveDir <- file.path("models", model$status$name, "scenarios")
if (input$scenFileName == ""){
notify("Please enter a file name", type = "warning")
} else {
saveRDS(scenarios_save, file = file.path(saveDir, paste0(input$scenFileName,".rds")))
}
notify(paste("File saved in", saveDir))
} else {
notify("No results available to save", type = "warning")
}
}
)
# Load saved scenarios (overrides any scenarios that exist) ----
# Output: Define GUI element to select model from a list -----------------
output$selectExistingScenarioFiles<- renderUI({
selectInput(
inputId = "scenFileToLoad",