-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathccvi_app.R
1551 lines (1348 loc) · 59.9 KB
/
ccvi_app.R
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
# based on example app: https://github.com/daattali/shiny-server/blob/master/mimic-google-form/app.R
# and blog post explaining it: https://deanattali.com/2015/06/14/mimicking-google-form-shiny/
#' Create the ccviR Shiny application
#'
#'
#'
#' @noRd
ccvi_app <- function(testmode_in, ...){
# which fields are mandatory
fieldsMandatory1 <- c("assessor_name", "geo_location", "tax_grp", "species_name")
fieldsMandatory2 <- c("range_poly_pth", "assess_poly_pth")
# Input options
valueNms <- c("Greatly increase", "Increase", "Somewhat increase", "Neutral")
valueOpts <- c(3, 2, 1, 0)
# CSS to use in the app
appCSS <-
".mandatory_star { color: red; }
.shiny-input-container { margin-top: 25px; }
#submit_msg { margin-left: 15px; }
#error { color: red; }
body { background: #fcfcfc; }
#header { background: #fff; border-bottom: 1px solid #ddd; margin: -20px -15px 0; padding: 15px 15px 10px; }
"
# set theme
my_theme <- ggplot2::theme_classic() +
ggplot2::theme(text = ggplot2::element_text(size = 12),
strip.background = ggplot2::element_blank())
ggplot2::theme_set(my_theme)
# Header #=================================
ui <- function(request){
fluidPage(
shinyjs::useShinyjs(),
shinyjs::inlineCSS(appCSS),
title = "ccviR app",
tags$head(tags$style(type = "text/css",
".container-fluid { max-width: 1050px; /* or 1050px */}")),
div(id = "header",
h1("ccviR: An app to caluclate the NatureServe Climate Change Vulnerability Index"),
strong(
span("ccviR is a product developed and maintained by ECCC STB. This project is lead by Ilona Naujokaitis-Lewis and Sarah Endicott"),
br(),
span("Code"),
a("on GitHub", href = "https://github.com/see24/ccviR", target="_blank"),
HTML("•"),
a("ccviR website", href = "https://landscitech.github.io/ccviR/articles/app_vignette.html", target="_blank"),
HTML("•"),
a("NatureServe website", href = "https://www.natureserve.org/conservation-tools/climate-change-vulnerability-index", target="_blank"))
),
navlistPanel(
id = "tabset",
well = FALSE,
widths = c(3, 9),
# Introduction #===============
tabPanel(
"Welcome",
fluidPage(
h2("Welcome"),
p("This app provides a new interface for the Climate Change Vulnerability Index (CCVI) created by ",
a("NatureServe", href = "https://www.natureserve.org/conservation-tools/climate-change-vulnerability-index", target="_blank"),
"that automates the spatial analysis needed to inform the index. ",
"The app is based on version 3.02 of the NatureServe CCVI. ",
"See the app ",
a("tutorial", href = "https://landscitech.github.io/ccviR/articles/app_vignette.html", target="_blank"),
"for a demonstration of how to use the app. ",
"For detailed instructions on how to use the index and definitions ",
"of the terms used below see the ",
a("NatureServe Guidelines.", href = "https://www.natureserve.org/sites/default/files/guidelines_natureserveclimatechangevulnerabilityindex_r3.02_1_jun_2016.pdf", target="_blank"),
"Required datasets are indicated with ", labelMandatory("a"), "."),
h3("Preparing to use the app"),
p(strong("Step 0: "),"The first time you use the app you can either",
a("download", href = "https://drive.google.com/drive/folders/18mO5GDUmwi-nswhIAC36bmtYsvmqNQkH?usp=share_link", target="_blank"),
"a pre-prepared climate data set used in the app or",
" prepare your own using raw climate data and the ",
a("data preparation app.", href = "https://landscitech.github.io/ccviR/articles/data_prep_vignette.html", target="_blank")),
p(strong("Step 1: "), "Acquire species-specific spatial datasets:",
tags$ul(
tags$li(labelMandatory("Species North American or global range polygon")),
tags$li(labelMandatory("Assessment area polygon")),
tags$li("Non-breeding range polygon"),
tags$li("Projected range change raster"),
tags$li("Physiological thermal niche (PTN) polygon. ",
"PTN polygon should include cool or cold environments ",
"that the species occupies that may be lost or reduced ",
"in the assessment area as a result of climate change."))),
p(strong("Step 2: "), "Acquire species-specific sensitivity and life history data.",
"Including information about dispersal and movement ability, ",
"temperature/precipitation regime, dependence on disturbance events, ",
"relationship with ice or snow-cover habitats, physical",
" specificity to geological features or their derivatives, ",
"interactions with other species including diet and pollinator ",
"specificity, genetic variation, and phenological response to ",
"changing seasons. Recognizing that some of this information is",
" unknown for many species, the Index is designed such that only",
" 10 of the 19 sensitivity factors require input in order to ",
"obtain an overall Index score."),
h3("Start assessment"),
actionButton("start", "Start", class = "btn-primary"),
br(),
br(),
strong("Or load data from a previous assessment"),
br(),
#load_bookmark_ui("load"),
shinyFilesButton("loadcsv", "Select file", "Select file", multiple = FALSE),
br(),
strong("Download column definitions for saved data"),
br(),
downloadButton("downloadDefs", "Download csv"),
br(),
h3("Citation"),
p("Endicott S, Naujokaitis-Lewis I (2023). ",
em("ccviR: Calculate the NatureServe Climate Change Vulnerability ",
"Index in R. "),
"Environment and Climate Change Canada, Science and Technology ",
"Branch. ",
a("https://landscitech.github.io/ccviR/.", href = "https://landscitech.github.io/ccviR/")),
h3("References"),
p("Young, B. E., K. R. Hall, E. Byers, K. Gravuer, G. Hammerson,",
" A. Redder, and K. Szabo. 2012. Rapid assessment of plant and ",
"animal vulnerability to climate change. Pages 129-150 in ",
"Wildlife Conservation in a Changing Climate, edited by J. ",
"Brodie, E. Post, and D. Doak. University of Chicago Press, ",
"Chicago, IL."),
p("Young, B. E., N. S. Dubois, and E. L. Rowland. 2015. Using the",
" Climate Change Vulnerability Index to inform adaptation ",
"planning: lessons, innovations, and next steps. Wildlife ",
"Society Bulletin 39:174-181.")
)
),
# Species Info #===============
tabPanel(
"Species Information",
column(
width = 12,
div(
id = "form_sp_info",
h3("Species information"),
textInput("assessor_name", labelMandatory("Assessor Name"), ""),
textInput("geo_location", labelMandatory("Geographic Area Assessed")),
selectInput("tax_grp", labelMandatory("Major Taxonomic Group"),
c("Vascular Plant", "Nonvascular Plant", "Lichen",
"Invert-Insect", "Invert-Mollusk", "Invert-Other",
"Fish", "Amphibian", "Reptile", "Mammal", "Bird")),
textInput("species_name", labelMandatory("Species Scientific Name")),
textInput("common_name", "Common Name"),
checkboxInput("cave", "Check if the species is an obligate of caves or groundwater systems"),
checkboxInput("mig", "Check if species is migratory and you wish to enter exposure data for the migratory range that lies outside of the assessment area"),
actionButton("next1", "Next", class = "btn-primary"),
br(),br()
)
)
),
# Spatial Analysis #============
tabPanel(
"Spatial Data Analysis",
fluidRow(
column(
12,
div(
id = "spatial",
h3("Spatial data analysis"),
get_file_ui("clim_var_dir", "Folder location of prepared climate data",
type = "dir", mandatory = TRUE, spinner = TRUE),
verbatimTextOutput("clim_var_error", ),
br(),
get_file_ui("range_poly_pth", "Range polygon shapefile", mandatory = TRUE),
get_file_ui("assess_poly_pth", "Assessment area polygon shapefile", mandatory = TRUE),
get_file_ui("ptn_poly_pth", "Physiological thermal niche file"),
get_file_ui("nonbreed_poly_pth", "Non-breeding Range polygon shapefile"),
selectInput("rng_chg_used", "Will a projected range change raster be supplied?",
c("No" = "no",
"Yes, one range change raster will be supplied for all scenarios" = "one",
"Yes, multiple range change rasters will be supplied, one for each scenario (Preferred)" = "multiple")),
uiOutput("rng_chg_sel_ui"),
conditionalPanel(condition = "input.rng_chg_used !== 'no'",
strong("Classification of projected range change raster"),
p("Enter the range of values in the raster corresponding to ",
"lost, maintained, gained and not suitable."),
from_to_ui("lost", "Lost:", c(-1, -1)),
from_to_ui("maint", "Maintained:", c(0, 0)),
from_to_ui("gain", "Gained:", c(1,1)),
from_to_ui("ns", "Not Suitable:", c(99, 99)),
br(),
strong("Gain modifier"),
p("Range gains predicted based on future climate projections should be ",
"interpreted cautiously. It is important to consider whether ",
"the gains are likely to be realized. E.g. Is the species ",
"capable of dispersing to the new habitat and will factors other ",
"than climate be suitable in those areas?"),
p("To account for this you can set the gain modifier below to less",
" than 1 in order to down weight future range expansions when the",
" modelled response to climate change is being assessed. A value of 0 will ",
"ignore gains all together while 0.5 assumes that only half",
" the projected gains are realized and 1 assumes all gains are realized."),
numericInput("gain_mod", NULL, 1, min = 0, max = 1, step = 0.1),
textAreaInput("gain_mod_comm", "Gain modifier explanation")
),
strong("Click Run to begin the spatial analysis or to re-run it",
" after changing inputs"),
br(),
actionButton("startSpatial", "Run", class = "btn-primary"),
br(),
conditionalPanel(
condition = "input.startSpatial > 0",
shinycssloaders::withSpinner(verbatimTextOutput("spat_error"),
proxy.height = "50px"),
actionButton("next2", "Next", class = "btn-primary"),
br(), br()
)
)
)
)
),
# Exposure Results #====================================================
tabPanel(
"Exposure Results",
fluidRow(
column(
12,
# # helpful for testing
# shinyjs::runcodeUI(type = "textarea"),
p("Exposure is determined by the change in temperature or moisture",
" that is expected to occur in the future. The maps below are",
" created by taking historical climate - future climate and then",
" classifying the results into six categories using the median",
" and 1/2 the interquartile range. Thus, negative values for",
" temperature indicate warmer conditions (\u00B0C) and negative values for",
" moisture (mm) indicate drier conditions."),
div(
id = "texp_map_div",
h3("Temperature exposure"),
shinycssloaders::withSpinner(leaflet::leafletOutput("texp_map")),
tableOutput("texp_tbl")
),
div(
id = "cmd_map_div",
h3("Moisture exposure"),
leaflet::leafletOutput("cmd_map"),
tableOutput("cmd_tbl")
),
div(
h3("Migratory exposure - Climate change exposure index"),
div(id = "missing_ccei",
HTML("<font color=\"#FF0000\"><b>Data set not provided.</b></font> <br>CCEI data and a non-breeding range are needed to calculate."),
br(),
br()),
div(
id = "ccei_exp",
leaflet::leafletOutput("ccei_map"),
tableOutput("tbl_ccei"))
)
)
),
fluidRow(
column(
12,
actionButton("next3", "Next", class = "btn-primary"),
br(), br()
)
)
),
# Section B questions #=================
tabPanel(
"Vulnerability Questions",
fluidRow(
column(
12,
h3("Vulnerability Questions"),
div(
id = "secB",
h4("Section B: Indirect Exposure to Climate Change"),
h4("Evaluate for specific geographical area under consideration"),
h5("Factors that influence vulnerability"),
check_comment_ui("B1", "1) Exposure to sea level rise:",
choiceNames = valueNms,
choiceValues = valueOpts),
check_comment_ui("B2a", "2a) Distribution relative to natural barriers",
choiceNames = valueNms,
choiceValues = valueOpts),
check_comment_ui("B2b", "2b) Distribution relative to anthropogenic barriers",
choiceNames = valueNms,
choiceValues = valueOpts),
check_comment_ui("B3", " 3) Predicted impact of land use changes resulting from human responses to climate change",
choiceNames = valueNms[2:4],
choiceValues = valueOpts[2:4])
)
)
),
# Section C questions #=============================
fluidRow(
column(
12,
div(
id = "secC",
h4("Section C: Sensitivity and Adaptive Capacity"),
check_comment_ui("C1", "1) Dispersal and movements",
choiceNames = valueNms,
choiceValues = valueOpts),
strong("2b) Predicted sensitivity to changes in precipitation, hydrology, or moisture regime:"),
check_comment_ui("C2bii", "ii) physiological hydrological niche.",
choiceNames = valueNms,
choiceValues = valueOpts),
check_comment_ui("C2c", "2c) Dependence on a specific disturbance regime likely to be impacted by climate change.",
choiceNames = valueNms[2:4],
choiceValues = valueOpts[2:4]),
check_comment_ui("C2d", "2d) Dependence on ice, ice-edge, or snow-cover habitats.",
choiceNames = valueNms,
choiceValues = valueOpts),
check_comment_ui("C3", "3) Restriction to uncommon landscape/geological features or derivatives.",
choiceNames = valueNms[2:4],
choiceValues = valueOpts[2:4]),
check_comment_ui("C4a", "4a) Dependence on other species to generate required habitat.",
choiceNames = valueNms[2:4],
choiceValues = valueOpts[2:4]),
shinyjs::hidden(
div(
id = "animal_only",
check_comment_ui("C4b", "4b) Dietary versatility (animals only).",
choiceNames = valueNms[2:4],
choiceValues = valueOpts[2:4])
)
),
shinyjs::hidden(
div(
id = "plant_only",
check_comment_ui("C4c", "4c) Pollinator versatility (plants only).",
choiceNames = valueNms[2:4],
choiceValues = valueOpts[2:4])
)
),
check_comment_ui("C4d", "4d) Dependence on other species for propagule dispersal.",
choiceNames = valueNms[2:4],
choiceValues = valueOpts[2:4]),
check_comment_ui("C4e", "4e) Sensitivity to pathogens or natural enemies.",
choiceNames = valueNms[2:4],
choiceValues = valueOpts[2:4]),
check_comment_ui("C4f", "4f) Sensitivity to competition from native or non-native species.",
choiceNames = valueNms[2:4],
choiceValues = valueOpts[2:4]),
check_comment_ui("C4g", "4g) Forms part of an interspecific interaction not covered by 4a-f.",
choiceNames = valueNms[2:4],
choiceValues = valueOpts[2:4]),
check_comment_ui("C5a", "5a) Measured genetic variation.",
choiceNames = valueNms[2:4],
choiceValues = valueOpts[2:4]),
conditionalPanel(
"input.C5a == ''",
check_comment_ui("C5b", "5b) Occurrence of bottlenecks in recent evolutionary history (use only if 5a is unknown).",
choiceNames = valueNms[2:4],
choiceValues = valueOpts[2:4]),
),
conditionalPanel(
"input.C5a == '' && input.C5b == ''",
shinyjs::hidden(
div(
id = "plant_only2",
check_comment_ui("C5c", "5c) Reproductive system (plants only; use only if C5a and C5b are unknown).",
choiceNames = valueNms[2:4],
choiceValues = valueOpts[2:4])
)
)
),
check_comment_ui("C6", "6) Phenological response to changing seasonal temperature and precipitation dynamics.",
choiceNames = valueNms[2:4],
choiceValues = valueOpts[2:4])
)
)
),
# Section D questions #=============================
fluidRow(
column(
12,
div(
id = "secD",
h4("Section D: Documented or Modeled Response to Climate Change"),
h5("(Optional; May apply across the range of a species)"),
check_comment_ui("D1", "1) Documented response to recent climate change. ",
choiceNames = valueNms,
choiceValues = valueOpts),
check_comment_ui("D4", "4) Occurrence of protected areas in modeled future distribution.",
choiceNames = valueNms[2:4],
choiceValues = valueOpts[2:4]),
actionButton("next4", "Next", class = "btn-primary"),
br(), br()
)
)
)
),
# Spatial Vulnerability Questions #================================
tabPanel(
"Spatial Vulnerability Questions",
fluidRow(
column(
12,
h3("Spatial Vulnerability Questions"),
h4("Section C: Sensitivity and Adaptive Capacity"),
br(),
spat_vuln_ui(
id = "C2ai",
header = "Predicted sensitivity to temperature and moisture changes:",
vuln_q_nm = "2a) i) Historical thermal niche."
),
spat_vuln_ui(
id = "C2aii",
vuln_q_nm = "2a) ii) Physiological thermal niche."
),
spat_vuln_ui(
id = "C2bi",
vuln_q_nm = "2b) i) Historical hydrological niche."
),
h4("Section D: Documented or Modeled Response to Climate Change"),
br(),
spat_vuln_ui(
id = "D2_3",
header = "Modeled future range change",
chk_box = FALSE
),
fluidRow(column(9, strong("2) Modeled future (2050) change in population or range size.")),
column(1, actionButton(paste0("help_", "D2"), label = "", icon = icon("info")))),
uiOutput("box_D2"),
fluidRow(column(9, strong("3) Overlap of modeled future (2050) range with current range"),),
column(1, actionButton(paste0("help_", "D3"), label = "", icon = icon("info")))),
uiOutput("box_D3"),
actionButton("next5", "Next", class = "btn-primary")
)
)
),
# Results #===================================
tabPanel(
"Index Results",
fluidPage(
div(
id = "formData",
#style = 'width:800px;',
h3("Results"),
h5("Click the button to calculate or re-calculate the index"),
actionButton("calcIndex", "Calculate", class = "btn-primary")
),
conditionalPanel(
condition = "output.calcFlag == true",
h4("Data completeness"),
tableOutput("n_factors"),
h4("Variation in index"),
p("When multiple values are selected for any of the vulnerability ",
"factors the average of the values is used to calculate the ",
"overall index. To test the uncertainty in the result a Monte Carlo ",
"simulation with 1000 runs is carried out. In each simulation run ",
"one of the selected values is randomly chosen and the index is ",
"calculated. The graph below shows the proportion of runs with each",
" index value for each scenario. "),
# p("Confidence in the index is:",
# textOutput("conf_index", inline = TRUE)),
plotOutput("conf_graph", width = 300, height = 200),
div(
id = "indplt",
#style = 'width:800px;',
br(),
h4("Factors contributing to index value"),
p("The CCVI is calculated by combining the index calculated based on ",
"exposure, sensitivity and adaptive capacity with the index ",
"calculated based on documented or modelled responses to climate change. ",
"The plot below demonstrates which of these had the strongest",
"influence on the overall calculated index. The lines indicate",
" the range of scores produced by the Monte Carlo simulations. ",
"A score of negative one on the vertical ",
"axis indicates none of the factors in the modelled response to",
" climate change section were completed"),
# Might want to add something like this to change width dependent
# on n facets https://stackoverflow.com/questions/50914398/increase-plot-size-in-shiny-when-using-ggplot-facets
plotOutput("ind_score_plt", height = "300px"),
textOutput("slr"),
br(), br(),
p("The score for each vulnerability factor is determined by the ",
"answers to vulnerability questions (Neutral: 0, Greatly increases: 3)",
"multiplied by the exposure multiplier for temperature or moisture,",
"whichever is most relevant to that factor. When multiple values ",
"are selected for any of the vulnerability ",
"factors the average of the values is used. These scores are summed ",
"to determine the index. The plot below demonstrates which factors ",
"had the highest scores and how exposure impacted the score."),
plotly::plotlyOutput("q_score_plt")
),
br(),
br(),
actionButton("restart", "Assess another species",
class = "btn-primary"),
br(),
br(),
downloadButton("report", "Generate report", class = "btn-primary"),
)
)
)
),
div(
id = "footer",
style = "float:right",
br(), br(), br(), br(),
shinySaveButton("downloadData", "Save progress", "Save app data as a csv file",
class = "btn-primary", icon = shiny::icon("save")),
br(),
br(),
br())
)
}
# Server #========================
server <- function(input, output, session) {
file_pths <- NULL
# start up Note this time out is because when I disconnected from VPN it
# made the getVolumes function hang forever because it was looking for
# drives that were no longer connected. Now it will give an error
timeout <- R.utils::withTimeout({
volumes <- c(wd = getShinyOption("file_dir"),
Home = fs::path_home(),
getVolumes()())
}, timeout = 200, onTimeout = "silent")
if(is.null(timeout)){
stop("The app is unable to access your files because you were connected",
" to the VPN and then disconnected. To fix this either reconnect to",
" the VPN or restart your computer and use the app with out connecting",
" to VPN. See issue https://github.com/see24/ccviR/issues/36 for more ",
"information", call. = FALSE)
}
observeEvent(input$start, {
updateTabsetPanel(session, "tabset",
selected = "Species Information"
)
shinyjs::runjs("window.scrollTo(0, 0)")
})
# restore a previous session
shinyFileChoose("loadcsv", root = volumes, input = input,
filetypes = "csv")
index_res <- reactiveVal(FALSE)
spat_res <- reactiveVal(FALSE)
file_pths <- reactiveVal()
clim_dir_pth <- reactiveVal()
# Restore from saved file #=================================================
restored_df <- eventReactive(input$loadcsv, {
if(!is.integer(input$loadcsv)){
df_loaded <- read.csv(parseFilePaths(volumes, input$loadcsv)$datapath)
update_restored(df_loaded, session)
if(!is.null(df_loaded$MAT_6)){
df_spat <- apply_spat_tholds(df_loaded, df_loaded$cave)
spat_res(df_spat)
}
index_res(recreate_index_res(df_loaded))
loaded_pths <- df_loaded %>% slice(1) %>%
select(contains("pth"), -any_of("clim_dir_pth")) %>%
as.list()
if(length(loaded_pths)>0){
file_pths(loaded_pths)
}
clim_dir_pth(df_loaded %>% slice(1) %>% .$clim_dir_pth)
updateTabsetPanel(session, "tabset",
selected = "Species Information"
)
shinyjs::runjs("window.scrollTo(0, 0)")
return(TRUE)
}
})
observeEvent(restored_df(), {
showNotification("Successfully restored from file.", duration = 10)
})
# Species Info #=================
# Enable the Submit button when all mandatory fields are filled out
observe({
mandatoryFilled <-
vapply(fieldsMandatory1,
function(x) {
!is.null(input[[x]]) && input[[x]] != ""
},
logical(1))
mandatoryFilled <- all(mandatoryFilled)
shinyjs::toggleState(id = "next1", condition = mandatoryFilled)
})
# When next button is clicked move to next panel
observeEvent(input$next1, {
updateTabsetPanel(session, "tabset",
selected = "Spatial Data Analysis"
)
shinyjs::runjs("window.scrollTo(0, 0)")
})
observe({
tax_lg <- ifelse(input$tax_grp %in% c("Vascular Plant", "Nonvascular Plant"),
"Plant",
ifelse(
input$tax_grp == "Lichen",
"Lichen",
"Animal"
))
if(tax_lg == "Plant"){
shinyjs::show("plant_only")
shinyjs::show("plant_only2")
shinyjs::hide("animal_only")
}
if(tax_lg == "Animal"){
shinyjs::show("animal_only")
shinyjs::hide("plant_only")
shinyjs::hide("plant_only2")
}
if(tax_lg == "Lichen"){
shinyjs::hide("animal_only")
shinyjs::hide("plant_only")
shinyjs::hide("plant_only2")
}
})
# Spatial Analysis #===============
toListen <- reactive({
purrr::map(filePathIds(), \(x){input[[x]]})
})
observeEvent(toListen(),{
pths_in <- file_pths()
purrr::walk(filePathIds(),
\(x) if(!is.integer(input[[x]])){
pths_in[[x]] <<- parseFilePaths(volumes, input[[x]])$datapath
})
file_pths(pths_in)
})
# clear output filepaths when x clicked
toClear <- reactive({
purrr::map(paste0(filePathIds(), "_clear"), \(x){input[[x]]})
})
observeEvent(toClear(),{
buttonIds <- paste0(filePathIds(), "_clear")
pths_in <- file_pths()
purrr::walk(buttonIds,
\(x){ if(input[[x]] > 0){
fl_x <- stringr::str_extract(x, "(.*)(_clear)", group = 1)
pths_in[[fl_x]] <<- ""
}})
file_pths(pths_in)
}, ignoreInit = TRUE)
# Enable the Submit button when all mandatory fields are filled out
observe({
mandatoryFilled2 <-
vapply(fieldsMandatory2,
function(x) {
isTruthy(file_pths()[[x]]) & isTruthy(clim_dir_pth())
},
logical(1))
mandatoryFilled2 <- all(mandatoryFilled2)
if (isTRUE(getOption("shiny.testmode"))) {
mandatoryFilled2 <- TRUE
}
shinyjs::toggleState(id = "startSpatial", condition = mandatoryFilled2)
})
# update filePathIds based on selection for rng_chg
filePathIds <- reactive({
# File path ids to use with file choose
fileIds <- c("range_poly_pth", "nonbreed_poly_pth", "assess_poly_pth", "ptn_poly_pth")
names(fileIds) <- fileIds
rng_chg_pths <- stringr::str_subset(names(input), "rng_chg_pth_\\d$|rng_chg_pth$")
if(length(rng_chg_pths) > 0){
names(rng_chg_pths) <- rng_chg_pths
return(c(fileIds, rng_chg_pths))
} else {
return(fileIds)
}
})
# Find file paths
shinyDirChoose(input, "clim_var_dir", root = volumes)
observe({
purrr::map(filePathIds(), shinyFileChoose, root = volumes, input = input,
filetypes = c("shp", "tif", "asc", "nc", "grd", "bil"))
})
# parse file paths
observeEvent(input$clim_var_dir,{
if(is.integer(input$clim_var_dir)){
if (isTRUE(getOption("shiny.testmode"))) {
pth <- system.file("extdata/clim_files/processed", package = "ccviR")
} else {
return(NULL)
}
} else {
pth <- parseDirPath(volumes, input$clim_var_dir)
}
clim_dir_pth(pth)
})
observeEvent(input$clim_var_dir_clear, {
clim_dir_pth(NULL)
})
# output file paths
output$clim_var_dir_out <- renderText({
clim_dir_pth()
})
observe({
purrr::walk2(file_pths(), filePathIds()[names(file_pths())], ~{
out_name <- paste0(.y, "_out")
output[[out_name]] <- renderText({.x})
})
})
# load spatial data
clim_readme <- reactive({
req(clim_dir_pth())
if(!file.exists(fs::path(clim_dir_pth(), "climate_data_readme.csv"))){
stop("The climate folder is missing the required climate_data_readme.csv file",
call. = FALSE)
}
utils::read.csv(fs::path(clim_dir_pth(), "climate_data_readme.csv"),
check.names = FALSE)
})
clim_vars <- reactive({
root_pth <- clim_dir_pth()
req(root_pth)
req(clim_readme)
clim_vars <- try(get_clim_vars(root_pth, scenario_names = clim_readme()$Scenario_Name))
})
range_poly_in <- reactive({
if (isTRUE(getOption("shiny.testmode"))) {
sf::st_read(system.file("extdata/rng_poly.shp",
package = "ccviR"),
agr = "constant", quiet = TRUE)
} else {
sf::st_read(file_pths()$range_poly_pth,
agr = "constant", quiet = TRUE)
}
})
nonbreed_poly <- reactive({
if (isTRUE(getOption("shiny.testmode"))) {
# not currently included in package
# pth <- system.file("extdata/nonbreed_poly.shp",
# package = "ccviR")
pth <- file_pths()$nonbreed_poly_pth
} else {
pth <- file_pths()$nonbreed_poly_pth
}
if(!isTruthy(pth)){
return(NULL)
}
sf::st_read(pth, agr = "constant", quiet = TRUE)
})
assess_poly <- reactive({
if (isTRUE(getOption("shiny.testmode"))) {
sf::st_read(system.file("extdata/assess_poly.shp",
package = "ccviR"),
agr = "constant", quiet = TRUE)
} else {
sf::st_read(file_pths()$assess_poly_pth,
agr = "constant", quiet = TRUE) %>%
valid_or_error("assessment area polygon")
}
})
# use readme to render scenario names for rng chg rasters
output$rng_chg_sel_ui <- renderUI({
if(input$rng_chg_used == "no"){
return(NULL)
} else if(input$rng_chg_used == "one"){
get_file_ui("rng_chg_pth", "Projected range change raster")
} else if (input$rng_chg_used == "multiple"){
tagList(
strong("Select a projected range change raster for each scenario"),
purrr::map2(clim_readme()$Scenario_Name,
1:length(clim_readme()$Scenario_Name),
~get_file_ui(paste0("rng_chg_pth", "_", .y), .x)),
br(), br()
)
}
})
# doing this rather than eventReactive so that it still has a value (NULL)
# if shinyalert is not called
hs_rast <- reactiveVal()
observeEvent(input$shinyalert, {
if (isTRUE(getOption("shiny.testmode"))) {
pth <- system.file("extdata/rng_chg_45.tif",
package = "ccviR")
} else {
pth <- file_pths()[stringr::str_subset(names(input), "rng_chg_pth")] %>%
unlist()
pth <- pth[sort(names(pth))]
}
if(!isTruthy(pth) || length(pth) == 0){
return(NULL)
}else {
names(pth) <- fs::path_file(pth) %>% fs::path_ext_remove()
out <- check_trim(terra::rast(pth))
hs_rast(out)
}
})
ptn_poly <- reactive({
if (isTRUE(getOption("shiny.testmode"))) {
pth <- system.file("extdata/PTN_poly.shp", package = "ccviR")
} else {
pth <- file_pths()$ptn_poly_pth
}
if(!isTruthy(pth)){
return(NULL)
}
sf::st_read(pth, agr = "constant", quiet = TRUE)
})
# assemble hs_rcl matrix
hs_rcl_mat <- reactive({
mat <- matrix(c(input$lost_from, input$lost_to, 1,
input$maint_from, input$maint_to, 2,
input$gain_from, input$gain_to, 3,
input$ns_from, input$ns_to, 0),
byrow = TRUE, ncol = 3)
# if an input is blank then the value is NA but that converts raster values that
# are NA to that value
mat[which(!is.na(mat[, 1])), ]
})
doSpatial <- reactiveVal(FALSE)
repeatSpatial <- reactiveVal(FALSE)
observe({
if(!is.null(restored_df())){
repeatSpatial(TRUE)
message("doSpatial restore")
}
})
observeEvent(input$startSpatial, {
showModal(modalDialog(
p("Note: Re-running the spatial analysis will overwrite any changes made to ",
"the Spatial Vulnerability Questions. Comments will be preserved so ",
"you can record the change made in the comments and then change it ",
"again after re-running the analysis."),
footer = tagList(
actionButton("shinyalert", "Continue"),
modalButton("Cancel")
),
title = "Do you want to run the spatial analysis?"))
if(!repeatSpatial()){
shinyjs::click("shinyalert")
}
})
observeEvent(input$shinyalert, {
removeModal()
if(input$shinyalert > 0){
doSpatial(TRUE)
repeatSpatial(TRUE)
}
shinyjs::runjs("window.scrollTo(0, document.body.scrollHeight)")
})
# run spatial calculations
spat_res1 <- eventReactive(input$shinyalert, {
req(doSpatial())
req(clim_vars())
tryCatch({
analyze_spatial(range_poly = range_poly_in(),
non_breed_poly = nonbreed_poly(),
scale_poly = assess_poly(),
hs_rast = hs_rast(),
ptn_poly = ptn_poly(),
clim_vars_lst = clim_vars(),
hs_rcl = hs_rcl_mat(),
gain_mod = input$gain_mod,
scenario_names = clim_readme()$Scenario_Name)
},
error = function(cnd) conditionMessage(cnd))
})
range_poly <- reactive({
req(range_poly_in())
req(doSpatial())
req(!is.character(spat_res1()))
spat_res1()$range_poly_assess
})
range_poly_clim <- reactive({
req(doSpatial())
req(!is.character(spat_res1()))
spat_res1()$range_poly_clim
})
observe({
req(doSpatial())
req(!is.character(spat_res1()))
spat_res(spat_res1()$spat_table)
})
output$clim_var_error <- renderText({
if(inherits(clim_vars(), "try-error")){
stop(conditionMessage(attr(clim_vars(), "condition")))
}
})
output$spat_error <- renderText({
if(inherits(hs_rast(), "try-error")){
stop("Error in range change raster",
conditionMessage(attr(hs_rast(), "condition")))
}
if(is.character(spat_res1())){
stop(spat_res1(), call. = FALSE)
} else {
"Spatial analysis complete"
}
})
# When next button is clicked move to next panel
observeEvent(input$next2, {
updateTabsetPanel(session, "tabset",
selected = "Exposure Results"
)
shinyjs::runjs("window.scrollTo(0, 0)")
})
# calculate exp multipliers and vuln Q values for spat
spat_res2 <- reactiveVal(FALSE)
observe({
req(!is.character(spat_res()))
req(spat_res())
spat_res2(apply_spat_tholds(spat_res(), input$cave))
})
# Exposure maps #=========================================================
output$texp_map <- leaflet::renderLeaflet({
req(!is.character(spat_res()))
req(doSpatial())