-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathIQ_Report_Render.R
1409 lines (1111 loc) · 57.1 KB
/
IQ_Report_Render.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
## This file executes IQ_Report.Rmd to render PDF reports detailing data that has
## been flagged for falling outside of IQ range, as determined dynamically based on the data
library(tidyverse)
library(data.table)
library(doFuture)
library(lubridate)
library(stringr)
library(openxlsx)
library(tictoc)
# Libraries for Rmd
library(knitr)
library(data.table)
library(dplyr)
library(lubridate)
library(ggplot2)
library(ggpubr)
library(scales)
library(EnvStats)
library(tidyr)
library(kableExtra)
library(tidyverse)
library(stringr)
library(glue)
library(plyr)
library(dplyr)
library(git2r)
# Set to TRUE to render IQ Reports for each habitat
render_reports <- TRUE
# import "seacar_data_location" variable which points to data directory
source("seacar_data_location.R")
# Create output path if it doesn't already exist
output_path <- c("output","output/data")
for (path in output_path) {
if (!dir.exists(path)){dir.create(path, recursive = TRUE)}
}
#List data files
seacardat <- list.files(seacar_data_location, full.names = TRUE, pattern=".txt")
# Water Column habitat contains Nekton, discrete & continuous Water Clarity & Nutrient data
# Create list of WC NUT files
wq_files <- seacardat[str_detect(seacardat, "Combined_WQ_WC_NUT_")]
wq_disc_files <- str_subset(wq_files, "_cont_", negate=TRUE)
wq_cont_files <- str_subset(wq_files, "_cont_")
nekton_file <- str_subset(seacardat, "All_NEKTON")
#Set quantile thresholds for flagging "questionable" values
quant_low <- 0.001
quant_high <- 0.999
num_sds <- 3
# any parameters to skip in report?
parstoskip <- c("")
#What are the strings that need to be interpreted as NA values?
nas <- c("NULL", "NA", "")
reffilepath <- "output/ScriptResults/Database_Thresholds.xlsx"
ref_parameters <- setDT(read.xlsx(reffilepath, sheet = 1, startRow = 7))
# Make copy of original ref_parameters file
ref_parameters_original <- copy(ref_parameters)
ref_parameters <- ref_parameters[IndicatorName!="Acreage", ]
win_threshold_path <- "http://publicfiles.dep.state.fl.us/DEAR/WIN/MDQS/4_Activity_Result_WIN_Standards.xlsx"
#### Update WIN Thresholds to latest version ----
win_thresholds <- setDT(read.xlsx(win_threshold_path, sheet = "RangeCheck(Matrix-238)", startRow = 3))
win_thresholds <- win_thresholds[Matrix=="AQUEOUS-Surface Water"]
# Value imputation must account for when value==0, convert to 0.000001
impute_val <- function(val, thres){
if(thres=="low"){
ifelse(val==0, -0.000001, val)
} else if(thres=="high"){
ifelse(val==0, 0.000001, val)
}
}
# Initialize a data.table to store the differences
threshold_changes <- data.table(ParameterName = character(),
OldLowThreshold = numeric(), NewLowThreshold = numeric(),
OldHighThreshold = numeric(), NewHighThreshold = numeric(),
change = logical())
# Mapping of ParameterName to AnalyteName and thresholds
threshold_mapping <- list(
list(param = "Dissolved Oxygen", analyte = "Dissolved Oxygen"),
list(param = "Dissolved Oxygen Saturation", analyte = "Dissolved oxygen saturation"),
list(param = "pH", analyte = "pH"),
list(param = "Specific Conductivity", analyte = "Specific Conductance", factor = 1000),
list(param = "Water Temperature", analyte = "Temperature, Water", sheet = "RangeCheck(ActivityType-237)", activity_type = "Field")
)
# Function to get the thresholds and log changes if they differ
get_thresholds_and_log_changes <- function(param_info) {
factor <- param_info$factor %||% 1 # Default factor is 1 if not specified
sheet <- param_info$sheet %||% NULL
activity_type <- param_info$activity_type %||% NULL
if (!is.null(sheet)) {
win_thresholds_wt <- setDT(read.xlsx(win_threshold_path, sheet = sheet, startRow = 3))
thresholds <- win_thresholds_wt[AnalyteName == param_info$analyte & Activity.Type == activity_type]
} else {
thresholds <- win_thresholds[AnalyteName == param_info$analyte]
}
# Impute values
imputed_low <- impute_val(thresholds[, Lowest.Allowable.Threshold] / factor, "low")
imputed_high <- impute_val(thresholds[, Highest.Allowable.Threshold] / factor, "high")
# Extract the old values from ref_parameters
old_low <- ref_parameters[CombinedTable == "Discrete WQ" & ParameterName == param_info$param, LowThreshold]
old_high <- ref_parameters[CombinedTable == "Discrete WQ" & ParameterName == param_info$param, HighThreshold]
# Determine if there's a change in either threshold
change_flag <- (!is.na(old_low) && old_low != imputed_low) || (!is.na(old_high) && old_high != imputed_high)
# Log all entries and mark if there was a change
threshold_changes <<- rbind(threshold_changes,
data.table(ParameterName = param_info$param,
OldLowThreshold = old_low, NewLowThreshold = imputed_low,
OldHighThreshold = old_high, NewHighThreshold = imputed_high,
change = change_flag))
list(low = imputed_low, high = imputed_high)
}
# Apply the thresholds and log changes once per ParameterName
for (param_info in threshold_mapping) {
thresholds <- get_thresholds_and_log_changes(param_info)
# Update both LowThreshold and HighThreshold in a single call
ref_parameters[CombinedTable == "Discrete WQ" & ParameterName == param_info$param,
`:=` (LowThreshold = thresholds$low, HighThreshold = thresholds$high)]
}
# Continue set-up ----
#Specify GitHub user info
github_user = "tylerhill122"
github_email = "[email protected]"
#Get current script git commit and path, and create a version label
scriptpath <- rstudioapi::getSourceEditorContext()$path
scriptname <- str_sub(scriptpath, max(str_locate_all(scriptpath, "/")[[1]]) + 1, -1)
gitcommit_script <- system(paste0("git rev-list HEAD -1 ",scriptname), intern=TRUE) #NOTE: this command only looks within the current branch (assumes the user is already using 'main').
scriptversion <- paste0(scriptname, ", Git Commit ID: ", gitcommit_script)
#Get latest git commit ID
gitcommit <- system("git rev-parse HEAD", intern=TRUE)
table_template <- function(){
return(
data.table(
ParameterID = numeric(),
ParameterName = character(),
ParameterUnits = character(),
IndicatorID = numeric(),
IndicatorName = character(),
Habitat = character(),
ThresholdID = numeric(),
sub_parameter = character(),
q_low = integer(),
q_high = integer(),
mean = integer(),
n_tot = integer(),
n_q_low = integer(),
n_q_high = integer(),
QuadSize_m2 = integer()
)
)
}
# Empty frames/list to store results
data_directory <- list()
qs <- table_template()
wq_qs <- table_template()
# Filter by species group? FOR CORAL ONLY - Indicator/Parameter SG1 combos
species_group_filtering <- TRUE
# List to store flagged data for Habitat Water Column
wq_flagged_data_list <- list()
# Select which continuous parameters to include:
all_params <- c(
"Dissolved Oxygen",
"Dissolved Oxygen Saturation",
"pH",
"Salinity",
"Turbidity",
"Water Temperature"
)
# Select which regions to include Continuous data for
regions <- c(
"NE",
"NW",
"SE",
"SW"
)
# list of habitats to generate reports for
habitats <- unique(ref_parameters$Habitat)
# subset for a given report
# habitats <- c("Submerged Aquatic Vegetation")
# Loop through each habitat ----
tic()
for (h in habitats){
if(h=="Water Column"){
# list to store shortened file names to display in report
file_short_list <- list()
water_column_summary_directory <- list()
program_counts <- data.table()
# Check if Nekton file is present, add to report
if(length(nekton_file)>0){
type_name <- "Nekton"
file <- nekton_file
# Record shortened file name
file_short <- tail(str_split(file, "/")[[1]], 1)
file_short_list[[type_name]] <- file_short
qs_dat <- table_template()
data <- fread(file, sep='|', na.strings = nas)
data <- data[Include==1 & MADup==1 & !is.na(ResultValue) &
SpeciesGroup1 %in% c("Grazers and reef dependent species", "Reef fish"), ]
# Record parameter name and units
param_ids <- unique(data$ParameterID)
param_names <- unique(data$ParameterName)
i <- unique(data$IndicatorName)
i_id <- unique(data$IndicatorID)
# Record data totals by parameter
p_count <- data %>%
dplyr::group_by(ProgramID, ParameterName) %>%
dplyr::summarise(n_tot = n(), .groups = "keep")
p_count$typeName <- type_name
program_counts <- bind_rows(program_counts, p_count)
# Nekton Processing
for (p_id in param_ids){
p <- ref_parameters[ParameterID==p_id & IndicatorID==i_id, ParameterName]
threshold_id <- ref_parameters[ParameterID==p_id & CombinedTable==type_name,
ThresholdID]
if(p %in% parstoskip){next}
dat_par <- data[ParameterName==p,
.(ParameterID = p_id,
ParameterName = p,
ParameterUnits = NA,
IndicatorID = i_id,
IndicatorName = i,
Habitat = h,
ThresholdID = threshold_id,
q_low = quantile(ResultValue, probs = quant_low),
q_high = quantile(ResultValue, probs = quant_high),
mean = mean(ResultValue),
n_tot = length(ResultValue))] %>% unique()
# pull high and low quantiles for filtering
quant_low_value <- dat_par$q_low
quant_high_value <- dat_par$q_high
# grab subset of data that falls below quantile limit
subset_low <- data[ParameterName==p & ResultValue < quant_low_value, ]
subset_low$q_subset <- "low"
# grab subset of data that falls above quantile limit
subset_high <- data[ParameterName==p & ResultValue > quant_high_value, ]
subset_high$q_subset <- "high"
# combine datasets for display in report
combined_subset <- bind_rows(subset_low, subset_high)
# Append the combined data frame to the result list
wq_flagged_data_list[[type_name]][[i]][[p]] <- combined_subset
# Add n_q_low and n_q_high to dat_par table
dat_par$n_q_low <- nrow(subset_low)
dat_par$n_q_high <- nrow(subset_high)
dat_par[ , c('sub_parameter', 'QuadSize_m2')] = NA
qs_dat <- rbind(qs_dat, dat_par)
print(paste0(p, " sequencing complete"))
}
# Record overall results
wq_qs <- rbind(wq_qs, qs_dat)
# File into directory to display summaries for each Indicator
water_column_summary_directory[[type_name]] <- qs_dat
print(paste0(file_short, " export done"))
}
# Check if WQ_Disc files are present, add to report
if(length(wq_disc_files)>0){
# DISCRETE
type_name <- "Discrete WQ"
qs_dat <- table_template()
# Discrete processing
for (file in wq_disc_files){
# shortened file name
file_short <- tail(str_split(file, "/")[[1]], 1)
data <- fread(file, sep='|', na.strings = nas)
data <- data[Include==1 & MADup==1 & !is.na(ResultValue), ]
param_id <- unique(data$ParameterID)
param_name <- unique(data$ParameterName)
param_units <- unique(data$ParameterUnits)
# Update ParameterName and Units in ref_parameters
# This maintains consistency with new exports
ref_parameters[ParameterID==param_id, `:=` (ParameterName = param_name,
Units = param_units)]
for (p in param_name){
if(p %in% parstoskip){next}
threshold_id <- ref_parameters[ParameterID==param_id & CombinedTable==type_name,
ThresholdID]
# Set indicator name for each parameter (WC, WQ, NUT)
i <- ref_parameters[ParameterID==param_id & CombinedTable==type_name,
unique(IndicatorName)]
i_id <- ref_parameters[ParameterID==param_id & CombinedTable==type_name,
unique(IndicatorID)]
# If parameter is "Total Nitrogen", calculate quantiles/SDs separately for "uncalculated" records
if(p == "Total Nitrogen"){
# Record data totals by parameter (for both All & No Calc)
p_count_all <- data %>%
dplyr::group_by(ProgramID, ParameterName) %>%
dplyr::summarise(n_tot = n(), .groups = "keep")
p_count_all$typeName <- type_name
program_counts <- bind_rows(program_counts, p_count_all)
p_count_nocalc <- data[str_detect(SEACAR_QAQCFlagCode, "1Q", negate = TRUE), ] %>%
dplyr::group_by(ProgramID, ParameterName) %>%
dplyr::summarise(n_tot = n(), .groups = "keep")
p_count_nocalc$typeName <- type_name
program_counts <- bind_rows(program_counts, p_count_nocalc)
dat_par_all <- data[ParameterName==p,
.(ParameterID = param_id,
ParameterName = p,
ParameterUnits = param_units,
IndicatorID = i_id,
IndicatorName = i,
Habitat = h,
ThresholdID = 21,
q_low = quantile(ResultValue, probs = quant_low),
q_high = quantile(ResultValue, probs = quant_high),
mean = mean(ResultValue),
n_tot = length(ResultValue))] %>% unique()
dat_par_all[, sub_parameter := "All"]
dat_par_nocalc <- data[ParameterName==p & str_detect(SEACAR_QAQCFlagCode, "1Q", negate = TRUE),
.(ParameterID = param_id,
ParameterName = p,
ParameterUnits = param_units,
IndicatorID = i_id,
IndicatorName = i,
Habitat = h,
ThresholdID = 31,
q_low = quantile(ResultValue, probs = quant_low),
q_high = quantile(ResultValue, probs = quant_high),
mean = mean(ResultValue),
n_tot = length(ResultValue))] %>% unique()
dat_par_nocalc[, sub_parameter := "Calculated"]
dat_par <- rbind(dat_par_all, dat_par_nocalc)
for (sub_param in unique(dat_par$sub_parameter)){
if(sub_param == "Calculated"){
sub_data <- data[str_detect(SEACAR_QAQCFlagCode, "1Q", negate = TRUE), ]
} else {
sub_data <- data
}
# pull high and low quantiles for filtering
quant_low_value <- dat_par[sub_parameter==sub_param, q_low]
quant_high_value <- dat_par[sub_parameter==sub_param, q_high]
# grab subset of data that falls below quantile limit
subset_low <- sub_data[ParameterName==p & ResultValue < quant_low_value, ]
subset_low$q_subset <- "low"
# grab subset of data that falls above quantile limit
subset_high <- sub_data[ParameterName==p & ResultValue > quant_high_value, ]
subset_high$q_subset <- "high"
# combine datasets for display in report
combined_subset <- bind_rows(subset_low, subset_high)
combined_subset$sub_parameter <- sub_param
# new combined parameter name (Total Nitrogen + sub_param)
new_param_name <- paste0("Total Nitrogen (", sub_param, ")")
combined_subset[sub_parameter==sub_param, `:=` (ParameterName = new_param_name)]
# Append the combined data frame to the result list
wq_flagged_data_list[[type_name]][[i]][[new_param_name]] <- combined_subset
# Append file_short to include all file names for WQ
file_short_list[[type_name]][[i]][[p]] <- file_short
# Add n_q_low and n_q_high to dat_par table
dat_par[sub_parameter==sub_param, `:=` (n_q_low = nrow(subset_low))]
dat_par[sub_parameter==sub_param, `:=` (n_q_high = nrow(subset_high))]
# Rename Total Nitrogen parameter to include Sub_parameter
# dat_par[sub_parameter==sub_param, `:=` (parameter = paste0("Total Nitrogen (", sub_param, ")"))]
dat_par[ , c('QuadSize_m2')] = NA
}
} else {
# Record data totals by parameter
p_count <- data %>%
dplyr::group_by(ProgramID, ParameterName) %>%
dplyr::summarise(n_tot = n(), .groups = "keep")
p_count$typeName <- type_name
program_counts <- bind_rows(program_counts, p_count)
dat_par <- data[ParameterName==p & !is.na(ResultValue) & MADup == 1 & Include == 1,
.(ParameterID = param_id,
ParameterName = p,
ParameterUnits = param_units,
IndicatorID = i_id,
IndicatorName = i,
Habitat = h,
ThresholdID = threshold_id,
q_low = quantile(ResultValue, probs = quant_low),
q_high = quantile(ResultValue, probs = quant_high),
mean = mean(ResultValue),
n_tot = length(ResultValue))]
# pull high and low quantiles for filtering
quant_low_value <- dat_par$q_low
quant_high_value <- dat_par$q_high
# grab subset of data that falls below quantile limit
subset_low <- data[ParameterName==p & ResultValue < quant_low_value, ]
subset_low$q_subset <- "low"
# grab subset of data that falls above quantile limit
subset_high <- data[ParameterName==p & ResultValue > quant_high_value, ]
subset_high$q_subset <- "high"
# combine datasets for display in report
combined_subset <- bind_rows(subset_low, subset_high)
# Append the combined data frame to the result list
wq_flagged_data_list[[type_name]][[i]][[p]] <- combined_subset
# Append file_short to include all file names for WQ
file_short_list[[type_name]][[i]][[p]] <- file_short
# Add n_q_low and n_q_high to dat_par table
dat_par$n_q_low <- nrow(subset_low)
dat_par$n_q_high <- nrow(subset_high)
dat_par[ , c('sub_parameter', 'QuadSize_m2')] = NA
print(paste0(p, " sequencing complete"))
}
# append to make long-form table
qs_dat <- rbind(qs_dat, dat_par)
}
}
# Record overall results
wq_qs <- rbind(wq_qs, qs_dat)
# File into directory to display summaries for each Indicator
water_column_summary_directory[[type_name]] <- wq_qs
print(paste0(file_short, " export done"))
}
# Check if WQ_Cont files are present, add to report
if(length(wq_cont_files)>0){
# Continuous
type_name <- "Continuous WQ"
cont_dat <- table_template()
for(p in all_params){
print(paste0("Starting Continuous parameter: ", p))
par_name <- str_replace_all(p," ","_")
data_combined <- list()
region_files <- list()
for(region in regions){
# Pattern used to locate correct Parameter / Region combination
pattern <- paste0(par_name,"_",region)
file <- str_subset(wq_cont_files, pattern)
file_short <- tail(str_split(file, "/")[[1]], 1)
# record short file names for display in report
region_files <- c(region_files, file_short)
# Read in data file
data <- fread(file, sep='|', na.strings = nas)
data <- data[Include==1 & MADup==1 & !is.na(ResultValue), ]
# Record region name as column "region"
data$region <- region
# Ensure ValueQualifier column is interpreted as numeric
data$ValueQualifier <- as.numeric(data$ValueQualifier)
# combine regional data sets for a given parameter
data_combined <- bind_rows(data_combined, data)
}
param_id <- unique(data_combined$ParameterID)
param_name <- unique(data_combined$ParameterName)
param_units <- unique(data_combined$ParameterUnits)
threshold_id <- ref_parameters[ParameterID==param_id & CombinedTable==type_name,
ThresholdID]
# Set indicator name for each parameter (WC, WQ, NUT)
i <- ref_parameters[ParameterID==param_id & CombinedTable==type_name,
IndicatorName]
i_id <- ref_parameters[ParameterID==param_id & CombinedTable==type_name,
IndicatorID]
# Record data totals by parameter
p_count <- data_combined %>%
dplyr::group_by(ProgramID, ParameterName) %>%
dplyr::summarise(n_tot = n(), .groups = "keep")
p_count$typeName <- type_name
program_counts <- bind_rows(program_counts, p_count)
# Append file_short to include all file names for WQ
file_short_list[[type_name]][[i]][[p]] <- region_files
dat_par <- data_combined[ParameterName==p,
.(ParameterID = param_id,
ParameterName = param_name,
ParameterUnits = param_units,
IndicatorID = i_id,
IndicatorName = i,
Habitat = h,
ThresholdID = threshold_id,
q_low = quantile(ResultValue, probs = quant_low),
q_high = quantile(ResultValue, probs = quant_high),
mean = mean(ResultValue),
n_tot = length(ResultValue))]
# pull high and low quantiles for filtering
quant_low_value <- dat_par$q_low
quant_high_value <- dat_par$q_high
# grab subset of data that falls below quantile limit
subset_low <- data_combined[ParameterName==p & ResultValue < quant_low_value, ]
subset_low$q_subset <- "low"
# grab subset of data that falls above quantile limit
subset_high <- data_combined[ParameterName==p & ResultValue > quant_high_value, ]
subset_high$q_subset <- "high"
# combine datasets for display in report
combined_subset <- bind_rows(subset_low, subset_high)
# Append the flagged data to data directory
wq_flagged_data_list[[type_name]][[i]][[p]] <- combined_subset
# Add n_q_low and n_q_high to dat_par table
dat_par$n_q_low <- nrow(subset_low)
dat_par$n_q_high <- nrow(subset_high)
# Record results
cont_dat <- rbind(cont_dat, dat_par, fill=TRUE)
print(paste0(p, " Continuous processing complete!"))
}
water_column_summary_directory[[type_name]] <- cont_dat
# append to make long-form table
wq_qs <- rbind(wq_qs, cont_dat)
}
# Combine all flagged data outputs for each indicator into single directory
data_directory[[h]] <- wq_flagged_data_list
# Report filename
file_out <- paste0(gsub("/","_",gsub(" ", "_", h)), "_IQ_Report")
# Render report
if(render_reports){
rmarkdown::render(input = "IQ_Report.Rmd",
output_format = "pdf_document",
output_file = paste0(file_out, ".pdf"),
output_dir = "output",
clean = TRUE)
unlink(paste0("output/", file_out, ".md"))
}
}
if(h=="Submerged Aquatic Vegetation"){
file <- str_subset(seacardat, "All_SAV")
# shortened filename for display in report
file_short <- tail(str_split(file, "/")[[1]], 1)
# get list of indicators within a given habitat
indicators <- ref_parameters[Habitat==h, unique(IndicatorName)]
# load in habitat data
data <- fread(file, sep="|", na.strings = nas)
data <- data[Include==1 & MADup==1 & !is.na(ResultValue), ]
qs_dat <- table_template()
flagged_data_list <- list()
for (i in indicators){
# unique threshold_ids included for each indicator/habitat combo
threshold_ids <- ref_parameters[Habitat==h & IndicatorName==i, unique(ThresholdID)]
for(threshold_id in threshold_ids){
isSpeciesSpecific <- ref_parameters[ThresholdID==threshold_id, isSpeciesSpecific]
if(isSpeciesSpecific){
sg1_include <- c("Seagrass","Total SAV")
} else {
sg1_include <- c("Macroalgae","Seagrass","Total SAV")
}
indicator_data <- data[SpeciesGroup1 %in% sg1_include, ]
p <- ref_parameters[ThresholdID==threshold_id, ParameterName]
param_id <- ref_parameters[ThresholdID==threshold_id, ParameterID]
i_id <- ref_parameters[ThresholdID==threshold_id, IndicatorID]
# Record summary for table overview
dat_par <- indicator_data[ParameterName==p,
.(ParameterID = param_id,
ParameterName = p,
ParameterUnits = NA,
IndicatorID = i_id,
IndicatorName = i,
Habitat = h,
ThresholdID = threshold_id,
q_low = quantile(ResultValue, probs = quant_low),
q_high = quantile(ResultValue, probs = quant_high),
mean = mean(ResultValue),
n_tot = length(ResultValue))]
# pull high and low quantiles for filtering
quant_low_value <- dat_par$q_low
quant_high_value <- dat_par$q_high
# grab subset of data that falls below quantile limit
subset_low <- indicator_data[ParameterName==p & ResultValue < quant_low_value, ]
subset_low$q_subset <- "low"
# grab subset of data that falls above quantile limit
subset_high <- indicator_data[ParameterName==p & ResultValue > quant_high_value, ]
subset_high$q_subset <- "high"
# combine datasets for display in report
combined_subset <- bind_rows(subset_low, subset_high)
# Append data directory with included, excluded data
flagged_data_list[[i]][[p]] <- combined_subset
# Add n_q_low and n_q_high to dat_par table
dat_par$n_q_low <- nrow(subset_low)
dat_par$n_q_high <- nrow(subset_high)
dat_par[ , c('sub_parameter', 'QuadSize_m2')] = NA
# append to make long-form table
qs_dat <- rbind(qs_dat, dat_par)
}
}
# Record overall results
qs <- rbind(qs, qs_dat)
print(paste0(file_short, " export done"))
data_directory[[h]] <- flagged_data_list
# Report filename
file_out <- paste0(gsub("/","_",gsub(" ", "_", h)), "_IQ_Report")
# Render report
if(render_reports){
rmarkdown::render(input = "IQ_Report.Rmd",
output_format = "pdf_document",
output_file = paste0(file_out, ".pdf"),
output_dir = "output",
clean = TRUE)
unlink(paste0("output/", file_out, ".md"))
}
}
if(h=="Oyster/Oyster Reef"){
file <- str_subset(seacardat, "All_OYSTER")
# shortened filename for display in report
file_short <- tail(str_split(file, "/")[[1]], 1)
# get list of indicators within a given habitat
indicators <- ref_parameters[Habitat==h, unique(IndicatorName)]
# load in habitat data
data <- fread(file, sep="|", na.strings = nas)
data <- data[Include==1 & MADup==1 & !is.na(ResultValue), ]
# Adjustments to quad size & other temporary fixes
data[QuadSize_m2 == 0.06, QuadSize_m2 := 0.0625]
data[ProgramID == 4042 & is.na(QuadSize_m2), QuadSize_m2 := fcase(SampleDate == as_date("2014-06-11"), 1,
SampleDate >= as_date("2014-11-11") & SampleDate <= as_date("2015-01-22"), 0.33,
SampleDate >= as_date("2015-03-04"), 0.0625)]
data[ProgramID == 5035, QuadSize_m2 := NA]
qs_dat <- table_template()
flagged_data_list <- list()
for (i in indicators){
i_id <- ref_parameters[Habitat==h & IndicatorName==i, IndicatorID]
# unique parameters included for each indicator/habitat combo
threshold_ids <- ref_parameters[Habitat==h & IndicatorName==i, unique(ThresholdID)]
qs_dat <- table_template()
for(t_id in threshold_ids){
p <- ref_parameters[ThresholdID==t_id, ParameterName]
param_id <- ref_parameters[ThresholdID==t_id, ParameterID]
if(p %in% c("Density","Reef Height","Percent Live")){
# Record summary for table overview
dat_par <- data[ParameterName==p,
.(ParameterID = param_id,
ParameterName = p,
ParameterUnits = NA,
IndicatorID = i_id,
IndicatorName = i,
Habitat = h,
ThresholdID = t_id,
q_low = quantile(ResultValue, probs = quant_low),
q_high = quantile(ResultValue, probs = quant_high),
mean = mean(ResultValue),
n_tot = length(ResultValue))] %>% unique()
# pull high and low quantiles for filtering
quant_low_value <- dat_par$q_low
quant_high_value <- dat_par$q_high
# grab subset of data that falls below quantile limit
subset_low <- indicator_data[ParameterName==p & ResultValue < quant_low_value, ]
subset_low$q_subset <- "low"
# grab subset of data that falls above quantile limit
subset_high <- indicator_data[ParameterName==p & ResultValue > quant_high_value, ]
subset_high$q_subset <- "high"
# combine datasets for display in report
combined_subset <- bind_rows(subset_low, subset_high)
# Append data directory with included, excluded data
flagged_data_list[[i]][[p]] <- combined_subset
# Add n_q_low and n_q_high to dat_par table
dat_par$n_q_low <- nrow(subset_low)
dat_par$n_q_high <- nrow(subset_high)
dat_par$QuadSize_m2 <- NA
# append to make long-form table
qs_dat <- rbind(qs_dat, dat_par, fill=TRUE)
} else {
quad_size <- ref_parameters[ThresholdID==t_id, unique(QuadSize_m2)]
if(!is.na(quad_size)){
filtered_data <- data[ParameterName==p & QuadSize_m2==quad_size, ]
dat_par <- filtered_data[ ,
.(ParameterID = param_id,
ParameterName = p,
ParameterUnits = NA,
IndicatorID = i_id,
IndicatorName = i,
Habitat = h,
ThresholdID = t_id,
QuadSize_m2 = quad_size,
q_low = quantile(ResultValue, probs = quant_low),
q_high = quantile(ResultValue, probs = quant_high),
mean = mean(ResultValue),
n_tot = length(ResultValue))] %>% unique()
# pull high and low quantiles for filtering
quant_low_value <- dat_par$q_low
quant_high_value <- dat_par$q_high
# grab subset of data that falls below quantile limit
subset_low <- filtered_data[ResultValue < quant_low_value, ]
subset_low$q_subset <- "low"
# grab subset of data that falls above quantile limit
subset_high <- filtered_data[ResultValue > quant_high_value, ]
subset_high$q_subset <- "high"
# combine datasets for display in report
combined_subset <- bind_rows(subset_low, subset_high)
# New param name
newParamName <- paste0(p,"(",quad_size,")")
# Append data directory with included, excluded data
flagged_data_list[[i]][[newParamName]] <- combined_subset
# Add n_q_low and n_q_high to dat_par table
dat_par$n_q_low <- nrow(subset_low)
dat_par$n_q_high <- nrow(subset_high)
} else {
filtered_data <- data[ParameterName==p & is.na(QuadSize_m2), ]
dat_par <- filtered_data[ ,
.(ParameterID = param_id,
ParameterName = p,
IndicatorID = i_id,
IndicatorName = i,
Habitat = h,
ThresholdID = t_id,
QuadSize_m2 = NA,
q_low = quantile(ResultValue, probs = quant_low),
q_high = quantile(ResultValue, probs = quant_high),
mean = mean(ResultValue),
n_tot = length(ResultValue))] %>% unique()
# pull high and low quantiles for filtering
quant_low_value <- dat_par$q_low
quant_high_value <- dat_par$q_high
# grab subset of data that falls below quantile limit
subset_low <- filtered_data[ResultValue < quant_low_value, ]
subset_low$q_subset <- "low"
# grab subset of data that falls above quantile limit
subset_high <- filtered_data[ResultValue > quant_high_value, ]
subset_high$q_subset <- "high"
# combine datasets for display in report
combined_subset <- bind_rows(subset_low, subset_high)
# New param name
newParamName <- paste0(p,"(",quad_size,")")
# Append data directory with included, excluded data
flagged_data_list[[i]][[newParamName]] <- combined_subset
# Add n_q_low and n_q_high to dat_par table
dat_par$n_q_low <- nrow(subset_low)
dat_par$n_q_high <- nrow(subset_high)
}
# append to make long-form table
qs_dat <- rbind(qs_dat, dat_par, fill=TRUE)
}
}
# Record overall results
qs <- rbind(qs, qs_dat, fill=TRUE)
}
print(paste0(file_short, " export done"))
data_directory[[h]] <- flagged_data_list
# Report filename
file_out <- paste0(gsub("/","_",gsub(" ", "_", h)), "_IQ_Report")
# Render report
if(render_reports){
rmarkdown::render(input = "IQ_Report.Rmd",
output_format = "pdf_document",
output_file = paste0(file_out, ".pdf"),
output_dir = "output",
clean = TRUE)
unlink(paste0("output/", file_out, ".md"))
}
}
if(h=="Coastal Wetlands"){
file <- str_subset(seacardat, "All_CW")
# shortened filename for display in report
file_short <- tail(str_split(file, "/")[[1]], 1)
# get list of indicators within a given habitat
indicators <- ref_parameters[Habitat==h, unique(IndicatorName)]
# load in habitat data
data <- fread(file, sep="|", na.strings = nas)
data <- data[Include==1 & MADup==1 & !is.na(ResultValue), ]
qs_dat <- table_template()
flagged_data_list <- list()
for (i in indicators){
# unique parameters included for each indicator/habitat combo
parameters <- ref_parameters[Habitat==h & IndicatorName==i, unique(ParameterName)]
#Sg1 for Coastal Wetlands
sg1_include <- c("Mangroves and associates","Marsh","Invasives")
for (p in parameters){
if(p=="Total/Canopy Percent Cover"){
indicator_data <- data
} else {
indicator_data <- data[SpeciesGroup1 %in% sg1_include, ]
}
# Grab relevant IDs for each parameter
param_id <- ref_parameters[Habitat==h & ParameterName==p & IndicatorName==i, ParameterID]
threshold_id <- ref_parameters[Habitat==h & ParameterName==p & IndicatorName==i, ThresholdID]
i_id <- ref_parameters[Habitat==h & ParameterName==p & IndicatorName==i, IndicatorID]
# Record summary for table overview
dat_par <- indicator_data[ParameterName==p,
.(ParameterID = param_id,
ParameterName = p,
ParameterUnits = NA,
IndicatorID = i_id,
IndicatorName = i,
Habitat = h,
ThresholdID = threshold_id,
q_low = quantile(ResultValue, probs = quant_low),
q_high = quantile(ResultValue, probs = quant_high),
mean = mean(ResultValue),
n_tot = length(ResultValue))]
# pull high and low quantiles for filtering
quant_low_value <- dat_par$q_low
quant_high_value <- dat_par$q_high
# grab subset of data that falls below quantile limit
subset_low <- indicator_data[ParameterName==p & ResultValue < quant_low_value, ]
subset_low$q_subset <- "low"
# grab subset of data that falls above quantile limit
subset_high <- indicator_data[ParameterName==p & ResultValue > quant_high_value, ]
subset_high$q_subset <- "high"
# combine datasets for display in report
combined_subset <- bind_rows(subset_low, subset_high)
# Append data directory with included, excluded data
flagged_data_list[[i]][[p]] <- combined_subset
# Add n_q_low and n_q_high to dat_par table
dat_par$n_q_low <- nrow(subset_low)
dat_par$n_q_high <- nrow(subset_high)
dat_par[ , c('sub_parameter', 'QuadSize_m2')] = NA