Repository navigation
Expand file tree
/
Copy pathserver.R
More file actions
1479 lines (1281 loc) · 57.1 KB
/
Copy pathserver.R
File metadata and controls
1479 lines (1281 loc) · 57.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
#### Server ####
server <- function(input, output, session) {
# Store the main session in userData for module access
session$userData$parent_session <- session
# Call secure_server to check credentials
#Comment out for local testing without credentials
# res_auth <- secure_server(
# check_credentials = check_credentials(
# db = "setup/credentials.sqlite",
# passphrase = Sys.getenv("DB_PASSWORD")
# )
# )
#setup loaded data
loaded_data <- reactiveVal(NULL)
# Initialize home module
home_state <- home_server("home", loaded_data
, auth = res_auth) #comment our auth for local testing without credentials
#un comment line below for production with credentials:
# , auth = list( user = "user_name"))
# Sidebar Gating Logic
observe({
# List of tabs to disable until full sync is complete
tabs_to_gate <- c("sensor_data", "flow_data", "toc_forecasts")
if (home_state$full_sync_done()) {
for (tab in tabs_to_gate) {
shinyjs::removeCssClass(selector = paste0("a[data-value='", tab, "']"), class = "disabled-menu")
# Remove the tooltip from the parent list item
shinyjs::runjs(sprintf("$('a[data-value=\"%s\"]').parent('li').removeAttr('title');", tab))
}
} else {
for (tab in tabs_to_gate) {
shinyjs::addCssClass(selector = paste0("a[data-value='", tab, "']"), class = "disabled-menu")
# Add a tooltip to the parent list item (since pointer-events: none on the <a> disables its own tooltips)
shinyjs::runjs(sprintf("$('a[data-value=\"%s\"]').parent('li').attr('title', 'Select the Initialize Data button to proceed to the detailed data pages');", tab))
}
}
})
# Reactive values for storing data
values <- reactiveValues(
all_data = NULL,
flow_sites = NULL,
clp_snotel_data = NULL,
snotel_error = NULL,
canyon_q = NULL,
last_refresh = Sys.time()
)
#TODO: This is done at load up, should it be moved to global?
#### Pre loading API/Cached Data ####
observeEvent(home_state$start_sync(), {
req(home_state$start_sync() > 0)
# "message" is the bold title, "detail" is the printed talking point
withProgress(message = "Dashboard Initialization", detail = "Starting up...", value = 0, {
print("--- STARTING DATA INITIALIZATION ---")
incProgress(0.1, detail = "Retrieving pre-loaded data...")
# Use the data already loaded by the home module
cached_data <- home_state$cached_df()
print(paste("Pre-loaded data retrieved. Total records:", nrow(cached_data)))
#### ---- WET API PULL ---- ####
home_state$set_status("wet_api", "loading")
incProgress(0.15, detail = "Importing ROSS radio telemetry data (WET API)...")
print("Calculating max datetimes in cached dataset by site...")
max_dts <- cached_data %>%
summarise(max_DT = max(DT_round, na.rm = TRUE), .by = "site")
# We pull data up to the end of the current day for initialization
end_DT <- as.POSIXct(paste0(Sys.Date(), " 23:55"), tz = "America/Denver")
wet_sites <- c("sfm", "chd", "pfal")
invalid_values <- c(-9999, 638.30, -99.99)
site_start_DT <- filter(max_dts, site %in% wet_sites) %>%
mutate(max_cached_DT = with_tz(max_DT, "America/Denver"))
print(paste("Target WET sites identified:", paste(site_start_DT$site, collapse = ", ")))
if(nrow(site_start_DT) > 0) {
print("Initiating WET API puller. This may take a moment depending on network connection...")
wet_data_raw <- map2(site_start_DT$site, site_start_DT$max_cached_DT,
function(s, dt) {
print(paste(" -> Pulling", s, "from", dt, "to", end_DT))
pull_wet_api(
target_site = s,
start_datetime = dt,
end_datetime = end_DT
)
}) %>%
rbindlist()
print(paste("WET API pull returned", nrow(wet_data_raw), "raw rows."))
print("Cleaning WET data (removing invalid values and NAs)...")
wet_data <- wet_data_raw %>%
filter(value %nin% invalid_values, !is.na(value)) %>%
split(f = list(.$site, .$parameter), sep = "-")
print("WET data cleaning and splitting complete.")
} else {
print("No WET sites identified. Skipping pull.")
wet_data <- list()
}
home_state$set_status("wet_api", "done")
#### ---- HYDROVU API PULL---- ####
incProgress(0.1, detail = "Retrieving HydroVu data...")
home_state$set_status("hydrovu_api", "loading")
hv_site <- c("pbd")
# Grab Sys.time()
t <- Sys.time()
# Make the start/end time in UTC
utc_start_DT <- with_tz(filter(max_dts, site %in% hv_site) %>% pull(max_DT) , "UTC")
utc_end_DT <- lubridate::with_tz(t, "UTC")
print(paste("Target HV sites identified:", paste(hv_site, collapse = ", ")))
if(length(utc_start_DT) > 0) {
print("Initiating HV API puller. This may take a moment depending on network connection...")
staging_directory = tempdir()
client_creds <- read_yaml("creds/HydroVuCreds.yml")
# Read in credentials from environment variables (GitHub Secrets)
client_id <- client_creds$client
client_secret <- client_creds$secret
# Check if credentials are available
if(client_id == "" || client_secret == "") {
stop("HydroVu credentials not found. Please check GitHub Secrets.")
} else {
message(paste("....Collation Step Update:", "HydroVu secrets retrieved"))
}
hv_token <- tryCatch({
hv_auth(client_id = client_id, client_secret = client_secret)
}, error = function(e) {
message("HydroVu authentication failed: ", e$message)
return(NULL)
})
if(is.null(hv_token)) {
stop("Could not authenticate with HydroVu API. Check credentials and API status.")
}
# Pulling in the data from hydrovu
hv_sites <- hv_locations_all(hv_token) %>%
filter(grepl("pbd", name, ignore.case = TRUE))%>%
filter(!grepl("2023|2024", name, ignore.case = TRUE))%>%
filter(!grepl("Vulink", name, ignore.case = TRUE))
message(paste("....Collation Step Update:", "Attempting to pull data from HydroVu API"))
walk(hv_site,
function(site) {
message("Requesting HV data for: ", hv_site)
ross.wq.tools::api_puller(
site = hv_site,
start_dt = utc_start_DT,
end_dt = utc_end_DT,
api_token = hv_token,
hv_sites_arg = hv_sites,
dump_dir = staging_directory
)
}
)
hv_data <- ross.wq.tools::munge_api_data(api_dir = staging_directory) %>%
distinct(.keep_all = TRUE)%>%
split(f = list(.$site, .$parameter), sep = "-") %>%
keep(~nrow(.) > 0)
print(paste("HV API pull returned", nrow(hv_data$`pbd-Temperature`), "raw rows."))
print("Cleaning HV data (removing invalid values and NAs)...")
} else {
print("No HV sites identified. Skipping pull.")
hv_data <- list()
}
home_state$set_status("hydrovu_api", "done")
#### ---- CONTRAIL API PULL ---- ####
home_state$set_status("contrail_api", "loading")
incProgress(0.1, detail = "Retrieving Contrail data...")
contrail_sites <- c( "pman_fc", "pbr_fc")
denver_contrail_start_DT <- filter(max_dts, site %in% contrail_sites) %>%
mutate(max_cached_DT = with_tz(max_DT, "America/Denver"))%>%
#grab the oldest one
slice_min(order_by = max_cached_DT)%>%
pull(max_cached_DT)
denver_contrail_end_DT <- with_tz(utc_end_DT, tz = "America/Denver")
print("Pulling Contrail data...")
contrail_creds <- read_yaml("creds/ContrailCreds.yml")
if(contrail_creds$username == "" || contrail_creds$password == "" || contrail_creds$login_url == "") {
message("Contrail credentials not found. ")
contrail_data <- list()
} else {
message(paste("....Collation Step Update:", "Contrail credentials retrieved"))
contrail_data <- tryCatch(
{
pull_contrail_api(
start_DT = denver_contrail_start_DT,
end_DT = denver_contrail_end_DT,
username = contrail_creds$username,
password = contrail_creds$password,
login_url = contrail_creds$login_url
)
},
error = function(e) {
message("Contrail API pull failed: ", conditionMessage(e))
list()
}
)
}
home_state$set_status("contrail_api", "done")
#### ---- CDWR FLOW API PULL ---- ####
home_state$set_status("cdwr_flow_api", "loading")
incProgress(0.15, detail = "Retrieving CDWR flow sites data...")
print("Pulling CDWR flow data for map/flow charts...")
tryCatch({
sites <- read_csv(file = "data/cdwr_sites_oi.csv", show_col_types = F)
if (nrow(sites) > 0) {
end_date <- as.character(Sys.Date() + days(1))
start_date <- as.character(Sys.Date() - days(7))
flow_sites_res <- sites %>%
split(1:nrow(.)) %>%
map_dfr(function(site_row) {
site_id <- site_row$abbrev
param_code <- site_row$parameter
make_empty_row <- function(msg = "No Data") {
site_row %>%
as_tibble() %>%
mutate(
current_flow_cfs = NA_real_,
flow_slope = NA_real_,
trend = msg,
nested_data = list(tibble(DT_round = as.POSIXct(character()), flow = numeric(), abbrev = character()))
) %>%
select(abbrev, station_name, data_source, water_source, gnis_id, latitude, longitude,
current_flow_cfs, flow_slope, trend, structure_type, site_type = station_type, nested_data)
}
result <- tryCatch({
flow_data <- get_telemetry_ts(
abbrev = site_id,
parameter = param_code,
start_date = start_date,
end_date = end_date,
api_key = cdwr_api_key,
timescale = "raw"
) %>%
mutate(DT_round = round_date(datetime, "15 min")) %>%
group_by(DT_round) %>%
summarise(flow = mean(meas_value, na.rm = TRUE), .groups = "drop") %>%
mutate(abbrev = site_id)
if (nrow(flow_data) == 0) return(make_empty_row("No Records"))
end_time <- Sys.time()
start_time_24h <- end_time - hours(24)
iv_data <- flow_data %>% filter(DT_round >= start_time_24h & DT_round <= end_time)
if (nrow(iv_data) >= 2) {
flow_model <- lm(flow ~ DT_round, data = iv_data)
slope <- coef(flow_model)[2]
current_flow <- iv_data %>%
arrange(DT_round) %>%
slice_tail(n = 1) %>%
pull(flow)
site_row %>%
as_tibble() %>%
mutate(
current_flow_cfs = current_flow,
flow_slope = slope * 3600,
trend = if_else(current_flow_cfs == 0, "NoFlow",
if_else(flow_slope > 0, "increasing", "decreasing")),
nested_data = list(flow_data)
) %>%
select(abbrev, station_name, data_source, water_source, gnis_id, latitude, longitude,
current_flow_cfs, flow_slope, trend, structure_type, site_type = station_type, nested_data)
} else {
make_empty_row("Insufficient Data for Trend")
}
}, error = function(e) {
make_empty_row("API Error/No Records")
})
return(result)
})
values$flow_sites <- flow_sites_res
print(paste("CDWR flow data pulled successfully for", nrow(flow_sites_res), "sites."))
}
}, error = function(e) {
print(paste("CDWR Error:", e$message))
})
home_state$set_status("cdwr_flow_api", "done")
#### ---- SNOTEL API PULL ---- ####
home_state$set_status("snotel_api", "loading")
incProgress(0.1, detail = "Retrieving SNOTEL snowpack data...")
print("Pulling SNOTEL data...")
values$snotel_error <- NULL
snotel_warnings <- character(0)
tryCatch({
clp_snotel_url <- "https://nwcc-apps.sc.egov.usda.gov/awdb/basin-plots/POR/WTEQ/assocHUC8/10190007_Cache_La_Poudre.csv"
# keep warnings: the HTTP status (e.g. 502) is reported as a warning
snotel_df <- withCallingHandlers(
read.csv(clp_snotel_url),
warning = function(w) {
snotel_warnings <<- c(snotel_warnings, conditionMessage(w))
invokeRestart("muffleWarning")
}
)
if (nrow(snotel_df) == 0) stop("The SNOTEL download contained no rows.")
names(snotel_df) <- gsub("^X", "", names(snotel_df))
values$clp_snotel_data <- snotel_df
print("SNOTEL data pulled successfully.")
}, error = function(e) {
msg <- paste(c(conditionMessage(e), snotel_warnings), collapse = " | ")
values$snotel_error <- msg
print(paste("SNOTEL Error:", msg))
})
home_state$set_status("snotel_api", "done")
#### ---- CANYON MOUTH HISTORICAL FLOW (For TOC Model) ---- ####
incProgress(0.1, detail = "Retrieving Canyon Mouth historical flow data...")
print("Pulling historical flow for Canyon Mouth (CLAFTCCO)...")
tryCatch({
# Find min and max date from cached data for the historical pull
min_date <- as.Date(min(cached_data$DT_round, na.rm = TRUE)) - days(1)
max_date <- as.Date(max(cached_data$DT_round, na.rm = TRUE)) + days(1)
canyon_q_res <- cdssr::get_telemetry_ts(
abbrev = "CLAFTCCO",
start_date = min_date,
end_date = max_date,
api_key = cdwr_api_key,
timescale = "hour"
) %>%
mutate(date = as.Date(force_tz(datetime, tz = "America/Denver")) )%>%
summarize(canyon_mouth_daily_flow_cfs = mean(meas_value, na.rm = TRUE), .by = date)
values$canyon_q <- canyon_q_res
print("Historical flow pulled successfully.")
}, error = function(e) {
print(paste("Canyon Flow Error:", e$message))
})
#### Data Aggregation ####
incProgress(0.1, detail = "Processing data...")
print("Aggregating API data...")
all_data_raw <- c(hv_data, wet_data, contrail_data)
list_names <- names(all_data_raw)
keep_indices <- !grepl("stage", list_names, ignore.case = TRUE)
all_data_raw <- all_data_raw[keep_indices]
if(length(all_data_raw) == 0){
print("Warning: No new API data found.")
combined_data <- data.frame()
} else {
print("Tidying API data...")
tidy_data <- all_data_raw %>%
map(~tidy_api_data(api_data = .)) %>%
keep(~!is.null(.))
print("Pulling field notes from mWater...")
mWater_creds <- read_yaml("creds/mWaterCreds.yml")
mWater_data <- load_mWater(creds = mWater_creds)
all_field_notes <- grab_mWater_sensor_notes(mWater_api_data = mWater_data) %>%
mutate(DT_round = with_tz(DT_round, tzone = "UTC"),
last_site_visit = with_tz(last_site_visit, tzone = "UTC"),
DT_join = as.character(DT_round))
sensor_malfunction_notes <- grab_mWater_malfunction_notes(mWater_api_data = mWater_data) %>%
mutate(start_DT = with_tz(start_DT, tzone = "UTC"),
end_DT = with_tz(end_DT, tzone = "UTC"))
print("Adding field notes to tidied data...")
combined_data <- tidy_data %>%
map(~add_field_notes(df = ., notes = all_field_notes), .progress = TRUE) %>%
bind_rows() %>%
mutate(auto_flag = NA,
mal_flag = NA)
}
incProgress(0.1, detail = "Structuring and deduplicating dataset...")
print("Merging new data with cached data and deduplicating...")
if(nrow(combined_data) > 0) {
dashboard_data <- bind_rows(cached_data, combined_data) %>%
arrange(site, parameter, DT_round) %>%
distinct(site, parameter, DT_round, .keep_all = TRUE) %>%
ungroup()
} else {
dashboard_data <- cached_data %>%
arrange(site, parameter, DT_round) %>%
distinct(site, parameter, DT_round, .keep_all = TRUE) %>%
ungroup()
}
print("--- DATA INITIALIZATION COMPLETE ---")
Sys.sleep(0.5)
incProgress(0.1, detail = "Data successfully loaded!")
# Finalize Initialization
loaded_data(dashboard_data)
home_state$set_status("all_done", TRUE)
showNotification("Data streams initialized successfully!", type = "message")
})
})
#### Base filtered data reactive ####
# Only updates when load_data is pressed
base_filtered_data <- eventReactive(input$load_data, {
req(loaded_data(), input$date_range, input$sites_select, input$parameters_select)
start_DT <- as.POSIXct(paste0(input$date_range[1], " 00:01"), tz = "America/Denver")
end_DT <- as.POSIXct(paste0(input$date_range[2], " 23:55"), tz = "America/Denver")
sites_sel <- filter(site_table, site_name %in% input$sites_select) %>% pull(site_code)
# Ensure we include required parameters for TOC model even if not selected for other plots
required_toc_params <- c("FDOM Fluorescence", "Temperature", "Specific Conductivity", "Turbidity")
all_params <- unique(c(input$parameters_select, required_toc_params))
loaded_data() %>%
mutate(DT_round_MT = with_tz(DT_round, tzone = "America/Denver")) %>%
filter(
between(DT_round_MT, start_DT, end_DT),
site %in% sites_sel,
parameter %in% all_params
) %>%
mutate(
mean = ifelse(!is.na(mal_flag), NA, mean),
mean = if_else(units == "m", mean * 3.28084, mean), #converting depth readings to feet for better interpretability
units = if_else(units == "m", "ft", units) # fix units for depth readings to reflect conversion to feet
)
})
#
#### Reactive value to store filtered data ####
filtered_data <- reactive({
req(base_filtered_data())
if (input$apply_qaqc_filter) {
#remove overflagged data (autogenerated flags)
apply_cleaning_filters(df = base_filtered_data(), new_value_col = "mean_cleaned")%>%
# interpolate missing data (<1 hour, 4 points)
apply_interpolation_missing_data(df = ., value_col = "mean_cleaned", dt_col = "DT_round_MT", method = "linear", max_gap = 4 )%>%
# apply binomial filter to turbidity and Chl-a
apply_low_pass_binomial_filter(df = ., value_col = "mean_filled", new_value_col = "mean_smoothed", dt_col = "DT_round_MT")%>%
# apply timestep median to reduce noise
mutate(DT_round = as.POSIXct(DT_round_MT)) %>%
apply_timestep_median(df = ., value_col = "mean_smoothed", new_value_col = "timestep_median", timestep = input$data_timestep, dt_col = "DT_round") %>%
#trim down dataset and rename columns
select(DT_round = DT_group, site, parameter, mean = timestep_median)%>%
#remove duplicates
distinct(site, parameter, mean, DT_round, .keep_all = TRUE)
} else {
# If QA/QC filter is not applied, just return base filtered data with timestep median applied
apply_interpolation_missing_data(df = base_filtered_data(), value_col = "mean", dt_col = "DT_round_MT", method = "linear", max_gap = 4)%>%
# take timestep median
mutate(DT_round = as.POSIXct(DT_round_MT)) %>%
apply_timestep_median(df = ., value_col = "mean_filled", new_value_col = "timestep_median", timestep = input$data_timestep, dt_col = "DT_round") %>%
#trim down dataset and rename columns
select(DT_round = DT_group, site, parameter, mean = timestep_median)%>%
#remove duplicates
distinct(site, parameter, mean, DT_round, .keep_all = TRUE)
}
})
#### Time Series Plots ####
#### Log Controls Dynamic UI ####
output$log_controls <- renderUI({
req(filtered_data())
data <- filtered_data()
req(nrow(data) > 0)
parameters <- unique(data$parameter)
# Create checkbox inputs for each parameter
checkbox_list <- lapply(parameters, function(param) {
# Create a clean input ID from parameter name
input_id <- paste0("log_", gsub("[^A-Za-z0-9]", "_", tolower(param)))
checkboxInput(input_id, paste("Log10 Scale -", param), FALSE)
})
do.call(tagList, checkbox_list)
})
#### Setup Dynamic Plots ####
output$dynamic_plots <- renderUI({
req(input$parameters_select, filtered_data())
# Calculate number of rows needed (1 plot per row)
n_params <- length(input$parameters_select)
n_rows <- n_params # One row per parameter
# Create rows with plots
plot_rows <- lapply(1:n_rows, function(row) {
parameter <- input$parameters_select[row]
plot_id <- paste0("time_series_plot_", row)
units <- plot_param_table%>%
filter(parameter == !!parameter)%>%
pull(units)
fluidRow(
column(
width = 12, # Full width for single plot
h4(paste0("Time Series for ", parameter, " (", units, ")")),
plotlyOutput(plot_id, height = "400px")
)
)
})
do.call(tagList, plot_rows)
})
#### Generate plots ####
observe({
req(input$parameters_select, filtered_data())
# Create a plot for each selected parameter
lapply(seq_along(input$parameters_select), function(i) {
parameter <- input$parameters_select[i]
plot_id <- paste0("time_series_plot_", i)
output[[plot_id]] <- renderPlotly({
# Filter data for this specific parameter
plot_data <- filtered_data() %>%
filter(parameter == !!parameter)%>%
left_join(site_table, by = c("site" = "site_code" ))
# Check if log scale is enabled for this parameter
log_input_id <- paste0("log_", gsub("[^A-Za-z0-9]", "_", tolower(parameter)))
use_log <- if (!is.null(input[[log_input_id]])) input[[log_input_id]] else FALSE
# Get parameter bounds from lookup table
param_bounds <- plot_param_table %>%
filter(parameter == !!parameter)
units <- plot_param_table%>%
filter(parameter == !!parameter)%>%
pull(units)
# Determine y-axis limits
if(nrow(param_bounds) > 0 && nrow(plot_data) > 0) {
data_min <- min(plot_data$mean, na.rm = TRUE)
data_max <- max(plot_data$mean, na.rm = TRUE)
# Use parameter bounds as default, but extend if data goes outside
y_min <- min(param_bounds$lower, data_min) - 0.2
y_max <- max(param_bounds$upper, data_max) + 0.2
# Add small buffer if data exactly matches bounds
if(data_min >= param_bounds$lower && data_max <= param_bounds$upper) {
y_min <- param_bounds$lower
y_max <- param_bounds$upper
}
} else if(nrow(plot_data) > 0) {
# Fallback to data range if no bounds available
y_min <- min(plot_data$mean, na.rm = TRUE)
y_max <- max(plot_data$mean, na.rm = TRUE)
} else {
# Default range if no data
y_min <- 0
y_max <- 1
}
# Set consistent colors for plotting by site
color_mapping <- setNames(site_table$color, site_table$site_code)
# Create the plotly plot
p <- plot_ly(plot_data,
x = ~DT_round,
y = ~mean,
type = "scatter",
color = ~site,
colors = color_mapping,
mode = "lines",
name = ~site_name) %>%
layout(
xaxis = list(title = "Date"),
yaxis = list(
title = if (use_log) paste0("Log10(", parameter,"(" ,units, ")", ")") else paste0(parameter," (" ,units, ")"),
type = if (use_log) "log" else "linear",
range = if (use_log) c(log10(max(y_min, 0.01)), log10(y_max)) else c(y_min, y_max)
),
hovermode = "closest"
)
return(p)
})
})
})
#### TOC model plots ####
#TODO: move most of this code to a separate function to clean up the server and make it more modular
observe({
req(input$parameters_select, input$sites_select, input$data_timestep, filtered_data())
# get site codes for filtering
sites_sel <- filter(site_table, site_name %in% input$sites_select )%>%
pull(site_code)
# remove FC sonde data
input_data <- filtered_data() %>%
filter(!str_detect( site, "_fc")) #FC sondes will not have correct parameters so we can omit them entirely
# Define required parameters
required_params <- c("FDOM Fluorescence", "Temperature", "Specific Conductivity", "Turbidity", "Chl-a Fluorescence")
# Check if all required parameters are present
available_params <- unique(input_data$parameter)
missing_params <- setdiff(required_params, available_params)
#if missing parameters or sites do not have model parameters (FC)
if(length(missing_params) > 0 & nrow(input_data) > 0) {
# Create warning message plot
warning_text <- paste("Cannot generate TOC model plots.",
"Missing required parameters:",
paste(missing_params, collapse = ", "))
# Create a plotly text plot with warning message
p <- plot_ly() %>%
add_text(x = 0.5, y = 0.5, text = warning_text,
textfont = list(size = 16, color = "red"),
showlegend = FALSE) %>%
layout(
xaxis = list(showgrid = FALSE, showticklabels = FALSE, zeroline = FALSE, range = c(0, 1)),
yaxis = list(showgrid = FALSE, showticklabels = FALSE, zeroline = FALSE, range = c(0, 1)),
plot_bgcolor = 'rgba(0,0,0,0)',
paper_bgcolor = 'rgba(0,0,0,0)',
margin = list(t = 50, b = 50, l = 50, r = 50)
)
return(p)
}
# check to make sure not all rows are NA
na_check <- input_data %>%
filter(parameter %in% required_params)%>%
select(mean)%>%
na.omit()
# If no data available, show Error message
if(nrow(na_check) == 0) {
no_data_text <- "No data available to estimate TOC for the selected time period and sites."
p <- plot_ly() %>%
add_text(x = 0.5, y = 0.5, text = no_data_text,
textfont = list(size = 16, color = "red"),
showlegend = FALSE) %>%
layout(
xaxis = list(showgrid = FALSE, showticklabels = FALSE, zeroline = FALSE, range = c(0, 1)),
yaxis = list(showgrid = FALSE, showticklabels = FALSE, zeroline = FALSE, range = c(0, 1)),
plot_bgcolor = 'rgba(0,0,0,0)',
paper_bgcolor = 'rgba(0,0,0,0)',
margin = list(t = 50, b = 50, l = 50, r = 50)
)
return(p)
}
# Apply TOC model on relevant data
toc_plot_data <- apply_toc_model(sensor_data = input_data,
scaling_params_file_path = "data/models/scaling_params_toc_20260715.parquet",
#summarizing model input results to user selected timestep (15 min -> 1 day)
summarize_interval = input$data_timestep,
time_col = "DT_round",
value_col = "mean",
canyon_q_data = values$canyon_q,
timeseries = T) %>%
left_join(site_table, by = c("site" = "site_code"))%>%
mutate(across(contains("TOC_guess"), ~ round(.x, 2)))
#parameter to plot
plot_param <- "TOC_guess_ensemble"
# get the list of sites
site_list <- unique(toc_plot_data$site_name)
# dynamically create plot containers
output$toc_plots_panel <- renderUI({
tagList(
lapply(site_list, function(site_cd) {
plotlyOutput(outputId = paste0("toc_plot_", site_cd), height = "400px")
})
)
})
# render one plot per site
lapply(site_list, function(site_cd) {
output[[paste0("toc_plot_", site_cd)]] <- renderPlotly({
site_toc_data <- toc_plot_data %>%
filter(site_name == site_cd)%>%
arrange(DT_round) %>%
#pad data to ensure continuous time series (important for ribbon plotting)
complete(DT_round = seq(min(DT_round), max(DT_round), by = input$data_timestep))%>%
mutate(
gap = is.na(TOC_guess_min) | is.na(TOC_guess_max) | is.na(.data[[plot_param]]),
gid = cumsum(lag(gap, default = TRUE) != gap)
)
if (nrow(site_toc_data) == 0) {
# Return empty plot safely if no data
return(
plot_ly() %>%
add_text(x = 0.5, y = 0.5, text = "No TOC data available for this date range.",
textfont = list(size = 16, color = "red"),
showlegend = FALSE) %>%
layout(
xaxis = list(showgrid = FALSE, showticklabels = FALSE, zeroline = FALSE, range = c(0, 1)),
yaxis = list(showgrid = FALSE, showticklabels = FALSE, zeroline = FALSE, range = c(0, 1))
) %>% config(displayModeBar = FALSE)
)
}
#get sample data
site_samples <- water_chem%>%
left_join(site_table, by = c("site_code"))%>%
filter(site_name == site_cd & !is.na(TOC))%>%
mutate(DT_round = with_tz(round_date(DT_sample, unit = "15 minutes"), tzone = "America/Denver"))%>%
filter(between(DT_round, min(site_toc_data$DT_round) - days(1), max(site_toc_data$DT_round) + days(1)))
p <- plot_ly() %>%
##### add shapes for general categories of TOC values ####
layout(
shapes = list(
# Green band 0–2
list(type = "rect", xref = "paper", x0 = 0, x1 = 1,
yref = "y", y0 = 0, y1 = 2,
fillcolor = "rgba(0,255,0,0.2)", line = list(width = 0)),
# Yellow band 2–4
list(type = "rect", xref = "paper", x0 = 0, x1 = 1,
yref = "y", y0 = 2, y1 = 4,
fillcolor = "rgba(255,255,0,0.2)", line = list(width = 0)),
# Red band 4–8
list(type = "rect", xref = "paper", x0 = 0, x1 = 1,
yref = "y", y0 = 4, y1 = 8,
fillcolor = "rgba(255,0,0,0.2)", line = list(width = 0))
)
)
if (nrow(site_toc_data) > 0) {
gids <- unique(site_toc_data$gid)
##### add RIBBONS complete model set of TOC values ####
for (i in seq_along(gids)) {
d <- site_toc_data[site_toc_data$gid == gids[i], ]
# make sure customdata has the same number of rows
d$custom_range <- paste0(d$TOC_guess_min, " - ", d$TOC_guess_max)
p <- p %>%
add_ribbons(
data = d,
x = ~DT_round,
ymin = ~TOC_guess_min,
ymax = ~TOC_guess_max,
fillcolor = "grey",
line = list(color = "transparent"),
opacity = 0.5,
name = "Models Range of Estimates",
customdata = ~custom_range,
hovertemplate = paste(
"%{customdata}<br>"),
showlegend = (i == 1) # Only one legend entry
)
}
##### add LINES ensemble mean model set of TOC values ####
for (i in seq_along(gids)) {
d <- site_toc_data[site_toc_data$gid == gids[i], ]
p <- p %>%
add_lines(
data = d,
x = ~DT_round,
y = ~.data[[plot_param]],
line = list(color = "#E70870", width = 2),
name = "Mean Model Estimate",
hovertemplate = paste(
"Ensemble Estimate: %{y:.2f}<extra></extra>"
),
showlegend = (i == 1) # Only show one legend
)
}
}
# add a placeholder so the plot still renders if all data is NA
if (nrow(site_toc_data) == 0) {
p <- p %>%
add_text(x = 0.5, y = 0.5, text = "No complete data segments", showlegend = FALSE) %>%
layout(
xaxis = list(showgrid = FALSE, showticklabels = FALSE, zeroline = FALSE, range = c(0, 1)),
yaxis = list(showgrid = FALSE, showticklabels = FALSE, zeroline = FALSE, range = c(0, 1))
)
}
if (nrow(site_samples) > 0) {
p <- p %>%
add_markers(
data = site_samples,
x = ~DT_sample,
y = ~TOC,
#symbol = ~collector,
marker = list(color = "blue", size = 8, shape = "circle"),
name = "Lab TOC",
hovertemplate = paste(
"Measured TOC: %{y:.2f} mg/L<br>"
)
)
}
# Get parameter y axis bounds from lookup in Global.R table
param_bounds <- plot_param_table %>%
filter(parameter == "TOC")
# Determine y-axis limits
if(nrow(param_bounds) > 0 && nrow(toc_plot_data) > 0) {
# Combine data safely
all_vals <- c(site_toc_data$TOC_guess_min, site_toc_data$TOC_guess_max)
if (nrow(site_samples) > 0) {
all_vals <- c(all_vals, site_samples$TOC)
}
data_min <- suppressWarnings(min(all_vals, na.rm = TRUE))
data_max <- suppressWarnings(max(all_vals, na.rm = TRUE))
if (is.infinite(data_min)) data_min <- param_bounds$lower
if (is.infinite(data_max)) data_max <- param_bounds$upper
# Use parameter bounds as default, but extend if data goes outside
y_min <- min(param_bounds$lower, data_min)
y_max <- max(param_bounds$upper, data_max)
# Add small buffer if data exactly matches bounds
if(data_min >= param_bounds$lower && data_max <= param_bounds$upper) {
y_min <- param_bounds$lower
y_max <- param_bounds$upper
}
} else if(nrow(site_toc_data) > 0) {
# Fallback to data range if no bounds available
y_min <- min(site_toc_data$TOC_guess_min, na.rm = TRUE) + 0.1 # add padding to avoid cutting off lowest data point
y_max <- max(site_toc_data$TOC_guess_max, na.rm = TRUE) + 0.1# add padding to avoid cutting off highes data point
} else {
# Default range if no data
y_min <- 0
y_max <- 1
}
#create empty shapes and annotations lists
shapes_list <- list()
annotations_list <- list()
# add preliminary text to annotations
# annotations_list <- append(annotations_list,
# list(
# x = max(site_toc_data$DT_round, na.rm = TRUE),
# y = y_max * 0.85,
# text = "PRELIMINARY RESULTS",
# showarrow = FALSE,
# xanchor = "right",
# yanchor = "top",
# font = list(size = 16, color = "black", family = "Arial Black")
# )
# )
# Add line/annotation if data is less than lower model bound
if(y_min <= toc_model_bounds$TOC_lower){
shapes_list <- append(shapes_list, list(
list(type = "line",
x0 = 0, x1 = 1, xref = "paper",
y0 = toc_model_bounds$TOC_lower,
y1 = toc_model_bounds$TOC_lower,
line = list(dash = "dash", width = 2, color = "black"))
))
annotations_list <- append(annotations_list, list(
list(x = 0.02, xref = "paper",
y = toc_model_bounds$TOC_lower,
text = "Model Lower Limit",
showarrow = FALSE,
xanchor = "left",
yanchor = "top")
))
}
# Add line/annotation if data exceeds upper model bound
if(y_max >= toc_model_bounds$TOC_upper) {
shapes_list <- append(shapes_list, list(
list(type = "line",
x0 = 0, x1 = 1, xref = "paper",
y0 = toc_model_bounds$TOC_upper,
y1 = toc_model_bounds$TOC_upper,
line = list(dash = "dash", width = 2, color = "black"))
))
annotations_list <- append(annotations_list, list(
list(x = 0.02, xref = "paper",
y = toc_model_bounds$TOC_upper,
text = "Model Upper Limit",
showarrow = FALSE,
xanchor = "left",
yanchor = "bottom")
))
}
start_DT <- as.POSIXct(paste0(input$date_range[1], " 00:01"), tz = "America/Denver")
end_DT <- as.POSIXct(paste0(input$date_range[2], " 23:55"), tz = "America/Denver")
#### Final layout tweaks ####
p %>%
layout(
title = paste0("Estimated TOC (mg/L) at: ", site_cd),
xaxis = list(title = "Date", range = c(start_DT, end_DT)),
yaxis = list(title = "Model Estimated TOC (mg/L)", range = c(y_min - 0.25, y_max+0.25)),
legend = list(orientation = "h", x = 0.5, xanchor = "center", y = -0.2),
hovermode = "x unified",
annotations = annotations_list
)
})
})
})
#### TOC Forecast Plots ####
# Generate Intake Forecast Plot
output$intake_toc_forecast_plot <- renderPlotly({
intake_cached_data <- arrow::read_parquet(intake_forecast_url, as_data_frame = TRUE)%>%
filter(date == max(date, na.rm = TRUE)) %>% # Get the most recent forecast date
mutate(across(contains("intake_q_swe_pred"), ~ round(.x, 2)))%>%
filter(date_24h <= Sys.Date() + days(10)) #Limit to the next 10 days
plot_toc_forecast(intake_cached_data, title_suffix = "Fort Collins Poudre River Intake TOC Forecast")
})
# Generate Distributed Forecast Plots
output$dist_toc_forecast_plots <- renderUI({
req(input$toc_forecast_sites)
sites <- input$toc_forecast_sites
plot_rows <- lapply(sites, function(site) {
clean_site_id <- gsub("[^[:alnum:]]", "_", site)
plot_id <- paste0("toc_plot_", clean_site_id)
fluidRow(
column(
width = 12,
style = "margin-bottom: 20px;",
h4(paste0("TOC Forecast: ", site)),
plotlyOutput(plot_id, height = "400px")
)
)
})
do.call(tagList, plot_rows)
})
# Create Distributed TOC Forecast Plots
observe({
# Ensure input is available
req(input$toc_forecast_sites)
# Load and filter
dist_cached_data <- arrow::read_parquet(distributed_forecast_url, as_data_frame = TRUE) %>%
mutate(across(contains("pred_toc"), ~ round(.x, 2))) %>%
filter(date == max(date, na.rm = TRUE)) %>% # Get the most recent forecast date
filter(date_24h <= Sys.Date() + days(10))
sites <- unique(dist_cached_data$site_name)
selected_sites <- sites[sites %in% input$toc_forecast_sites]
for (site in selected_sites) {
local({
current_site <- site
clean_site_id <- gsub("[^[:alnum:]]", "_", current_site)
plot_id <- paste0("toc_plot_", clean_site_id)