-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.R
4689 lines (4087 loc) · 202 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
# Mirko Mantovani - Ashwani Khemani - Abhishek Vasudevan - 02/20/2019
##################################################### Libraries #####################################################
library(shiny)
library(devtools)
library(ggplot2)
library(shinydashboard)
library(scales) # needed for percent function
library(shinythemes) # themes for bootstrapPage, fluidPage, navbarPage, or fixedPage
library(dashboardthemes)
library(ggthemes)
library(shinyalert)
library(leaflet)
library(rgdal)
library(shinyWidgets)
library(viridis) # Color palette
library(cdlTools) # convert FIPS codes into names
library(htmltools) # to use htmlEscape function
library(RColorBrewer)
library(reshape2)
library(fst)
library(data.table)
library(dplyr)
library(tidyr)
library(lubridate)
library(tidyverse)
# R data APIs libraries
library(ropenaq)
library(darksky)
library(RSocrata)
library(base)
library(sp)
library(raster)
library(gstat)
# Sys.setenv(DARKSKY_API_KEY = "17b13339acc2cb53e53ea50ea4142528")
#use this key if the above one does not work
# Sys.setenv(DARKSKY_API_KEY = "049f7d70c4d28508cffd077381fad386")
#new key by abhishek
#Sys.setenv(DARKSKY_API_KEY = "5ba09d7b0b3669a512befe6433d35f33")
# Sys.setenv(DARKSKY_API_KEY = "3a786ec08cd24ff6a6f807d957d5cfff")
dark_sky_keys = c("17b13339acc2cb53e53ea50ea4142528","03ef91f707e08fe3b5ee58c41aaf8ac8","0f7f0150c770440e7e08122f989ffccb","2a59f67744c4cf2b3acd83e539881940","3a786ec08cd24ff6a6f807d957d5cfff","5ba09d7b0b3669a512befe6433d35f33")
Sys.setenv(DARKSKY_API_KEY = sample(dark_sky_keys,1) )
########################################### PREPROCESSING and VARIABLES DEFINITION #########################################
# Constants
TIME_RANGE_CURRENT = "Current"
TIME_RANGE_24HOURS = "Last 24 hours"
TIME_RANGE_7DAYS = "Last 7 days"
UPDATE_NODES_STATUS <- FALSE
time_ranges <- c(TIME_RANGE_CURRENT,TIME_RANGE_24HOURS,TIME_RANGE_7DAYS)
tracked_measures <- c("co","h2s","no2","o3","so2","pm2.5","pm10","temperature","humidity","intensity")
openaq_tracked_measures <- c("co","bc","no2","o3","so2","pm2.5","pm10")
darksky_tracked_measures <- c("temperature", "humidity", "windSpeed", "windBearing", "cloudCover", "visibility", "pressure", "ozone", "summary")
all_measures <- paste0("AoT-",tracked_measures)
all_measures <- c(all_measures,paste0("Darksky-",darksky_tracked_measures))
all_measures <- c(all_measures,paste0("OpenAQ-",openaq_tracked_measures))
all_measures <-all_measures[-which(all_measures=="Darksky-summary")]
value_types <- c("min","max","average")
tab1_measures <- c("co","h2s","no2","o3","so2","pm2.5","pm10","bc")
tab2_measures <- c("temperature", "humidity","intensity", "windSpeed", "windBearing", "cloudCover", "visibility", "pressure", "ozone", "summary")
last <- NULL
statistics <- c("Median","Max","90th percentile")
pie_chart_backgrounds <- "white" #bcdae0 1a4756
bar_chart_backgrounds <- "#bcdae0" #bcdae0
pie_chart_backgrounds_first <- "#bcdae0" #bcdae0
#Removed any existing files
if(file.exists("fst/all_nodes_24hours.fst"))
file.remove("fst/all_nodes_24hours.fst")
if(file.exists("fst/all_nodes_7days.fst"))
file.remove("fst/all_nodes_7days.fst")
######################### theme definition #############################
darker_c <- "rgb(30, 34, 68)"
middle_c <- "rgb(52, 57, 104)"
lighter_c <- "rgb(76, 82, 136)"
mirko_theme <- shinyDashboardThemeDIY(
### general
appFontFamily = "Arial"
,appFontColor = "rgb(204, 228, 249)" #"rgb(128,177,221)"
,bodyBackColor = cssGradientThreeColors(
direction = "down"
,colorStart = darker_c #"rgb(49,56,107)"
,colorMiddle = "rgb(71,59,109)"
,colorEnd = "rgb(78,88,149)"
,colorStartPos = 0
,colorMiddlePos = 70
,colorEndPos = 100
)
### header
,logoBackColor = lighter_c
,headerButtonBackColor = lighter_c
,headerButtonIconColor = "rgb(62,133,179)"
,headerButtonBackColorHover = "rgb(49,56,107)"
,headerButtonIconColorHover = "rgb(255,255,255)"
,headerBackColor = lighter_c
,headerBoxShadowColor = ""
,headerBoxShadowSize = "0px 0px 0px"
### sidebar
,sidebarBackColor = cssGradientThreeColors(
direction = "down"
,colorStart = lighter_c #"rgb(49,56,107)"
,colorMiddle = middle_c #"rgb(71,59,109)"
,colorEnd = darker_c #"rgb(78,88,149)"
,colorStartPos = 0
,colorMiddlePos = 70
,colorEndPos = 100
)
,sidebarShadowRadius = ""
,sidebarPadding = 10
,sidebarShadowColor = "0px 0px 0px"
,sidebarMenuBackColor = cssGradientThreeColors(
direction = "right"
,colorStart = "rgb(48,103,157)"
,colorMiddle = "rgb(65,79,129)"
,colorEnd = "rgb(47, 53, 99)"
,colorStartPos = 0
,colorMiddlePos = 40
,colorEndPos = 100
)
,sidebarMenuPadding = 3
,sidebarMenuBorderRadius = 25
,sidebarUserTextColor = "rgb(128,177,221)"
,sidebarSearchBackColor = "rgb(40,70,115)"
,sidebarSearchIconColor = "rgb(50,115,145)"
,sidebarSearchBorderColor = "rgb(30,60,105)"
,sidebarTabTextColor = "rgb(128,177,221)"
,sidebarTabTextSize = 13
,sidebarTabBorderStyle = "none"
,sidebarTabBorderColor = "none"
,sidebarTabBorderWidth = 0
,sidebarTabBackColorSelected = cssGradientThreeColors(
direction = "right"
,colorStart = "rgb(56,137,189)"
,colorMiddle = "rgb(65,95,145)"
,colorEnd = "rgb(68,84,137)"
,colorStartPos = 0
,colorMiddlePos = 60
,colorEndPos = 100
)
,sidebarTabTextColorSelected = "rgb(255,255,255)"
,sidebarTabRadiusSelected = "30px"
,sidebarTabBackColorHover = cssGradientThreeColors(
direction = "right"
,colorStart = "rgb(56,137,189)"
,colorMiddle = "rgb(65,95,145)"
,colorEnd = "rgb(68,84,137)"
,colorStartPos = 0
,colorMiddlePos = 50
,colorEndPos = 100
)
,sidebarTabTextColorHover = "rgb(255,255,255)"
,sidebarTabBorderStyleHover = "none"
,sidebarTabBorderColorHover = "none"
,sidebarTabBorderWidthHover = 0
,sidebarTabRadiusHover = "30px"
### boxes
,boxBackColor = cssGradientThreeColors(
direction = "right"
,colorStart = "rgb(70,75,125)"
,colorMiddle = "rgb(65,79,129)"
,colorEnd = "rgb(55,70,120)"
,colorStartPos = 0
,colorMiddlePos = 30
,colorEndPos = 100
)
,boxBorderRadius = 15
,boxShadowSize = "0px 0px 0px"
,boxShadowColor = ""
,boxTitleSize = 16
,boxDefaultColor = "rgb(49,56,107)"
,boxPrimaryColor = "rgb(141,192,241)"
,boxSuccessColor = "rgb(64,186,170)"
,boxWarningColor = "rgb(255,217,144)"
,boxDangerColor = "rgb(249,144,144)"
,tabBoxTabColor = "rgb(80,95,155)"
,tabBoxTabTextSize = 14
,tabBoxTabTextColor = "rgb(128,177,221)"
,tabBoxTabTextColorSelected = "rgb(255,255,255)"
,tabBoxBackColor = cssGradientThreeColors(
direction = "right"
,colorStart = "rgb(70,75,125)"
,colorMiddle = "rgb(65,79,129)"
,colorEnd = "rgb(55,70,120)"
,colorStartPos = 0
,colorMiddlePos = 30
,colorEndPos = 100
)
,tabBoxHighlightColor = "rgb(80,95,155)"
,tabBoxBorderRadius = 15
### inputs
,buttonBackColor = "rgb(72,190,229)"
,buttonTextColor = "rgb(40,63,106)"
,buttonBorderColor = "rgb(72,190,229)"
,buttonBorderRadius = 20
,buttonBackColorHover = "rgb(115,210,240)"
,buttonTextColorHover = "rgb(255,255,255)"
,buttonBorderColorHover = "rgb(115,210,240)"
,textboxBackColor = "rgb(40,70,115)"
,textboxBorderColor = "rgb(30,60,105)"
,textboxBorderRadius = 20
,textboxBackColorSelect = "rgb(40,70,115)"
,textboxBorderColorSelect = "rgb(30,60,105)"
### tables
,tableBackColor = "transparent"
,tableBorderColor = "rgb(80,95,155)"
,tableBorderTopSize = 1
,tableBorderRowSize = 1
)
############################################### UI ################################################
ui <- dashboardPage(
dashboardHeader(
title = "Chicago Real-Time AQ",
titleWidth = 250
),
dashboardSidebar(
disable = FALSE,
collapsed = FALSE,
width = 250,
sidebarMenu(
useShinyalert(),
span(h2("Main Menu", style = "margin-left: 10px; font-size: 20px;")),
menuItem("Geospatial Visualizations", tabName = "geospatial_viz"),
# menuItem("Tabular Visualizations", tabName = "tabular_viz"),
menuItem("Options",
materialSwitch(inputId = "switch_units", label = "Switch to Imperial units", status = "primary"),
materialSwitch(inputId = "heat_map", label = "Visualize heat map", status = "primary"),
materialSwitch(inputId = "nodes_table_switch", label = "Hide tabular nodes panel", status = "primary",value=FALSE)
),
menuItem("Heatmap Inputs",
div(
selectizeInput("heatmap_measure","Select measure",all_measures,selected="OpenAQ-o3",multiple=FALSE,options=NULL,width = "200%"),
selectizeInput("measure_type","Select value type",value_types,selected="average",multiple=FALSE,options=NULL,width = "200%"),
selectizeInput("map_time_range","Select time range",time_ranges,selected=TIME_RANGE_CURRENT,multiple=FALSE,options=NULL),width = "200%"),style = "font-size: 50%;"),
menuItem("About", tabName = "about")
),
includeCSS("style.css")
),
dashboardBody(
mirko_theme,
tags$head(
# Include custom JS
includeScript("sage2responsive_new.js")
),
# content of each main tab (selectable from sidebar)
tabItems(
tabItem("geospatial_viz",
div(class="outer",
# If not using custom CSS, set height of leafletOutput to a number instead of percent
leafletOutput("map", width="100%", height="100%"),
# Shiny versions prior to 0.11 should use class = "modal" instead.
absolutePanel(id = "controls", class = "panel panel-default", fixed = TRUE,
draggable = TRUE, top = 90, left = "auto", right = 20, bottom = "auto",
width = 1300, height = "auto",
br(),
# h2("Node Data"),
selectizeInput(inputId = "time_range", "Select time range", time_ranges, selected = time_ranges[1],width = "100%"),
#selectizeInput(inputId = "time_range_ds", "Select time range", time_ranges, selected = time_ranges[2],width = "100%"),
tabsetPanel(
tabPanel("Pollutants",
tabsetPanel(
tabPanel("Graphical",
plotOutput("graphical_data",height = "22vmin"),
plotOutput("graphical_data_last",height = "22vmin")
),
tabPanel("Tabular",
div(DT::dataTableOutput("table_data", height = "22vmin"),style = "font-size:80%"),
div(DT::dataTableOutput("table_data_last", height = "22vmin"),style = "font-size:80%")
)
),
checkboxGroupButtons(
inputId = "measures1",
choices = tab1_measures[1:4],
justified = TRUE, status = "primary", selected = tab1_measures[1:4],
checkIcon = list(yes = icon("ok-sign", lib = "glyphicon"), no = icon("remove-sign", lib = "glyphicon"))
),
checkboxGroupButtons(
inputId = "measures2",
choices = tab1_measures[5:8],
justified = TRUE, status = "primary", selected = tab1_measures[5:8],
checkIcon = list(yes = icon("ok-sign", lib = "glyphicon"), no = icon("remove-sign", lib = "glyphicon"))
)
),
tabPanel("Measures",
tabsetPanel(
tabPanel("Graphical",
plotOutput("graphical_data_ds",height = "22vmin"),
plotOutput("graphical_data_last_ds",height = "22vmin")
),
tabPanel("Tabular",
div(DT::dataTableOutput("table_data_ds", height = "22vmin"),style = "font-size:80%"),
div(DT::dataTableOutput("table_data_last_ds", height = "22vmin"),style = "font-size:80%")
)
),
checkboxGroupButtons(
inputId = "measures1_ds",
choices = tab2_measures[1:5],
justified = TRUE, status = "primary", selected = tab2_measures[1:5],
checkIcon = list(yes = icon("ok-sign", lib = "glyphicon"), no = icon("remove-sign", lib = "glyphicon"))
),
checkboxGroupButtons(
inputId = "measures2_ds",
choices = tab2_measures[6:10],
justified = TRUE, status = "primary", selected = tab2_measures[6:10],
checkIcon = list(yes = icon("ok-sign", lib = "glyphicon"), no = icon("remove-sign", lib = "glyphicon"))
)
)
)
# ,materialSwitch(inputId = "switch_compare", label = "Compare nodes data", status = "primary")
# div( id="yearly_inputs",
# selectizeInput(inputId = "D_month", "Select Month", H_months, selected = 'January',width = "100%"),
# selectizeInput(inputId = "D_day", "Select Day", H_days, selected = '1',width = "100%")
# )
),
absolutePanel(id = "nodes", class = "panel panel-default", fixed = TRUE,
draggable = TRUE, top = 60, left = "auto", right = 840, bottom = "auto",
width = 1000, height = "auto",
br(),
box(width=NULL,height=NULL,
div(DT::dataTableOutput("nodes_table", height = "22vmin"),style = "font-size:80%")
)
,
checkboxGroupButtons(
inputId = "measures1_sites",
choices = tracked_measures[1:5],
justified = TRUE, status = "primary", selected = tracked_measures[1:5],
checkIcon = list(yes = icon("ok-sign", lib = "glyphicon"), no = icon("remove-sign", lib = "glyphicon"))
),
checkboxGroupButtons(
inputId = "measures2_sites",
choices = tracked_measures[6:10],
justified = TRUE, status = "primary", selected = tracked_measures[6:10],
checkIcon = list(yes = icon("ok-sign", lib = "glyphicon"), no = icon("remove-sign", lib = "glyphicon"))
)
),
# absolutePanel(id = "counties_panel", class = "panel panel-default", fixed = TRUE,
# draggable = FALSE, top = "auto", left = "auto", right = 20, bottom = -40,
# width = 330, height = "auto",
# h2("Shown counties"),
# knobInput(
# inputId = "num_counties",
# label = "Select number of counties",
# value = 1000,
# min = 0,
# max = 1100,
# displayPrevious = TRUE,
# lineCap = "round",
# fgColor = "#428BCA",
# inputColor = "#428BCA"
# ),
# sliderInput(inputId = "Opacity",
# sep = "",
# label = "Confidence level control",
# step = 0.1,
# value = 0, min = 0, max = 1
# # ,width = "90%"
# )
# ),
tags$div(id="cite",
'Visual Analytics, University of Illinois at Chicago 2019'
)
)),
tabItem("tabular_viz",
h1("WIP")),
tabItem("about",
htmlOutput("about_out")
)
)
)
)
############################################# SERVER ##############################################
server <- function(input, output, session) {
########################## AoT R APIs modified ######################
#' Timestamped message -- primarily used to push error output to user
#'
#' @param msg - The message to be logged
#' @return None (invisible NULL) as per cat
#' @noRd
log_msg <- function (msg) {
cat(format(Sys.time(), "%Y-%m-%d %H:%M:%OS3 "), ": ", msg, "\n", sep="")
}
#' Sends a request to the API, ensures 200 response and returns the response
#'
#' Given a URL and optional filters/query params, this sends an HTTP GET request
#' to the URL. The response"s status is checked -- if it isn"t 200 then an
#' error message is logged and the process halts; it it"s 200 then the entire
#' response object is returned.
#'
#' @param url - The URL to send the request to
#' @param filters - A list of tuples to build filters/query params
#' @return The entire response
#' @importFrom httr GET
#' @noRd
send_request <- function (url, filters = NULL) {
# send request; get response
if (!is.null(filters)) {
resp <- httr::GET(url, query=filters)
} else {
resp <- httr::GET(url)
}
# if not 200, log error
if (resp$status_code != 200) {
msg <- paste("Error in httr GET:", resp$status_code, resp$headers$statusmessage, url)
if(!is.null(resp$headers$`content-length`) && (resp$headers$`content-length` > 0)) {
details <- httr::content(resp)
msg <- paste(msg, details)
}
log_msg(msg)
}
# stop or return
httr::stop_for_status(resp)
return(resp)
}
#' Parses a response object as JSON and returns the `data` object
#'
#' @param resp - The response object
#' @return The parsed JSON body
#' @importFrom jsonlite fromJSON
#' @noRd
parse_content <- function (resp) {
content <- httr::content(resp, as="text")
json <- jsonlite::fromJSON(content)
data <- json$data
return(data)
}
#' Sends a request and parses the result as a single map object
#'
#' Given a URL and optional filters, a request is sent and the response
#' is processed as a single map object -- the response content has a
#' `data` key that maps an object representing details for the metadata
#' record requested.
#'
#' @param url - The URL to send the request to
#' @param filters - A list of tuples to build query params
#' @return The metadata details
#' @noRd
stat <- function (url, filters) {
resp <- send_request(url, filters)
details <- parse_content(resp)
return(details)
}
#' Gets a data frame of `node` metadata
#'
#' Nodes are the physical devices deployed to collect observations.
#' The are comprised of multiple sensors and are grouped by
#' projects.
#'
#' @param filters - A list of tuples to create filters/query params
#' @return A data frame of node metadata
#' @export
ls.nodes <- function (filters = NULL) {
# build url, send request, get response
url <- "https://api.arrayofthings.org/api/nodes"
resp <- send_request(url, filters)
# build data frame
data <- parse_content(resp)
df <- as.data.frame.list(data)
attr(df, "vsn") <- data$vsn
attr(df, "location") <- data$location.geometry #location.geometry.coordinates
attr(df, "address") <- data$human_address
attr(df, "description") <- data$description
# return data frame
return(df)
}
#' Gets a data frame of `obserations` data.
#'
#' Observation data are the environmental measurements made
#' by the sensors. Data listed here is more or less tuned
#' and trustworthy.
#'
#' @param filters - A list of tuples to create filters/query params
#' @return A data frame of observation data
#' @export
ls.observations <- function (filters = NULL) {
# build url, send request, get response
url <- "https://api.arrayofthings.org/api/observations"
resp <- send_request(url, filters)
# build data frame
data <- parse_content(resp)
df <- as.data.frame.list(data)
attr(df, "node_vsn") <- data$node_vsn
attr(df, "sensor_path") <- data$sensor_path
attr(df, "timestamp") <- data$timestamp # TODO modified because creates problems when no observations if as.POS.. as.POSIXlt(data$timestamp)
attr(df, "value") <- data$value
attr(df, "uom") <- data$uom
attr(df, "location") <- data$location
# return data frame
return(df)
}
##################################################### AoT utils #####################################################
get_and_preprocess_nodes <- function(){
df <- ls.nodes()
# filter out nodes not yet deployed
df <- subset(df, address != "TBD")
df$location.type <- NULL
df$location.geometry$type <- NULL
df$coordinates <- df$location.geometry$coordinates
df$location.geometry$coordinates <-NULL
df$location.geometry <- NULL
df$description <- NULL
temp <- do.call(rbind, df$coordinates)
colnames(temp) <- c("longitude","latitude")
df <- cbind(df[c("vsn", "address")], temp)
}
#gets the observations relative to h hours ago
get_h_hours_observations <- function(h, vsn){
# d <- get_last_available_date()
timestamp <- ls.observations(filters=list(node=vsn,size=1))$timestamp
t1 <- sub_hour_to_timestamp(timestamp,h-1)
t2 <- sub_hour_to_timestamp(timestamp,h)
df <- ls.observations(filters=list(
node=vsn,
timestamp=paste("ge:",t2,sep=""),
timestamp=paste("lt:",t1,sep=""),
size=200
# timestamp="ge:2018-08-01T00:00:00",
# timestamp="lt:2018-09-01T00:00:00"
))
df <- data.frame(df)
df$location.type <- NULL
df$location.geometry <- NULL
return(df)
}
#gets the observations relative to h hours ago for all nodes
get_h_hours_observations_all_nodes <- function(h){
# d <- get_last_available_date()
timestamp <- ls.observations(filters=list(size=1))$timestamp
t1 <- sub_hour_to_timestamp(timestamp,h-1)
t2 <- sub_hour_to_timestamp(timestamp,h)
df <- ls.observations(filters=list(
timestamp=paste("ge:",t2,sep=""),
timestamp=paste("lt:",t1,sep=""),
size=600
# timestamp="ge:2018-08-01T00:00:00",
# timestamp="lt:2018-09-01T00:00:00"
))
df <- data.frame(df)
df$location.type <- NULL
df$location.geometry <- NULL
return(df)
}
#gets the observations relative to h hours ago
get_d_days_observations <- function(d, vsn){
# d <- get_last_available_date()
timestamp <- ls.observations(filters=list(node=vsn,size=1))$timestamp
t1 <- sub_day_to_timestamp(timestamp,d-1)
t2 <- sub_day_to_timestamp(timestamp,d)
df <- ls.observations(filters=list(
node=vsn,
timestamp=paste("ge:",t2,sep=""),
timestamp=paste("lt:",t1,sep=""),
size=200
# timestamp="ge:2018-08-01T00:00:00",
# timestamp="lt:2018-09-01T00:00:00"
))
df <- data.frame(df)
df$location.type <- NULL
df$location.geometry <- NULL
return(df)
}
#gets all the observation in the past 24 h, limited to 50k (max api limit should be 100k)
get_last_24h_data <- function(vsn){
# d <- get_last_available_date()
timestamp <- ls.observations(filters=list(node=vsn,size=1))$timestamp
t1 <- sub_day_to_timestamp(timestamp,1)
t2 <- sub_day_to_timestamp(timestamp,0)
df <- ls.observations(filters=list(
node=vsn,
timestamp=paste("ge:",t1,sep=""),
timestamp=paste("lt:",t2,sep=""),
size=50000
# timestamp="ge:2018-08-01T00:00:00",
# timestamp="lt:2018-09-01T00:00:00"
))
df <- data.frame(df)
df$location.type <- NULL
df$location.geometry <- NULL
return(df)
}
# function to get data for all the nodes for a day
get_d_days_observations_all_nodes <- function(d){
# d <- get_last_available_date()
timestamp <- ls.observations(filters=list(size=1))$timestamp
# print(timestamp)
t1 <- ymd_hms(timestamp)-lubridate::days(d-1)
t1 <- force_tz(t1, "America/Chicago")
t2 <- ymd_hms(timestamp)-lubridate::days(d)
t2 <- force_tz(t2, "America/Chicago")
# print(t1)
# print(t2)
df <- ls.observations(filters=list(
timestamp=paste("ge:",t2,sep=""),
timestamp=paste("lt:",t1,sep=""),
size=600
))
df <- data.frame(df)
df$location.type <- NULL
df$location.geometry <- NULL
return(df)
}
# function to get data for all the nodes for seven days
get_and_preprocess_observations_7d_all_nodes <- function(){
days <- c(1:7)
dfs <- lapply(days, get_d_days_observations_all_nodes)
df1 <- do.call(rbind, dfs)
df <- data.frame(df1$node_vsn)
names(df) <- c("vsn")
df$measure <- df1$sensor_path
df$time <- df1$timestamp
df$value <- df1$value
df$measure <-lapply(df$measure,extract_sensor)
df$uom <- df1$uom
df$measure <- unlist(df$measure)
df$time <- lapply(df$time,convert_timestamp_to_chicago_timezone)
df <- extract_date_fields_d(df)
df <-aggregate(df$value, by=list(df$vsn,df$measure,df$uom, df$year, df$month, df$day, df$hms),
FUN=mean)
names(df) <- c("vsn","measure","uom","year","month","day","hms", "value")
return(df)
}
get_and_preprocess_observations_7d <- function(vsn){
days <- c(1:7)
dfs <- lapply(days, get_d_days_observations, vsn)
df1 <- do.call(rbind, dfs)
df <- data.frame(df1$node_vsn)
names(df) <- c("vsn")
df$measure <- df1$sensor_path
df$time <- df1$timestamp
df$value <- df1$value
df$measure <-lapply(df$measure,extract_sensor)
df$uom <- df1$uom
df <- filter_out_untracked_measures(df)
df$measure <- unlist(df$measure)
df$time <- lapply(df$time,convert_timestamp_to_chicago_timezone)
df <- extract_date_fields_d(df)
df <-aggregate(df$value, by=list(df$vsn,df$measure,df$uom, df$year, df$month, df$day, df$hms),
FUN=mean)
names(df) <- c("vsn","measure","uom","year","month","day","hms", "value")
return(df)
}
get_and_preprocess_observations_24h <- function(vsn){
# Every 5210 observations it's 1 hour
# OLD METHOD, 24 requests
hours <- c(1:24)
dfs <- lapply(hours, get_h_hours_observations, vsn)
df1 <- do.call(rbind, dfs)
df <- data.frame(df1$node_vsn)
# All the observations in 1 request strategy
# df1 <- get_last_24h_data(vsn)
# df <- data.frame(df1$node_vsn)
names(df) <- c("vsn")
df$measure <- df1$sensor_path
df$time <- df1$timestamp
df$value <- df1$value
df$measure <-lapply(df$measure,extract_sensor)
df$uom <- df1$uom
df <- filter_out_untracked_measures(df)
df$measure <- unlist(df$measure)
df$time <- lapply(df$time,convert_timestamp_to_chicago_timezone)
df <- extract_date_fields_h(df)
df <-aggregate(df$value, by=list(df$vsn,df$measure,df$uom, df$h, df$year, df$month, df$day, df$hms),
FUN=mean)
names(df) <- c("vsn","measure","uom","h","year","month","day", "hms", "value")
return(df)
}
# get data for all nodes for last 24 horus
get_and_preprocess_observations_24h_all_nodes <- function(){
# Every 5210 observations it's 1 hour
# OLD METHOD, 24 requests
hours <- c(1:24)
dfs <- lapply(hours, get_h_hours_observations_all_nodes)
df1 <- do.call(rbind, dfs)
df <- data.frame(df1$node_vsn)
# All the observations in 1 request strategy
# df1 <- get_last_24h_data(vsn)
# df <- data.frame(df1$node_vsn)
names(df) <- c("vsn")
df$measure <- df1$sensor_path
df$time <- df1$timestamp
df$value <- df1$value
df$measure <-lapply(df$measure,extract_sensor)
df$uom <- df1$uom
df <- filter_out_untracked_measures(df)
df$measure <- unlist(df$measure)
df$time <- lapply(df$time,convert_timestamp_to_chicago_timezone)
df <- extract_date_fields_h(df)
df <-aggregate(df$value, by=list(df$vsn,df$measure,df$uom, df$h, df$year, df$month, df$day, df$hms),
FUN=mean)
names(df) <- c("vsn","measure","uom","h","year","month","day", "hms", "value")
return(df)
}
get_and_preprocess_observations <- function(vsn){
df1 <- ls.observations(filters=list(node=vsn))
# filter out nodes not yet deployed
df <- data.frame(df1$node_vsn)
if(nrow(df)>0){
names(df) <- c("vsn")
df$measure <- df1$sensor_path
df$time <- df1$timestamp
df$value <- df1$value
df$measure <-lapply(df$measure,extract_sensor)
df$uom <- df1$uom
df <- filter_out_untracked_measures(df)
df$measure <- unlist(df$measure)
df <-aggregate(df$value, by=list(df$vsn,df$measure,df$time,df$uom),
FUN=mean)
names(df) <- c("vsn","measure","time","uom","value")
df$time <- lapply(df$time,convert_timestamp_to_chicago_timezone)
df <- extract_date_fields(df)
}
return(df)
}
# get current data for all the AOT nodes
get_and_preprocess_observations_all_nodes <- function(){
df1 <- ls.observations(filters=list())
# filter out nodes not yet deployed
df <- data.frame(df1$node_vsn)
if(nrow(df)>0){
names(df) <- c("vsn")
df$measure <- df1$sensor_path
df$time <- df1$timestamp
df$value <- df1$value
df$measure <-lapply(df$measure,extract_sensor)
df$uom <- df1$uom
df <- filter_out_untracked_measures(df)
df$measure <- unlist(df$measure)
df <-aggregate(df$value, by=list(df$vsn,df$measure,df$time,df$uom),
FUN=mean)
names(df) <- c("vsn","measure","time","uom","value")
df$time <- lapply(df$time,convert_timestamp_to_chicago_timezone)
df <- extract_date_fields(df)
}
return(df)
}
# get all nodes data for open AQ last 7 days
ls.observations_openaq_7d_all_nodes <- function (time) {
# build url, send request, get response
data <- aq_measurements(city = "Chicago-Naperville-Joliet",date_from = as.character(Sys.Date()-7), date_to = as.character(Sys.Date()))
df <- as.data.frame.list(data)
attr(df, "value") <- data$value
attr(df, "location") <- data$location
# return data frame
return(df)
}
# get all nodes data for open AQ last 7 days
get_and_preprocess_observations_7d_all_nodes_openaq <- function(){
df1 <- ls.observations_openaq_7d_all_nodes("curr")
df <- data.frame(df1$location)
names(df) <- c("vsn")
df$measure <- df1$parameter
levels(df$measure)[levels(df$measure)=="pm25"] <- "pm2.5"
df$time <- df1$dateLocal
df$value <- df1$value
df$uom <- df1$unit
df$longitude <- df1$longitude
df$latitude <- df1$latitude
df$year <- format(df$time, format = "%Y")
df$month <- format(df$time, format = "%m")
df$day <- format(df$time, format = "%d")
df$hms <- paste(df$month, "/", df$day,"/",substr(df$year,3,4), sep="")
df <-aggregate(df$value, by=list(df$vsn,df$measure,df$uom, df$year, df$month, df$day, df$hms,df$longitude,df$latitude),
FUN=mean)
names(df) <- c("vsn","measure","uom","year","month","day","hms", "longitude","latitude","value")
return(df)
}
# get data for all nodes for open aq last 24 hours
ls.observations_openaq_24h_all_nodes <- function (time) {
# build url, send request, get response
# build data frame
data <- aq_measurements(city = "Chicago-Naperville-Joliet",date_from = as.character(Sys.Date()), date_to = as.character(Sys.Date()+1))
df <- as.data.frame.list(data)
attr(df, "timestamp") <- data$dateLocal # TODO modified because creates problems when no observations if as.POS.. as.POSIXlt(data$timestamp)
attr(df, "value") <- data$value
attr(df, "location") <- data$location
# return data frame
return(df)
}
get_and_preprocess_observations_24h_openaq_all_nodes <- function(){
df1 <- ls.observations_openaq_24h_all_nodes("curr")
df <- data.frame(df1$location)
names(df) <- c("vsn")
df$measure <- df1$parameter
levels(df$measure)[levels(df$measure)=="pm25"] <- "pm2.5"
df$time <- df1$dateLocal
df$value <- df1$value
df$longitude <- df1$longitude
df$latitude <- df1$latitude
df$uom <- df1$unit
df$year <- format(df$time, format = "%Y")
df$month <- format(df$time, format = "%m")
df$day <- format(df$time, format = "%d")
df$h <- format(df$time, format = "%H")
df$hms <- paste("d:",df$day, "h:", df$h)
df <-aggregate(df$value, by=list(df$vsn,df$measure,df$uom, df$year, df$month, df$day, df$hms,df$longitude,df$latitude),
FUN=mean)
names(df) <- c("vsn","measure","uom","year","month","day","hms","longitude","latitude","value")
return(df)
}
#get all nodes data for openAQ for current time
ls.observations_openaq_all_nodes <- function (time) {
# build url, send request, get response
# build data frame
#TODO A: Retrieving latest stats here as some locations do not have updates in the past hour
#data <- aq_measurements(city = "Chicago-Naperville-Joliet",location=vsn,date_from = as.character(Sys.Date()-7), date_to = as.character(Sys.Date()))
data <- aq_latest(country = "US", city = "Chicago-Naperville-Joliet")
df <- as.data.frame.list(data)
attr(df, "value") <- data$value
attr(df, "location") <- data$location
# return data frame
return(df)
}
get_and_preprocess_observations_openaq_all_nodes <- function(){
df1 <- ls.observations_openaq_all_nodes("curr")
df <- data.frame(df1$location)
names(df) <- c("vsn")
df$measure <- df1$parameter
levels(df$measure)[levels(df$measure)=="pm25"] <- "pm2.5"
df$time <- df1$lastUpdated
df$value <- df1$value
df$longitude <- df1$longitude
df$latitude <- df1$latitude
df$uom <- df1$unit
df$year <- format(df$time, format = "%Y")
df$month <- format(df$time, format = "%m")
df$day <- format(df$time, format = "%d")
df$hms <- paste(df$month, "/", df$day,"/",substr(df$year,3,4), sep="")
df <-aggregate(df$value, by=list(df$vsn,df$measure,df$uom, df$year, df$month, df$day, df$hms,df$longitude,df$latitude),
FUN=mean)
names(df) <- c("vsn","measure","uom","year","month","day","hms","longitude","latitude","value")
#print(df)
return(df)
}
sub_hour_to_timestamp <- function(timestamp, h){
pb.txt <- strptime(timestamp,"%Y-%m-%dT%H:%M:%S", tz="GMT")
pb.date <- as.POSIXct(pb.txt, tz="Europe/London")
t <- pb.date - 60*60*h+180
return(paste(strsplit(as.character(t)," ", fixed = TRUE, perl = FALSE, useBytes = FALSE)[[1]][1],
"T",
strsplit(as.character(t)," ", fixed = TRUE, perl = FALSE, useBytes = FALSE)[[1]][2],sep=""))
}
sub_day_to_timestamp <- function(timestamp, d){
pb.txt <- strptime(timestamp,"%Y-%m-%dT%H:%M:%S", tz="GMT")