-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.R
1945 lines (1654 loc) · 77.3 KB
/
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
##########################################################
# S E N T I N E L #
# Sensor Network Intelligent Emissions Locator #
##########################################################
# M.K. MacDonald -//- ORD/CEMM/AMCD/SFSB -//- macdonald.megan@epa.gov
# Rev. 1.1: January
# This is a Shiny web application. You can run the application by clicking the 'Run App' button above.
# Note this software is not yet in final form. Please direct any questions or bug reports to the email above.
##########################################################
options(install.packages.check.source = "no")
# install pkgs
library(shiny)
library(dplyr)
library(DT)
library(shinyWidgets)
library(janitor)
library(shinydashboard)
library(shinycssloaders)
library(rhandsontable)
library(data.table)
library(stringr)
library(rhandsontable)
library(leaflet)
library(openair)
library(lattice)
library(plotly)
library(tidyverse)
library(lubridate)
library(ggpubr)
library(tinytex)
# tinytex::install_tinytex() ## make sure this is run the first time running the app
library(knitr)
library(kableExtra)
library(tidyverse)
library(rmarkdown)
library(htmltools)
library(devtools)
#install_github("davidcarslaw/openairmaps", force = TRUE) ## make sure this is run the first time running the app
library(openairmaps)
# baseline Functions
library(quantreg)
library(splines2)
library(splines)
library(zoo)
source("getBaseline.R") ## found in app folder
options(scipen=999) # turn off scientific notation in app
########################################################### app starts here:
options(shiny.maxRequestSize=30*1024^2)
# User Interface Build
ui <- dashboardPage( ###################################################### build sidebar
skin = "black",
dashboardHeader(title = "SENTINEL"),
dashboardSidebar(
sidebarMenu(
tags$a(img(src="ngemlogo.png", width = 125,
style="display: block; margin-left: auto; margin-right: auto;"),
href="https://www.epa.gov/air-research/next-generation-emission-measurement-ngem-research-fugitive-air-pollution"),
menuItem(
"Data Upload",
tabName = "DataUpload",
icon = icon("fas fa-turn-up")
),
menuItem(
"Data Check",
tabName = "DataCheck",
icon = icon("fas fa-check")
),
menuItem( # make side bar menu items
"Dashboard",
tabName = "Dashboard",
icon = icon("fas fa-house")
),
menuItem( # make side bar menu items
"Data Table",
tabName = "DataTable",
icon = icon("fas fa-list")
),
menuItem(
"QA Tables",
tabName = "QA Tables",
icon = icon("fas fa-wrench"),
menuSubItem('Single Node',
tabName = 'singlenode',
icon = icon('fas fa-chevron-right')),
menuSubItem('Collocated Nodes',
tabName = 'multinode',
icon = icon('fas fa-chevron-right'))
),
menuItem(
"About",
tabName = "about",
icon = icon("fas fa-heart")
)
)
),
dashboardBody( ################################################## build main page of app
# tags$head(tags$style(HTML(' /* body */
# .content-wrapper, .right-side {
# background-color: #FFFFFF;
# }
# '))),
setBackgroundColor("ghostwhite"),
tags$head(
tags$style(HTML(".main-sidebar { font-size: 25px; }")) #change the font size to 20
),
tabItems(
# DATA UPLOAD PAGE -------------------------------------------------------
tabItem(tabName = "DataUpload",
tags$style(type="text/css",
".shiny-output-error { visibility: hidden; }",
".shiny-output-error:before { visibility: visible; content: 'Timestamp,Sensor ID, and Signal 1 must be identified to generate Table '; }"
),
# h4("Upload one or more data files from any number of sensors of the same type in .csv format.
# Files should all have the same structure but can be from different unit IDs.
# Use column naming tool to indicate which columns are present. Sensor ID, Timestamp, and Signal are required. "),
fluidRow(style = "background-color:ghostwhite;",
column(6,
#upload files
fileInput("files",
label = h4("Upload"),
multiple = TRUE)
),
column(6,
br(),
br(),
downloadButton('saveQAfile',"Download Compiled Data"),
radioButtons(
"skip_val",
"Header lines to skip?",
choices = c(0,1,2,3),
selected = 0,
inline = TRUE
)
)
),
br(),
fluidRow(style = "background-color:ghostwhite;",
column(4,
tabsetPanel(
#Required Cols
tabPanel(
h4("ID/Time"),
uiOutput("ID_column"),
uiOutput("Time_column"),
uiOutput("Time_Zone"),
selectInput("Time_format", "Time Format", c("%d-%b-%Y %H:%M:%S","%Y-%m-%d %H:%M:%S","%m-%d-%Y %H:%M:%S","%d-%m-%Y %H:%M:%S","%m/%d/%y %H:%M:%S", "%m/%d/%Y %H:%M:%S", "%m/%d/%Y %H:%M"), selected = "%d-%b-%Y %H:%M:%S"),
),
tabPanel(
h4("Signal"),
uiOutput("Signal_column"),
selectInput("Signal_units", "Signal Units?", c("ppm", "ppb"))
),
tabPanel(
h4("Met"),
uiOutput("WS_column"),
selectInput("WS_units", "WS Units?", c("mph" = 2.237, "m/s" = 1), selected = 1),
uiOutput("WD_column"),
#numericInput("WD_offset_val", label = h5("Add Wind Direction offset?"), value = 0)
),
# Optional Cols
tabPanel(
h4("Other"),
uiOutput("Temp_column"),
selectInput("Temp_units", "Temperature Units?", c("C", "F")),
uiOutput("RH_column"),
uiOutput("Lat_column"),
uiOutput("Long_column"),
uiOutput("Can_column")
)
)
),
column(8, style = "background-color:ghostwhite;",
#display df
# fluidRow(column(align = "center", width = 12, DT::dataTableOutput("table", width = 700)))
rHandsontableOutput("upload_table")
)
)
),
# DATA CHECK PAGE ---------------------------------------------------------
tabItem(tabName = "DataCheck",
h3("Data Check"),
br(),
# summary table showing canisters/QA/day ranges of spod units and lat/long
fluidRow(column(align = "center", width = 12, withSpinner(DT::dataTableOutput("summarytable", width = 900))))
),
# DASHBOARD PAGE ----------------------------------------------------------
tabItem(tabName = "Dashboard",
fluidRow(
column(9,
uiOutput("unitselect")
),
column(2,
radioButtons("ws_select", label = "Remove low WS?",
choices = c("All Data", ">1 m/s"),
selected = "All Data", inline=TRUE)
),
column(1,
downloadButton("report", "Export"),
)
),
fluidRow( ## SDI row
tabBox( ## signal map
title = "Signal Map",side = "right", ### Signal Map Box
tabPanel(h4("Graph"),
fluidRow(leafletOutput("polarmap", height = "550px") %>% withSpinner(color = "#0dc5c1"), height = "550px"),
textOutput("latlongtext"),
),
tabPanel(h4("Controls"), "Controls",
sliderInput(
"windfilterInput",
label = h4("Wind Speed Filter:"),
min = 0,
max = 12,
value = c(0,7)
),
selectInput(
"statselect",
label = h4("Select Stat:"),
choices = list(
"Median" = "median",
"Weighted Mean" = "weighted.mean",
"Maximum" = "max", "nwr" = "nwr"
),
selected = "median"
),
h6("For less than 200 data points, selct 'nwr' "),
height = "500px"
), height = "500px"
),
tabBox(# SDI plots box
title = "SDI plots", side = "right", ### SDI plots box
tabPanel(h4("SDI"),
fluidRow(
box(
selectInput(
"statselectSDI",
label = h4("Select SDI Stat:"),
choices = list(
"Median" = "median",
"Weighted Mean" = "weighted.mean",
"Mean" = "mean",
"Maximum" = "max", "nwr" = "nwr"
),
selected = "median"
),
plotOutput("SDI")%>% withSpinner(color="#0dc5c1"),
height = "550px", width = "600px")), height = "550px", width = "600px"
),
tabPanel(h4("Freq"), #frequency plot
fluidRow(
box(
selectInput(
"statselectFREQ",
label = h4("Select Frequency Stat:"),
choices = list(
"Median" = "median",
"Weighted Mean" = "weighted.mean",
"Mean" = "mean",
"Maximum" = "max"
),
selected = "median"
),
plotOutput("FREQ") %>% withSpinner(color="#0dc5c1"),
height = "550px", width = "600px")), height = "550px", width = "600px"
),
tabPanel(h4("Wind Rose"), #Wind Rose plot
fluidRow(
box(plotOutput("WR") %>% withSpinner(color = "#0dc5c1"),
height = "550px", width = "600px")), height = "550px", width = "600px")),
height = "550px", width = "600px"
),
br(),
br(),
fluidRow( ### Time Series plots box
tabBox(
title = "Time Series",side = "right",
tabPanel(h4("Baseline"), h4("Baseline Fit: Raw signal trace (5 minute values) plotted in black with baseline fit (df = 10) plotted in red"),
plotlyOutput("BCplot")),
tabPanel(h4("WD"), h4("Wind Direction: Baseline corrected signal trace (5 minute values) plotted in black with wind direction plotted in green (5 minute values)"),
plotlyOutput("windplot")),
tabPanel(h4("WS"), h4("Wind Speed: Baseline corrected signal trace (5 minute values) plotted in black with wind direction plotted in gray (5 minute values)"),
plotlyOutput("windspeedplot")),
tabPanel(h4("Calibrations"), h4("Calibrations: Baseline corrected signal trace (5 minute values) plotted in black with user-reported calibration periods plotted as points, if collected during this time frame"),
plotlyOutput("CALplot")),
tabPanel(h4("RH"), h4("RH: Baseline corrected signal trace (5 minute values) plotted in black with Relative Humidity (%) plotted in purple"),
plotlyOutput("RHplot")),
tabPanel(h4("Temp"), h4("Temperature: Baseline corrected signal trace (5 minute values) plotted in black with temperature (deg C) plotted in blue"),
plotlyOutput("Tplot")),
tabPanel(h4("Triggers"), h4("Canister Triggers: Baseline corrected signal trace (5 minute values) plotted in black with canister triggers plotted as points, if collected during this time frame"),
plotlyOutput("canplot")),
width = 12
), width = 12
),
),
# DATA TABLE PAGE ---------------------------------------------------------
tabItem(
tabName = "DataTable",
h4("Table Results"),
br(),
downloadButton('Download',"Download .CSV data"),
br(),
br(),
DTOutput(outputId = "datatab", width = 1000)
),
# CAL TABLE PAGE ----------------------------------------------------------
tabItem(
tabName = "singlenode",
h2("QA Table for 1 Unit"),
br(),
uiOutput("calunitselect"),
uiOutput("singlenodestarttime"),
uiOutput("singlenodeendtime"),
br(),
radioButtons("durationInput", h4("Select length of QA frame:"),
choices = c("1 min" = 60, "1 hour" = 3600, "1 day" = 86400),
selected = "1 min"),
radioButtons("freqfile", h4("Select Frequency of sensor values:"),
choices = c("10 sec" = 10,
"30 sec" = 30,
"1 min" = 60),
selected = "10 sec"),
downloadButton("singlenodereport", "Generate report"),
box(tableOutput("draw_caltab"), width = 12)),
### add small plotly graph???
# COLLOCATED CAL TABLE PAGE --------------------------------------------
tabItem(tabName = "multinode",
h2("Sensor Agreement"),
h5("QA Table for 2 co-located units during same time frame"),
br(),
br(),
fluidRow(
column(6,
uiOutput("calunitselect1"),
uiOutput("calunitselect2")
),
column(6,
uiOutput("multinodestarttime"),
uiOutput("multinodeendtime"),
downloadButton("multinodereport", "Generate report")
)
),
box(tableOutput("draw_subcaltab"), width = 12),
box(plotlyOutput("SensorAgreement_buildplot"), width = 12)
),
# ABOUT PAGE --------------------------------------------------------------
tabItem(tabName = "about",
fluidRow( width = 12,
box( width = 12,
br(),
HTML("<h3> <b>SENTINEL:</b> An application for automated fenceline sensor data analysis </h3>"),
br(),
h4(div(em("Purpose:"))),
br(),
h4("There is growing interest in fenceline monitoring around chemical facilities.
Fenceline sensors used in these monitoring applications can collect large amounts
of concentration and meteorological data for extended time periods. The SENsor
InTellIgeNt Emissions Locator (SENTINEL) application helps users compile, process,
and analyze data from fenceline sensors. This application delivers these
capabilities in a user-friendly interface that can combine and process daily data
files from multi-sensor deployments, allowing users to gain insights from compiled
sensor data over time. The SENTINEL app is one of the technologies developed under
the Next Generation Emissions Measurements (NGEM) program. We awknowledge contributions
from past and present contributors to this software: Halley Brantley, Yadong Xu,
Wei Tang, and Gustavo Quieroz."),
br()
)
),
fluidRow(
box( width = 12,
h4("Version 1.0 (Aug 2024)"),
br(),
h4("Contact:"),
h4("macdonald.megan@epa.gov"),
br(),
#actionButton("pdf", "SENTINEL User Guide",class = "btn-success", class = "btn-lg", onclick = "window.open('SENTINEL Shiny App User Guide V1.pdf')"),
br()
)
)
)
)
)
)
# End of UI build
# Start of server build
server <- function(input, output) {
options(shiny.maxRequestSize=60*1024^4)
# Data Upload Page Functions ----------------------------------------------
# read in files
test <- reactive({
req(input$files)
req(input$skip_val)
inFile <- input$files
skip_num <- as.numeric(input$skip_val)
print(skip_num)
if (is.null(inFile)){
return(NULL)
} else {
numfiles = nrow(inFile)
filelist = list()
for (i in 1:numfiles)
{ # check for SENSIT SPod data which does not carry a sensor ID col.
#read in data file
Data <- fread(input$files[[i, 'datapath']], skip = skip_num) # will have to edit to "skip to usable dat" somehow ... EDITED##############
#check for Sensit Connect data, which does not carry the Sensor Id col
print(Data)
filename <- input$files$name[[i]]
print(filename)
Data$spod_check <- ifelse(grepl("SPOD_Data_Export", filename, fixed = TRUE) == TRUE, str_match(filename, "SPOD_Data_Export_\\s*(.*?)\\s*_")[,2], "0" )
print(str_match(filename, "SPOD_Data_Export_\\s*(.*?)\\s*_")[,2])
# Roll up data
filelist[[i]] <- Data
}
#do.call(rbind, filelist)
#plyr:::rbind.fill(lapply(x,function(y){as.data.frame(t(filelist),stringsAsFactors=FALSE)}))
data.table::rbindlist(filelist, fill = TRUE)
}
})
##creating dropdowns
output$ID_column <- renderUI({
req(input$files)
test_df <- test()
selectizeInput("ID_column",
"Sensor ID:",
c(names(test_df), "NA"),
selected= "spod_check")
})
output$Time_column <- renderUI({
req(input$files)
test_df <- test()
selectizeInput("Time_column",
"Date/Time stamp:",
c(names(test_df), "NA"),
selected=ifelse(any(names(test_df) == 'Local Date Time'),'Local Date Time', 'NA'))
})
output$Time_Zone <- renderUI({
req(input$files)
selectizeInput("Time_Zone",
"Select Time Zone (choose local time for SPods):",
c( "UTC", "America/New_York", "America/Chicago", "America/Denver", "America/Phoenix", "America/Los_Angeles", "America/Anchorage"),
selected="America/New_York")
})
output$Signal_column <- renderUI({
req(input$files)
test_df <- test()
selectizeInput("Signal_column",
"Sensor Signal 1:",
c(names(test_df), "NA"),
selected=ifelse(any(names(test_df) == 'pid1_PPB_Calc'),'pid1_PPB_Calc', 'NA'))
})
output$WS_column <- renderUI({
req(input$files)
test_df <- test()
selectizeInput("WS_column",
"Wind Speed:",
c(names(test_df), "NA"),
selected=ifelse(any(names(test_df) == 'ws_speed'),'ws_speed', 'NA'))
})
output$WD_column <- renderUI({
req(input$files)
test_df <- test()
selectizeInput("WD_column",
"Wind Direction (deg):",
c(names(test_df), "NA"),
selected=ifelse(any(names(test_df) == 'ws_direction'),'ws_direction', 'NA'))
})
output$Temp_column <- renderUI({
req(input$files)
test_df <- test()
selectizeInput("Temp_column",
"Temperature:",
c(names(test_df), "NA"),
selected=ifelse(any(names(test_df) == 'temp'),'temp', 'NA'))
})
output$RH_column <- renderUI({
req(input$files)
test_df <- test()
selectizeInput("RH_column",
"Relative Humidity (%):",
c(names(test_df), "NA"),
selected=ifelse(any(names(test_df) == 'rh_Humd'),'rh_Humd', 'NA'))
})
output$Lat_column <- renderUI({
req(input$files)
test_df <- test()
selectizeInput("Lat_column",
"Latitude (decimal):",
c(names(test_df), "NA"),
selected=ifelse(any(names(test_df) == 'lat'),'lat', 'NA'))
})
output$Long_column <- renderUI({
req(input$files)
test_df <- test()
selectizeInput("Long_column",
"Longitude (decimal):",
c(names(test_df), "NA"),
selected=ifelse(any(names(test_df) == 'long'),'long', 'NA'))
})
output$Can_column <- renderUI({
req(input$files)
test_df <- test()
selectizeInput("Can_column",
"Active Canister trigger:",
c(names(test_df), "NA"),
selected=ifelse(any(names(test_df) == 'trig.trig_activeFlag'),'trig.trig_activeFlag', 'NA'))
})
# build DF to recieve new col names
df_new <- reactive({
req(input$files)
old_signal_name <- input$Signal_column
old_sensor_id_name <- input$ID_column
old_WS_name <- input$WS_column
old_WD_name <- input$WD_column
old_Temp_name <- input$Temp_column
old_RH_name <- input$RH_column
old_Lat_name <- input$Lat_column
old_Long_name <- input$Long_column
old_Can_name <- input$Can_column
old_Time_name <- input$Time_column
df_1 <- test()
names(df_1)[names(df_1) == old_signal_name] <- 'Signal_1'
names(df_1)[names(df_1) == old_sensor_id_name] <- 'Sensor_ID'
names(df_1)[names(df_1) == old_WS_name] <- 'WS'
names(df_1)[names(df_1) == old_WD_name] <- 'WD'
names(df_1)[names(df_1) == old_Temp_name] <- 'Temp'
names(df_1)[names(df_1) == old_RH_name] <- 'RH'
names(df_1)[names(df_1) == old_Lat_name] <- 'Lat'
names(df_1)[names(df_1) == old_Long_name] <- 'Long'
names(df_1)[names(df_1) == old_Can_name] <- 'Canister'
names(df_1)[names(df_1) == old_Time_name] <- 'Timestamp'
df_1 <- as.data.frame(df_1)
print(df_1)
return(df_1)
})
# export CSV file of aggregated data - make a "daily files download" option ?? add to data check page?
output$saveQAfile <- downloadHandler(
filename = function() {
QA_df <- test_df_new()
paste0("Data_Export_", Sys.Date(), "_QA.csv", sep="")
},
content = function(file) {
readr::write_csv(hot_to_r(input$upload_table), file)
}
)
# Upload Table
output$upload_table <- renderRHandsontable({
req(input$Time_column) ##### this is causing red warning messages, find a way to suppress these?? also this is very slow...try with normal output table??
all_QA_static <- df_new()
all_QA_static[is.na(all_QA_static)] = " "
all_QA_static$QA <- "None"
all_QA_static$Timestamp <- as.character(all_QA_static$Timestamp)
flags <- c("None","Calibration","Interferance","Maintenance","Malfunction","Other","WD_Interference", "WD_Error")
rhandsontable(all_QA_static, width = 850, height = 550)%>%
hot_col(col = "QA", type = "dropdown", source = flags)%>%
hot_context_menu(allowRowEdit = FALSE, allowColEdit = FALSE)%>%
hot_cols(columnSorting = TRUE)
})
####### Data Processing, Cleaning, and Aggregating
data_5min <- reactive({
WSunit <- input$WS_units
TimeZone <- input$Time_Zone
DF = hot_to_r(input$upload_table)
DF <- as.data.frame(DF)
DF$wsunit <- WSunit
time_format <- input$Time_format
##################### Data prep and cleaning
#formats <- c( "%d-%b-%Y %H:%M:%S","%Y-%m-%d %H:%M:%S", "%m/%d/%y %H:%M:%S", "%m/%d/%Y %H:%M:%S" )
formats <- time_format
DF$Timestamp <- stringr::str_replace_all(DF$Timestamp, " AM", "") #strip out any AM/PM
DF$Timestamp <- stringr::str_replace_all(DF$Timestamp, " PM", "") #strip out any AM/PM
print(DF$Timestamp)
DF$Timestamp <- lubridate::parse_date_time(DF$Timestamp, formats, tz = TimeZone)
#DF$Timestamp <- as.POSIXct(DF$Timestamp, format = "%Y-%m-%d %H:%M:%S", tz = TimeZone)
#force cols to numeric if they exist ; create NA versions if they dont exist so QA can run
DF <- DF %>% mutate(across(matches('Signal_1|WS|WD|Temp|RH|Canister|Lat|Long'), as.numeric))
if(!'WS' %in% names(DF)) DF <- DF %>% mutate(WS = NA)
if(!'WD' %in% names(DF)) DF <- DF %>% mutate(WD = NA)
if(!'Signal_1' %in% names(DF)) DF <- DF %>% mutate(Signal_1 = NA)
if(!'Lat' %in% names(DF)) DF <- DF %>% mutate(Lat = NA)
if(!'Long' %in% names(DF)) DF <- DF %>% mutate(Long = NA)
if(!'Canister' %in% names(DF)) DF <- DF %>% mutate(Canister = NA)
if(!'Temp' %in% names(DF)) DF <- DF %>% mutate(Temp = NA)
if(!'RH' %in% names(DF)) DF <- DF %>% mutate(RH = NA)
DF <- as.data.frame(DF)
# apply wind speed correction to m/s
DF$WS_mps <- as.numeric(DF$WS) / as.numeric(DF$wsunit,2)
# add U and V for WD averaging
DF$u <- DF$WS_mps * sin(2 * pi * DF$WD/360)
DF$v <- DF$WS_mps * cos(2 * pi * DF$WD/360)
# Check for lat and long // round to prevent slightly off coordinates // return 0 to NA for mapping
if(!'Lat' %in% names(DF)) DF <- DF %>% add_column(Lat = 0)
if(!'Long' %in% names(DF)) DF <- DF %>% add_column(Long = 0)
DF$Lat <- round(DF$Lat, 3)
DF$Long <- round(DF$Long, 3)
DF$Lat[is.na(DF$Lat)] <- 0
DF$Long[is.na(DF$Long)] <- 0
##################### Complete Auto QA scan
##### look for QA col, if not there, add it
if(!'QA' %in% names(DF)) DF <- DF %>% add_column(QA = "None")
# check for repeated wind/PID vals
DF$QA <- ifelse(rep(rle(DF$WS)$lengths,
times = rle(DF$WS)$lengths) * sign(DF$WS) > 30, "WS_repeat", DF$QA ) # flag 10
DF$QA <- ifelse(rep(rle(DF$WD)$lengths,
times = rle(DF$WD)$lengths) * sign(DF$WD) > 30, "WD_repeat", DF$QA ) # flag 11
DF$QA <- ifelse(rep(rle(DF$Signal_1)$lengths,
times = rle(DF$Signal_1)$lengths) * sign(DF$Signal_1) > 30, "Sig_repeat", DF$QA ) # flag 12
# check for illogical wind vals
DF$QA <- ifelse(DF$WS > 40,"WS_offscale",DF$QA ) # flag 11
DF$QA <- ifelse(DF$WD > 360 | DF$WD < 0,"WD_offscale",DF$QA ) # flag 12
# check for missing data
DF$QA <- ifelse(is.na(DF$Signal_1),"Missing_Signal",DF$QA ) # flag 13
######################## end of AutoQA Flagging
# Baseline Correction (default to 10)
DF <- DF[!is.na(DF$Timestamp),]
DF$bc <- (DF$Signal_1 - getBaseline(DF$Signal_1, DF$Timestamp, df = 10))
print(DF)
# roll up to 5 min
timeBase <- "5 min"
timeBreaks <- seq(round(min(DF$Timestamp, na.rm = T), "min"),
round(max(DF$Timestamp, na.rm = T), "min"), timeBase)
DF$timecut <- cut(DF$Timestamp, timeBreaks)
# average vals to 5 min
Data_5 <- DF %>%
dplyr::group_by(Sensor_ID, timecut) %>%
dplyr::summarize(
signal_1 = mean(Signal_1, na.rm = TRUE),
bc_signal_1 = mean(bc, na.rm = TRUE),
ws = mean(WS_mps, na.rm = TRUE),
Temp = mean(Temp, na.rm = TRUE),
RH = mean(RH, na.rm = TRUE),
U = mean(u, na.rm = TRUE),
V = mean(v, na.rm = TRUE),
QA = paste(unique(QA), collapse = ', '),
Lat = unique(Lat, na.rm = TRUE),
Long = unique(Long, na.rm = TRUE),
Canister = paste(unique(Canister), collapse = ', ')
)
#calc WD based on U and V (leave WS as a scalar calc)
Data_5$wd <- atan2(-Data_5$U, -Data_5$V)*180/pi + 180
print(Data_5)
#print(sum(is.na(Data_5$timecut)))
return(Data_5)
})
# Data Check Page Functions -----------------------------------------------
#display data (summary table showing 5 min data)
output$summarytable <- DT::renderDataTable({
req(input$files)
TimeZone <- input$Time_Zone
df <- as.data.frame(data_5min())
df$timecut <- as.POSIXct(df$timecut, format = "%Y-%m-%d %H:%M:%S", tz = TimeZone)
#df$timecut <- lubridate::parse_date_time(df$timecut,orders = "ymd HMS", tz = TimeZone)
summary <- df %>%
dplyr::group_by(Sensor_ID) %>%
dplyr::summarise(
Start_Time = min(timecut, na.rm = T),
End_Time = max(timecut, na.rm = T),
Lat = unique(Lat),
Long = unique(Long),
Count = n(),
QA =paste(unique(QA), collapse = ', '),
Canister = paste(unique(Canister), collapse = ', ')
)
summary$Start_Time <- as.character(summary$Start_Time)
summary$End_Time <- as.character(summary$End_Time)
datatable(summary,
selection = 'single',
options = list(autoWidth = TRUE,
scrollX = TRUE,
searching = FALSE,
lengthChange = FALSE),
rownames= FALSE)
})
#### add export options here: daily 5 min processed files or one large file?
# Dashboard Page Functions ------------------------------------------------
# build in option to exclude low wind speed data from analysis
data_5min_highws <- reactive({
req(data_5min())
all <- data_5min()
data_5min_highws <- subset(all, all$ws >= 1)
})
# select between SPods for analysis
output$unitselect <- renderUI({
choice <- unique(data_5min()$Sensor_ID)
selectInput("unitselect",h4("Select unit to display:"), choices = choice, selected = choice[1])
})
# select active SPod data set (> 1 min or normal)
data_5min_active <- reactive({
if (input$ws_select == "All Data")
data_5min()
else if (input$ws_select == ">1 m/s")
data_5min_highws()
# else
# stop("Unexpected dataset")
})
# Leaflet polar map
output$polarmap <- renderLeaflet({
req(input$unitselect)
req(input$statselect)
unitinput <- input$unitselect
print(unitinput)
statinput <- input$statselect
req(data_5min_active())
data_all_5 <- as.data.frame(data_5min_active())
data_all_5_1 <- subset(data_all_5,
data_all_5$ws >= input$windfilterInput[1] &
data_all_5$ws <= input$windfilterInput[2]&
data_all_5$QA == "None")
output$latlongtext <- renderText({ "Note: Basemap only displayed when lat/long data detected"})
polarMap(data_all_5_1,
latitude = 'Lat',
longitude = 'Long',
pollutant = 'bc_signal_1',
statistic = statinput,
provider = "Esri.WorldImagery",
key = TRUE,
#limits = "fixed",
# iconWidth = 450, iconHeight = 650,
# fig.width = 5, fig.height = 5,
par.settings=list(fontsize=list(text=19),
add.line = list(col = "white"),
axis.line = list(col = "white"),
axis.text = list(col = 'white'),
add.text = list(col = 'white'),
layout.widths = list(left.padding = 3, right.padding = 0, axis.key.padding = 0)
))
})
#str(trellis.par.get(), max.level = 1)
######################################################## SDI plots and Wind Roses
output$FREQ <- renderPlot({
req(input$statselectFREQ)
req(input$unitselect)
req(data_5min_active())
unitinput <- input$unitselect
# print(unitinput)
data_all_5 <- as.data.frame(data_5min_active())
data_all_5_1 <- subset(data_all_5,
data_all_5$Sensor_ID == input$unitselect &
data_all_5$QA == "None")
statFREQ <- input$statselectFREQ
trellis.par.set(theme = col.whitebg()) # make background transparent
polarFreq(data_all_5_1, pollutant = "bc_signal_1",fontsize = 18,
statistic = statFREQ, main = NULL, key.position = "right",
par.settings = col.whitebg())
})
SDI_build <- reactive({# SDI plot
req(data_5min_active())
req(input$statselectSDI)
data_all_5 <- as.data.frame(data_5min_active())
data_all_5_1 <- subset(data_all_5,
data_all_5$Sensor_ID == input$unitselect &
data_all_5$QA == "None")
statSDI <- input$statselectSDI
trellis.par.set(theme = col.whitebg()) # make background transparent
polarPlot(data_all_5_1, pollutant = "bc_signal_1", fontsize = 25,
statistic = statSDI, main = NULL, key.position = "right",
par.settings = col.whitebg())
})
output$SDI <- renderPlot({
SDI_build()
})
WR_build <- reactive({# Wind Rose plot
req(data_5min_active())
data_all_5 <- as.data.frame(data_5min_active())
data_all_5_1 <- subset(data_all_5,
data_all_5$Sensor_ID == input$unitselect &
data_all_5$QA == "None")
#trellis.par.set(background = list(col="green")) # make background transparent
trellis.par.set(theme = col.whitebg()) # make background transparent
windRose(data_all_5_1, fontsize = 18, paddle = F, cols = "hue",
main = NULL, key.position = "right",
par.settings=list(par.sub.text=list(cex=0.8),
col.whitebg()))
})
output$WR <- renderPlot({
WR_build()
})
######################################################## time series outputs
BCplot_build <- reactive({# background Correction plot
req(data_5min_active())
data_all_5 <- as.data.frame(data_5min_active())
data_all_5_1 <- subset(data_all_5,
data_all_5$Sensor_ID == input$unitselect &
data_all_5$QA == "None")
p <-
plot_ly(
data_all_5_1,
x = ~ timecut,
y = ~ signal_1,
type = "scatter", name = "Raw Signal",
hovertext = ~ paste0("time: ", data_all_5_1$timecut, "<br>", "WD: ", round(data_all_5_1$wd,2)),
hoverinfo = "text",
mode = "lines", showlegend = T, connectgaps = FALSE, line = list(color = "black")) %>%
layout(showlegend = T,
yaxis = list(title = paste0 ("5-min Signal (",input$Signal_units, ")"), showgrid = FALSE, showline = TRUE, mirror=TRUE),
legend = list(
orientation = "h",
x = 0.3,
y = -0.5
),
xaxis = list(type = 'Date', tickformat = "%m/%d/%y %H:%M", showgrid = FALSE, showline = TRUE, mirror=TRUE),
scene = list(xaxis = list(showgrid = F, showline = TRUE, mirror=TRUE),
yaxis = list(showgrid = F, showline = TRUE, mirror=TRUE))
)
p <- p %>% add_trace(y = data_all_5_1$signal_1 - data_all_5_1$bc_signal_1, name = 'Baseline', mode = 'lines', connectgaps = FALSE, line = list(color = "red"))
p
})
output$BCplot <- renderPlotly({ # baseline correction plot
BCplot_build()
})
WDplot_build <- reactive({ # Wind Direction plot
req(data_5min_active())
data_all_5 <- as.data.frame(data_5min_active())
data_all_5_1 <- subset(data_all_5,
data_all_5$Sensor_ID == input$unitselect &
data_all_5$QA == "None")
ay <- list(
tickfont = list(color = "black"),
overlaying = "y",
side = "right",
title = "5-min Signal (ppb)",
showgrid = FALSE,
showline = TRUE, mirror=TRUE)
w <-
plot_ly(
data_all_5_1,
x = ~timecut,
y = ~wd,
type = "scatter", name = "Wind Direction",
hovertext = ~ paste0("time: ", data_all_5_1$timecut),
hoverinfo = "text",
mode = "markers", showlegend = T, marker = list(color = "green")) %>%
layout(showlegend = T,
legend = list(
orientation = "h",
x = 0.3,
y = -0.5
),
xaxis = list(type = 'Date', tickformat = "%m/%d/%y %H:%M", showgrid = FALSE, mirror=TRUE),
scene = list(xaxis = list(showgrid = F,showline = TRUE, mirror=TRUE),
yaxis = list(showgrid = F, showline = TRUE, mirror=TRUE))
)
w <- w %>% add_trace(y = data_all_5_1$bc_signal_1, name = 'Signal', yaxis = "y2",type = 'scatter', mode = 'lines', connectgaps = FALSE, line = list(color = "black"), marker = list(color = 'black', opacity=0))
w <- w %>% layout(
yaxis2 = ay,
xaxis = list(title="Date", showgrid = FALSE, showline = TRUE, mirror=TRUE),
yaxis = list(title= list(text = "Wind Direction (Deg.)", font = list(color = 'darkgreen')), tickfont = list(color = 'darkgreen'), showgrid = FALSE, showline = TRUE, mirror=TRUE),
margin = list(l = 50, t = 50, b =50, r = 100, pad = 20))
w
})
output$windplot <- renderPlotly({ # wind direction plot
WDplot_build()
})
WSplot_build <- reactive({ # Wind Direction plot
req(data_5min_active())
data_all_5 <- as.data.frame(data_5min_active())
data_all_5_1 <- subset(data_all_5,
data_all_5$Sensor_ID == input$unitselect &
data_all_5$QA == "None")
ay <- list(
tickfont = list(color = "black",size = 20),
overlaying = "y",