Skip to content

Commit 7919835

Browse files
committedSep 29, 2015
update for presentation
1 parent 1ed7dd2 commit 7919835

File tree

23 files changed

+2198
-177
lines changed

23 files changed

+2198
-177
lines changed
 
Binary file not shown.

‎_data/freeway/speedValidation/speedValidation2.csv

+1,866
Large diffs are not rendered by default.
Loading
Loading
Loading
Loading

‎_scripts/dataOutages/dataOutage.R

+55-9
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Meta --------------------------------------------------------------------
22
# @file missingDataFinder.R
3-
# @description This script finds missing data within the PORTAL database.
3+
# @description This script finds missing data within the PORTAL database.
44
# @author Bryan Blanc <bryanpblanc@gmail.com>
55

66
# Initialization ----------------------------------------------------------
@@ -36,6 +36,7 @@ source("_functions/aggregation.R")
3636
missingData = function(station_id,detectors,startTime,endTime,percentile){
3737
dets = detectors$detectorid[detectors$stationid %in% station_id]
3838
lanes = sort(unique(detectors$lanenumber[detectors$detectorid %in% dets]))
39+
lanes = lanes[lanes!=0]
3940
laneList = list()
4041
if(length(dets)>0){
4142
query = freewayQuery(dets,startTime,endTime)
@@ -125,15 +126,15 @@ colnames(mapFrame)=c("station_id","long","lat","htmlLink","numOutages")
125126
for(i in 1:length(stationList)){
126127
sid = as.numeric(names(stationList[i]))
127128
mapFrame$station_id[i]=sid
128-
129+
129130
if(sid <5000){
130131
mapFrame$lat[i] = staLocs$Y[staLocs$stationid==sid]
131132
mapFrame$long[i] = staLocs$X[staLocs$stationid==sid]
132133
}else{
133134
mapFrame$lat[i] = staLocs$Y[staLocs$stationid==sid-4000]
134135
mapFrame$long[i] = staLocs$X[staLocs$stationid==sid-4000]
135136
}
136-
137+
137138
sta = stationList[[i]]
138139
numLanes = length(unique(detectors$lanenumber[detectors$stationid==sid]))
139140
if(numLanes >0){
@@ -154,9 +155,9 @@ for(i in 1:length(stationList)){
154155
melted$day = as.Date(melted$day)
155156
flagged = subset(melted,melted$value!=0)
156157
mapFrame$numOutages[i]=nrow(flagged)
157-
158-
159-
158+
159+
160+
160161
portalLink=paste0("http://portal.its.pdx.edu/Portal/index.php/stations/view/id/",sid,"/")
161162
if(sid>=5000){
162163
mapFrame$htmlLink[i] = paste0("<div align='center'><b>Ramp<b><br><br/><a href='",portalLink,"' target=_blank>",stations$locationtext[stations$stationid==sid][1],"</a></div>")
@@ -175,9 +176,9 @@ pal <- colorNumeric(
175176
domain = c(0,100)
176177
)
177178

178-
map= leaflet(mapFrame) %>% addProviderTiles("CartoDB.DarkMatter",options = providerTileOptions(noWrap = TRUE)) %>%
179+
map= leaflet(mapFrame) %>% addProviderTiles("CartoDB.DarkMatter",options = providerTileOptions(noWrap = TRUE)) %>%
179180
setView(-122.6662589, 45.5317385, zoom = 10) %>% addCircleMarkers(lng=~long,lat=~lat,popup =~htmlLink,color =~pal(numOutages))
180-
181+
181182

182183

183184
# Plotting ----------------------------------------------------------------
@@ -209,7 +210,7 @@ for(i in 1:length(stationList)){
209210
flagged$id = rownames(flagged)
210211
plotList[[as.character(sid)]]=flagged
211212
}
212-
213+
213214
#ggplot(flagged,aes(x = day, y = variable, group = value, colour=value))+geom_point()+scale_x_date()+scale_color_discrete(labels=flagKey$def)
214215
#flagged %>% ggvis(x=~day, y=~ variable, stroke =~value, fill =~value, key:=~id) %>% layer_points(opacity := 0.5) %>% add_tooltip(tFunk)
215216
}
@@ -219,3 +220,48 @@ for(i in 1:length(stationList)){
219220
saveRDS(plotList,"_data/freeway/dataOutages/plotList.rds")
220221

221222

223+
# Table -------------------------------------------------------------------
224+
flagKey = data.frame(matrix(nrow=4,ncol=2))
225+
colnames(flagKey)=c("value","def")
226+
flagKey$value=1:4
227+
flagKey$def = c("Very Low Values","Only Empty Data", "Zero Rows of Data", "Detector Unavailable")
228+
stationList = readRDS("_data/freeway/dataOutages/stationList.rds")
229+
230+
tabFrame = data.frame(matrix(nrow=length(stationList),ncol=6))
231+
colnames(tabFrame)=c("sid","location","flag1","flag2","flag3","numOutages")
232+
#colnames(tabFrame)=c("station_id",c("# Days w/ Very Low Values","# Days w/ Only Empty Data", "# Days w/ Zero Rows of Data"),"# Days w/ Outages (Total)")
233+
234+
for(i in 1:length(stationList)){
235+
sid = as.numeric(names(stationList[i]))
236+
tabFrame$sid[i]=sid
237+
tabFrame$location[i] = stations$locationtext[stations$stationid==sid][1]
238+
sta = stationList[[i]]
239+
numLanes = length(unique(detectors$lanenumber[detectors$stationid==sid]))
240+
if (numLanes>0){
241+
flag1 = 0
242+
flag2 = 0
243+
flag3 = 0
244+
for (j in 1:length(sta)){
245+
flags = unlist(sta[[j]])
246+
for (k in 1:length(flags)){
247+
if(flags[k]==1){
248+
flag1 = flag1 +1
249+
}else if(flags[k]==2){
250+
flag2 = flag2 +1
251+
}else if(flags[k]==3){
252+
flag3 = flag3 +1
253+
}
254+
}
255+
}
256+
tabFrame$flag1[i]=flag1
257+
tabFrame$flag2[i]=flag2
258+
tabFrame$flag3[i]=flag3
259+
tabFrame$numOutages[i]=flag1+flag2+flag3
260+
}
261+
}
262+
263+
tabFrame = tabFrame[complete.cases(tabFrame),]
264+
265+
saveRDS(tabFrame,"_data/freeway/dataOutages/tabFrame.rds")
266+
267+

‎_scripts/outlierExploration/dataPull.R

+1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ require(plyr)
55
require(ggplot2)
66
require(lubridate)
77
require(rjson)
8+
require(portalr)
89

910
setwd("/Users/bblanc/OneDrive/_ODOT/_Portal/investigations")
1011

‎_scripts/outlierExploration/histPlotter.R

+35-34
Original file line numberDiff line numberDiff line change
@@ -4,59 +4,60 @@ library(timeSeries)
44
library(plyr)
55
library(ggplot2)
66
library(lubridate)
7+
library(rjson)
8+
library(rgdal)
9+
require(portalr)
710

8-
setwd("/Users/bblanc/OneDrive/_ODOT/_Portal/investigations/histBuilder/")
11+
setwd("/Users/bblanc/OneDrive/_ODOT/_Portal/investigations/")
912

1013
####Connect to Portal db
1114
####Make sure you VPN into cecs network
12-
db_cred = fromJSON(file="/Users/bblanc/OneDrive/_ODOT/_Portal/investigations/db_credentials.json")
15+
db_cred = fromJSON(file="db_credentials.json")
1316
con <- dbConnect(dbDriver("PostgreSQL"), host=db_cred$db_credentials$db_host, port= 5432, user=db_cred$db_credentials$db_user, password = db_cred$db_credentials$db_pass, dbname=db_cred$db_credentials$db_name)
1417

15-
1618
####Relational Tables
1719
stations= dbGetQuery(con,"SELECT * FROM public.stations")
1820
highways = dbGetQuery(con,"SELECT * FROM public.highways")
1921
detectors = dbGetQuery(con,"SELECT * FROM public.detectors")
2022
corridors = dbGetQuery(con,"SELECT * FROM public.corridors")
2123
corridor_stations = dbGetQuery(con,"SELECT * FROM public.corridorstations")
24+
#
25+
# ##Load standard PORTAL functions
26+
# source("/Users/bblanc/OneDrive/_ODOT/_Portal/investigations/_codeResources/portalFxns.R")
2227

23-
##Load standard PORTAL functions
24-
source("/Users/bblanc/OneDrive/_ODOT/_Portal/investigations/_codeResources/portalFxns.R")
28+
oregonStationGeom = readOGR("_data/GIS/","oregonStations")
29+
orStationData = oregonStationGeom@data
30+
currentStations = subset(orStationData,is.na(orStationData$end_date))
31+
stationVec = sort(unique(currentStations$stationid))
2532

26-
juneRaw = readRDS("juneData.rds")
33+
juneRaw = readRDS("_data/freeway/juneData.rds")
2734

2835
juneAgg= list()
2936
for (i in 1:length(juneRaw)){
3037
sid = juneRaw[[i]]$station_id
31-
sData = juneRaw[[i]]$data
32-
if(nrow(sData)>0){
33-
#clean = filter(sData)
34-
#if(nrow(clean)>0){
35-
clean = join(sData,detectors,by="detectorid")
36-
clean$period = cut(clean$starttime,breaks="1 hour")
37-
agg = ddply(clean,c("lanenumber","period"),function(X) data.frame(volume=sum(X$volume), occupancy = mean(X$occupancy), speed = weighted.mean(X$speed,X$volume)))
38-
agg$period=as.POSIXct(agg$period)
39-
agg$dow = weekdays(agg$period,abbreviate=TRUE)
40-
agg$hour = hour(agg$period)
41-
agg_hd = ddply(agg,c("lanenumber","hour","dow"),function(X) data.frame(volume=mean(X$volume), occupancy = mean(X$occupancy), speed = mean(X$speed)))
42-
station = list()
43-
station[["station_id"]]=sid
44-
station[["data"]]=agg_hd
45-
juneAgg[[i]]=station
46-
#}else{
47-
# station = list()
48-
# station[["station_id"]]=sid
49-
# station[["data"]]=NA
50-
# juneAgg[[i]] = station
51-
#}
52-
53-
}else{
54-
station = list()
55-
station[["station_id"]]=sid
56-
station[["data"]]=NA
57-
juneAgg[[i]] = station
38+
if(sid %in% stationVec){
39+
sData = juneRaw[[i]]$data
40+
if(nrow(sData)>0){
41+
clean = portalr::filterFreeway(sData)
42+
if(nrow(clean)>0){
43+
clean = join(sData,detectors,by="detectorid")
44+
clean$period = cut(clean$starttime,breaks="1 hour")
45+
agg = ddply(clean,c("lanenumber","period"),function(X) data.frame(volume=sum(X$volume), occupancy = mean(X$occupancy), speed = weighted.mean(X$speed,X$volume)))
46+
agg$period=as.POSIXct(agg$period)
47+
agg$dow = weekdays(agg$period,abbreviate=TRUE)
48+
agg$hour = hour(agg$period)
49+
agg_hd = ddply(agg,c("lanenumber","hour","dow"),function(X) data.frame(volume=mean(X$volume), occupancy = mean(X$occupancy), speed = mean(X$speed)))
50+
juneAgg[[as.character(sid)]] = agg_hd
51+
}else{
52+
juneAgg[[as.character(sid)]] = NA
53+
}
54+
55+
}else{
56+
juneAgg[[as.character(sid)]] = NA
57+
}
5858
}
5959
print (i)
6060
}
6161

62-
saveRDS(juneAgg,"juneAggData.rds")
62+
saveRDS(juneAgg,"_data/freeway/juneAggData_clean.rds")
63+
saveRDS(currentStations, "_data/freeway/stationMeta.rds")

‎_scripts/specificIssues/portal_issues.R

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
big# Initialization ----------------------------------------------------------
1+
# Initialization ----------------------------------------------------------
22

33
#Load neccesary libraries
44
require(RPostgreSQL)
@@ -90,9 +90,9 @@ dev.off()
9090

9191
# Issue 6: I-205 SB @ OR-224/82nd: Missing Data -----------------------------------------------------------------
9292
stas = 1099
93-
subStations = subset(stations,stations$stationid %in% stas)
9493
dets = detectors$detectorid[detectors$stationid %in% stas ]
9594
subDetectors = subset(detectors,detectors$detectorid %in% dets)
95+
head(subDetectors)
9696
startDate = "2015-05-01"
9797
endDate = "2015-05-31"
9898
raw = dbGetQuery(con,freewayQuery(dets,startDate,endDate))

‎_scripts/speedValidation/speedValid.R

+60-21
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
require(portalr)
12
require(RPostgreSQL)
23
require(DBI)
34
require(timeSeries)
@@ -6,6 +7,7 @@ require(ggplot2)
67
require(lubridate)
78
require(reshape2)
89
require(rjson)
10+
require(portalr)
911

1012
setwd("/Users/bblanc/OneDrive/_ODOT/_Portal/investigations/")
1113

@@ -16,14 +18,9 @@ con <- dbConnect(dbDriver("PostgreSQL"), host=db_cred$db_credentials$db_host, po
1618

1719
####Relational Tables
1820
stations= dbGetQuery(con,"SELECT * FROM public.stations")
19-
highways = dbGetQuery(con,"SELECT * FROM public.highways")
2021
detectors = dbGetQuery(con,"SELECT * FROM public.detectors")
21-
corridors = dbGetQuery(con,"SELECT * FROM public.corridors")
22-
corridor_stations = dbGetQuery(con,"SELECT * FROM public.corridorstations")
23-
24-
###Load Querying Functions
25-
source("_functions/portalFxns.R")
2622

23+
#First round
2724
speeds = read.csv("_data/freeway/speedValidation/speedValidation.csv",stringsAsFactors = FALSE)
2825
speeds = speeds[,1:3]
2926
speeds$time = paste0("2015/08/19 ",speeds$Timestamp)
@@ -77,6 +74,43 @@ speedList[[8]]$crossStreet ="33rd Ave"
7774
speedList[[8]]$lane=1
7875
speedList[[8]]$sid = 1062
7976

77+
#Second Round
78+
speeds = read.csv("_data/freeway/speedValidation/speedValidation2.csv",stringsAsFactors = FALSE)
79+
speeds = speeds[,1:3]
80+
speeds$time = paste0("2015/09/03 ",speeds$Timestamp)
81+
speeds$time = as.POSIXct(strptime(speeds$time,format = "%Y/%m/%d %H:%M:%S"))
82+
83+
locs = unique(speeds$Location)
84+
locs = locs[locs != ""]
85+
86+
indices = which(speeds$Location %in% locs)
87+
indices[5]=nrow(speeds)
88+
89+
for (i in 1:(length(locs))){
90+
subList = list()
91+
subList[["location"]]=locs[i]
92+
sub = speeds[(indices[i]:(indices[i+1]-1)),c(2,4)]
93+
subList[["observed"]]=sub[complete.cases(sub),]
94+
speedList[[i+8]]=subList
95+
}
96+
97+
speedList[[9]]$highway="US-26 WB"
98+
speedList[[9]]$crossStreet ="185th Ave."
99+
speedList[[9]]$lane=1
100+
speedList[[9]]$sid = 1129
101+
speedList[[10]]$highway="US-26 WB"
102+
speedList[[10]]$crossStreet ="185th Ave."
103+
speedList[[10]]$lane=2
104+
speedList[[10]]$sid = 1129
105+
speedList[[11]]$highway="I-205 SB"
106+
speedList[[11]]$crossStreet ="Clackamas Hwy"
107+
speedList[[11]]$lane=1
108+
speedList[[11]]$sid = 1100
109+
speedList[[12]]$highway="I-205 SB"
110+
speedList[[12]]$crossStreet ="Clackamas Hwy"
111+
speedList[[12]]$lane=3
112+
speedList[[12]]$sid = 1100
113+
80114
saveRDS(speedList,"_data/freeway/speedValidation/speedList.rds")
81115
speedList=readRDS("_data/freeway/speedValidation/speedList.rds")
82116

@@ -94,32 +128,37 @@ for(i in 1:length(speedList)){
94128
start = as.character(round(start,"mins"))
95129
end = max(obs$time)
96130
end = as.character(round(end,"mins"))
97-
98-
request = dbGetQuery(con,freewayQuery_time(did,start,end))
131+
132+
request = freewayData(con,did,start,end)
99133
speedList[[i]]$portal = request
100-
134+
101135
histStart = as.POSIXct(start)
102136
week(histStart)<-week(histStart)-9
103137
histStart = as.character(histStart)
104138
histStartSeq = as.character(timeSequence(from = histStart, to = start, by = "week"))
105-
139+
106140
histEnd = as.POSIXct(end)
107141
week(histEnd)<-week(histEnd)-9
108142
histEnd = as.character(histEnd)
109143
histEndSeq = as.character(timeSequence(from = histEnd, to = end, by = "week"))
110-
144+
111145
query = paste0("SELECT * FROM freeway.data WHERE ((starttime >='",histStartSeq[1],"' AND starttime <='",histEndSeq[1],"')")
112146
for (j in 2:length(histStartSeq)){
113147
query = paste0(query," OR (starttime >='",histStartSeq[j],"' AND starttime <='",histEndSeq[j],"')")
114148
}
115149
query = paste0(query,") AND detectorid = ",did)
116-
150+
117151
request = dbGetQuery(con,query)
118152
request$time = paste0(hour(request$starttime),":",minute(request$starttime),":",second(request$starttime))
119-
153+
120154
agg = ddply(request,c("time"),summarise,speed=mean(speed,na.rm=TRUE))
121-
agg$time = as.POSIXct(strptime(paste0("2015-08-19 ",agg$time),format= "%Y-%m-%d %H:%M:%S"))
155+
if(i %in% 1:8){
156+
agg$time = as.POSIXct(strptime(paste0("2015-08-19 ",agg$time),format= "%Y-%m-%d %H:%M:%S"))
157+
}else{
158+
agg$time = as.POSIXct(strptime(paste0("2015-09-03 ",agg$time),format= "%Y-%m-%d %H:%M:%S"))
159+
}
122160

161+
123162
speedList[[i]]$hist = agg
124163
}
125164

@@ -129,28 +168,28 @@ for (i in 1:length(speedList)){
129168
obs = speedList[[i]]$observed
130169
obs$period = cut(obs$time,"1 min")
131170
obsAgg = ddply(obs,c("period"),summarise,speed = mean(Reading))
132-
171+
133172
portal = speedList[[i]]$portal
134173
portal$period = cut(portal$starttime,"1 min")
135174
portalAgg = ddply(portal,c("period"),summarise,speed = mean(speed))
136-
175+
137176
hist = speedList[[i]]$hist
138177
hist$period = cut(hist$time,"1 min")
139178
histAgg = ddply(hist,c("period"),summarise,speed = mean(speed))
140-
179+
141180
joined = join(obsAgg,portalAgg,by="period")
142181
joined = join(joined,histAgg, by ="period")
143182
colnames(joined)=c("time","observed","portal","hist")
144183
melted = melt(joined,id="time")
145184
melted$time=as.POSIXct(melted$time)
146-
185+
147186
speedList[[i]]$melted = melted
148-
149-
187+
188+
150189
plot=ggplot(melted,aes(x=time,y=value,group=variable,colour=variable))+geom_smooth()+scale_x_datetime()+
151190
ggtitle(paste0(speedList[[i]]$highway," @ ",speedList[[i]]$crossStreet,", Lane",speedList[[i]]$lane))+
152191
ylab("Speed (mph)")+xlab("")
153-
192+
154193
png(paste0("_results/img/speedValidation/",speedList[[i]]$location,".png"),width=900,height=600)
155194
print(plot)
156195
dev.off()

‎_shiny/bluetooth_tt/blue.R

+44-16
Original file line numberDiff line numberDiff line change
@@ -24,25 +24,25 @@ shinyApp(
2424
)
2525
)
2626
),
27-
27+
2828
server = function(input,output,session){
29-
29+
3030
hplot = reactive({
3131
hourSelect = input$hour
3232
binSelect = input$bin
33-
33+
3434
sub = subset(blue,blue$hour==hourSelect)
35-
35+
3636
percentBins = quantile(sub$tt_min,probs = seq(0,1.0,0.05))
3737
binNums = data.frame(matrix(nrow=length(percentBins),ncol=2))
3838
colnames(binNums)=c("name","num")
3939
binNums$name[1:20]= paste0(names(percentBins)[1:20],"-",names(percentBins)[2:21])
4040
binNums$name[21]= "100%"
4141
binNums$num=as.numeric(rownames(binNums))
42-
42+
4343
for (i in 1:nrow(sub)){
4444
obs = sub$tt_min[i]
45-
45+
4646
if(obs==max(percentBins[length(percentBins)])){
4747
binNames = "95%-100%"
4848
}else if(obs ==min(percentBins[1])){
@@ -53,31 +53,31 @@ shinyApp(
5353
upper = names(percentBins[percentBins == min(percentBins[obs <percentBins])])
5454
binNames = paste0(lower,"-",upper)
5555
}
56-
56+
5757
sub$pBin[i]= binNames
5858
sub$pBinNum[i] = binNums$num[binNums$name == binNames]
5959
}
60-
60+
6161
sub$pBin=factor(sub$pBin)
62-
62+
6363
tFunk = function(df){
6464
paste0("Percentile: ",binNums$name[df$pBinNum])
6565
}
66-
66+
6767
colRamp = colorRampPalette(colors=c("white","red"))
68-
68+
6969
h <- sub %>% ggvis(x = ~tt_min, fill=~pBinNum) %>%
7070
scale_numeric("fill",label="Percentile Bin", domain=c(1,20),range =colRamp(20)[c(1,20)])%>% group_by(pBinNum) %>%
7171
layer_histograms(width=binSelect) %>%
7272
add_axis("x", title = "Travel Time (minutes)")%>%
7373
add_axis("y", title = "Frequency") %>% add_tooltip(tFunk)
74-
74+
7575
return(h)
76-
76+
7777
})
78-
78+
7979
hplot %>% bind_shiny("ggvis", "ggvis_ui")
80-
80+
8181
}
8282
)
8383

@@ -98,7 +98,35 @@ tt_filter= function(data,dist){
9898
minFilter = floor((dist/(35+15))*3600)
9999
upper = mean(data$traveltime)+1.65*sd(data$traveltime)
100100
data = subset(data,data$traveltime >=minFilter & data$traveltime <=maxFilter & data$traveltime <= upper)
101-
101+
102102
}
103103

104+
require(dplyr)
105+
setwd("~/_ODOT_Portal/investigations")
106+
####Connect to Portal db
107+
####Make sure you VPN into cecs network
108+
db_cred = fromJSON(file="/Users/bblanc/OneDrive/_ODOT/_Portal/investigations/db_credentials.json")
109+
con <- dbConnect(dbDriver("PostgreSQL"), host=db_cred$db_credentials$db_host, port= 5432, user=db_cred$db_credentials$db_user, password = db_cred$db_credentials$db_pass, dbname=db_cred$db_credentials$db_name)
110+
111+
db = src_postgres(dbname = db_cred$db_credentials$db_name,
112+
host = db_cred$db_credentials$db_host,
113+
port = 5432,
114+
user = db_cred$db_credentials$db_user,
115+
password = db_cred$db_credentials$db_pass,
116+
options = "-c search_path=odot")
117+
118+
tbls = src_tbls(db)
119+
120+
ttseg_tbls = tbls[grep("ttseginventory",tbls)]
121+
ttseg_tblRef = data.frame(matrix(nrow=length(ttseg_tbls),ncol=2))
122+
colnames(ttseg_tblRef)=c("tbl_name","date")
123+
ttseg_tblRef$tbl_name=ttseg_tbls
124+
ttseg_tblRef$date = as.Date(paste0(substr(ttseg_tblRef$tbl_name,16,19),"-",
125+
substr(ttseg_tblRef$tbl_name,20,21),"-",
126+
substr(ttseg_tblRef$tbl_name,22,23)))
127+
128+
trav_tbls = tbls[grep("ttdcutraversals",tbls)]
129+
130+
test = tbl(db,"ttseginventory_20150615")
131+
testdf = data_frame(tbl)
104132

‎_shiny/dataOutages/server.R

+36-12
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,75 @@
11
library(shiny)
22
library(leaflet)
33
library(RColorBrewer)
4+
library(DT)
45

56
plotList = readRDS("plotList.rds")
67
mapFrame = readRDS("mapFrame.rds")
8+
tabFrame = readRDS("tabFrame.rds")
79

810
timePoints = as.Date(c("2015-01-01","2015-07-31"))
911

1012
function(input, output, session) {
11-
13+
1214
pal <- colorNumeric(
1315
palette = c("Green","Yellow","Red"),
1416
domain = c(0,max(mapFrame$numOutages))
1517
)
16-
18+
1719
output$leaf <- renderLeaflet({
18-
leaflet(mapFrame) %>% addProviderTiles("CartoDB.DarkMatter",options = providerTileOptions(noWrap = TRUE)) %>%
20+
leaflet(mapFrame) %>% addProviderTiles("CartoDB.DarkMatter",options = providerTileOptions(noWrap = TRUE)) %>%
1921
setView(-122.6662589, 45.5317385, zoom = 9) %>% addCircleMarkers(lng=~long,lat=~lat,popup =~htmlLink,color =~pal(numOutages),fillOpacity = 0.6,stroke=FALSE,layerId=~station_id) %>%
2022
addLegend("bottomright", pal = pal, values = ~numOutages,
2123
title = "Number of Outages",
2224
opacity = 1
2325
)
2426
})
25-
27+
28+
add_title <- function(vis, ..., x_lab = "X units", title = "Plot Title")
29+
{
30+
add_axis(vis, "x", orient = "top", ticks = 0, title = title,
31+
properties = axis_props(
32+
axis = list(stroke = "white"),
33+
labels = list(fontSize = 0)
34+
), ...)
35+
}
36+
2637
plt = reactive({
2738
markerID = input$leaf_marker_click$id
2839
if(!is.null(markerID)){
2940
sid = input$leaf_marker_click$id
3041
plotFrame = plotList[[as.character(sid)]]
31-
42+
3243
tFunk = function(x){
3344
if(is.null(x)) return(NULL)
3445
return(as.character(plotFrame$day[plotFrame$id == x$id]))
3546
}
36-
47+
3748
plotFrame %>% ggvis(x=~day, y=~ variable, stroke =~def, fill =~def, key:=~id) %>%
38-
layer_points(opacity := 0.5) %>% add_tooltip(tFunk) %>%
49+
layer_points(opacity := 0.5) %>% add_tooltip(tFunk) %>%
3950
set_options(height = 200, width = "100%") %>%
40-
scale_nominal(property="fill", label = "Outage Flag", domain = c("Very Low Values","Only Empty Data", "Zero Rows of Data", "Detector Unavailable"), range = brewer.pal(4,"Set1")) %>%
51+
scale_nominal(property="fill", label = "Outage Flag", domain = c("Very Low Values","Only Empty Data", "Zero Rows of Data", "Detector Unavailable"), range = brewer.pal(4,"Set1")) %>%
4152
scale_nominal(property="stroke", label = "Outage Flag", domain = c("Very Low Values","Only Empty Data", "Zero Rows of Data", "Detector Unavailable"), range = brewer.pal(4,"Set1")) %>%
4253
add_axis("y", title = "Lane Number", title_offset=50)%>%
43-
add_axis("x", title = "")%>% scale_datetime(property="x",domain = timePoints,nice="month", expand=0)
54+
add_axis("x", title = "")%>% scale_datetime(property="x",domain = timePoints,nice="month", expand=0)%>% add_title(title = tabFrame$location[tabFrame$sid == sid])
4455
}
4556
})
46-
57+
4758
observeEvent(input$leaf_marker_click,{
4859
plt %>% bind_shiny("ggvis", "ggvis_ui")
4960
})
50-
51-
}
61+
62+
output$outageData = renderDataTable({
63+
colnames(tabFrame)=c("Station","Location",c("# Days w/ Very Low Values","# Days w/ Only Empty Data", "# Days w/ Zero Rows of Data"),"# Days w/ Outages (Total)")
64+
65+
createLink <- function(val) {
66+
sprintf('<a href="http://portal.its.pdx.edu/Portal/index.php/stations/view/id/%s/" target="_blank" class="btn btn-primary">%s</a>',val,val)
67+
}
68+
69+
links = createLink(tabFrame$Station)
70+
71+
tabFrame$Station = links
72+
datatable(tabFrame,escape = FALSE, options = list(lengthMenu = c(5, 10, 50), pageLength = 5))
73+
})
74+
75+
}

‎_shiny/dataOutages/ui.R

+14-5
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,23 @@
11
library(shiny)
22
library(leaflet)
33
library(ggvis)
4+
library(DT)
45

56
fluidPage(
67
titlePanel(title = "",windowTitle = "Data Outage Explorer"),
7-
fixedRow(
8-
leafletOutput("leaf", width = "100%",height = 400)
8+
tabsetPanel(
9+
tabPanel("Outage Explorer",
10+
fixedRow(
11+
leafletOutput("leaf", width = "100%",height = 300)
12+
),
13+
p("Click a point on the map to plot data outages"),
14+
fixedRow(
15+
uiOutput("ggvis_ui"),ggvisOutput("ggvis")
16+
)
917
),
10-
p("Click a point on the map to plot data outages"),
11-
fixedRow(
12-
uiOutput("ggvis_ui"),ggvisOutput("ggvis")
18+
tabPanel("Outage Table",
19+
dataTableOutput("outageData")
20+
)
1321
)
22+
1423
)

‎_shiny/laneNumber_speedDiff/server.R

+11-17
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,6 @@ library(knitr)
44
library(stats)
55

66
shinyServer(function(input, output, session) {
7-
img.width <- 800
8-
img.height <- 400
9-
options(RCHART_HEIGHT = img.height, RCHART_WIDTH = img.width)
10-
opts_chunk$set(fig.width=6, fig.height=4)
11-
127
laneCheck = readRDS("laneNumberCheck.rds")
138
laneCheck$flag=FALSE
149
laneCheck$flag[laneCheck$pDiff_10 <0]=TRUE
@@ -33,17 +28,16 @@ shinyServer(function(input, output, session) {
3328
}
3429
}
3530

36-
h <- laneFrame %>% ggvis(x = ~pDiff_10,fill= ~out) %>% group_by(out) %>%
37-
layer_histograms(width=input_slider(min=1,max=10,step=1,value=5,label="Bin Width (mph)")) %>%
38-
scale_nominal("fill", label = "Outlier Status",
39-
domain = c("OK", "Minor", "Major"),
40-
range = c("green", "yellow", "red")) %>%
41-
set_options(width = img.width, height = img.height) %>%
42-
add_tooltip(tooltipFunc(laneFrame$stationid, laneFrame$pDiff_10,laneFrame$out), 'hover') %>%
43-
add_axis("x", title = "5th Percentile Difference in Speed Between Lanes 1 and 2 (mph)")%>%
44-
add_axis("y", title = "Frequency")%>%
45-
bind_shiny("ggvis", "ggvis_ui")
46-
47-
31+
h = reactive({
32+
laneFrame %>% ggvis(x = ~pDiff_10,fill= ~out) %>% group_by(out) %>%
33+
layer_histograms(width=input$bin) %>%
34+
scale_nominal("fill", label = "Outlier Status",
35+
domain = c("OK", "Minor", "Major"),
36+
range = c("green", "yellow", "red")) %>%
37+
add_tooltip(tooltipFunc(laneFrame$stationid, laneFrame$pDiff_10,laneFrame$out), 'hover') %>%
38+
add_axis("x", title = "5th Percentile Difference in Speed Between Lanes 1 and 2 (mph)")%>%
39+
add_axis("y", title = "Frequency") %>% set_options(height = 300, width = "100%")
40+
})
41+
h %>% bind_shiny("ggvis", "ggvis_ui")
4842
})
4943

‎_shiny/laneNumber_speedDiff/ui.R

+10-8
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,14 @@ library(ggvis)
33
library(knitr)
44

55
shinyUI(fluidPage(
6-
mainPanel(
7-
uiOutput("ggvis_ui"),
8-
ggvisOutput("ggvis"),
9-
tags$ul(tags$li("Minor outliers lie outside the 'inner fence' with is defined by the interval [1st Quartile - 1.5*IQR, 3rd Quartile +1.5*IQR]"),
10-
tags$li("Major outliers lie outside the 'outer fence' with is defined by the interval [1st Quartile - 3*IQR, 3rd Quartile +3*IQR]"))
11-
)
12-
13-
6+
fixedRow(column(width = 8,
7+
wellPanel(sliderInput("bin","Bin Width (mph)",min=1,max=10,value=5,step=1))
8+
)),
9+
fixedRow(column(width=8,
10+
uiOutput("ggvis_ui"),
11+
ggvisOutput("ggvis"),
12+
wellPanel(tags$ul(tags$li("Minor outliers lie outside the 'inner fence' with is defined by the interval [1st Quartile - 1.5*IQR, 3rd Quartile +1.5*IQR]"),
13+
tags$li("Major outliers lie outside the 'outer fence' with is defined by the interval [1st Quartile - 3*IQR, 3rd Quartile +3*IQR]"))
14+
)))
15+
1416
))

‎_shiny/outlierExplorer/server.R

+51-49
Original file line numberDiff line numberDiff line change
@@ -3,22 +3,23 @@ library(ggvis)
33
library(knitr)
44
library(stats)
55
library(DT)
6+
require(plyr)
67

78
shinyServer(function(input, output, session) {
89
img.width <- 700
910
img.height <- 400
1011
options(RCHART_HEIGHT = img.height, RCHART_WIDTH = img.width)
1112
opts_chunk$set(fig.width=7, fig.height=4)
12-
13+
1314
unfiltered = readRDS("juneAggData_raw.rds")
14-
filtered = readRDS("juneAggData.rds")
15+
filtered = readRDS("juneAggData_clean.rds")
1516
data = filtered
1617
stationMeta = readRDS("stations.rds")
1718
lane = "all"
1819
quant = "speed"
1920
hour = 8
2021
weekdays = c("Mon","Tue","Wed","Thu","Fri","Sat","Sun")
21-
22+
2223
observeEvent(input$quant,({
2324
quant = tolower(input$quant)
2425
if(quant=="speed"){
@@ -29,7 +30,7 @@ shinyServer(function(input, output, session) {
2930
}else if(quant == "volume"){
3031
binRange = c(100,1000)
3132
binInc = 100
32-
histStart = 500
33+
histStart = 200
3334
binLabel = "Bin Width (vph)"
3435
}else if (quant=="occupancy"){
3536
binRange = c(1,10)
@@ -39,7 +40,7 @@ shinyServer(function(input, output, session) {
3940
}
4041
updateSliderInput(session = session, inputId = "hist",label =binLabel,value = histStart,min = binRange[1],max=binRange[2],step=binInc)
4142
}))
42-
43+
4344
plotFrame = reactive({
4445
laneSelect = input$lane
4546
if(laneSelect=="All (Aggregated)"){
@@ -48,40 +49,41 @@ shinyServer(function(input, output, session) {
4849
lane <<- laneSelect
4950
}
5051
# print(lane)
51-
52+
5253
if(input$filter=="Unfiltered"){
5354
data = unfiltered
5455
}else{
5556
data = filtered
5657
}
57-
58+
5859
hour <<-input$hour
5960
weekdays <<- input$weekdays
60-
61+
6162
quant <<- tolower(input$quant)
6263
#print(quant)
6364
#print(weekdays)
6465
#print(hour)
6566
#print(lane)
66-
67+
6768
pf = data.frame(matrix(nrow = length(data),ncol = 3))
6869
colnames(pf)=c("station_id","quantity","out")
6970
if(lane=="all"){
7071
for (i in 1:length(data)){
71-
if(!is.null(data[[i]])){
72-
sid = data[[i]]$station_id
72+
if(!is.na(data[i])){
73+
sid = as.numeric(names(data[i]))
7374
pf$station_id[i]=sid
74-
sData = data[[i]]$data
75+
sData = data[[i]]
7576
if(is.data.frame(sData)){
7677
rows = sData$hour==hour & sData$dow %in% weekdays
7778
if(sum(rows>0)){
7879
sub = sData[rows,]
7980
if(quant == "volume"){
80-
q = sum(sub$volume)
81+
temp = ddply(sub,"lanenumber",summarise,volume = sum(volume))
82+
q = mean(temp$volume, na.rm = TRUE)
8183
}else if (quant =="occupancy"){
82-
q = mean(sub$occupancy)
84+
q = mean(sub$occupancy, na.rm = TRUE)
8385
}else if (quant == "speed"){
84-
q = weighted.mean(sub$speed,sub$volume)
86+
q = weighted.mean(sub$speed,sub$volume, na.rm = TRUE)
8587
}
8688
pf$quantity[i]=q
8789
}else{
@@ -96,7 +98,7 @@ shinyServer(function(input, output, session) {
9698
}
9799
}
98100
}
99-
#
101+
#
100102
# else if(lane=="On-Ramp"){
101103
# for (i in 1:length(data)){
102104
# if(!is.null(data[[i]])){
@@ -133,20 +135,20 @@ shinyServer(function(input, output, session) {
133135
# }
134136
else{
135137
for (i in 1:length(data)){
136-
if(!is.null(data[[i]])){
137-
sid = data[[i]]$station_id
138+
if(!is.na(data[i])){
139+
sid = as.numeric(names(data[i]))
138140
pf$station_id[i]=sid
139-
sData = data[[i]]$data
141+
sData = data[[i]]
140142
if(is.data.frame(sData)){
141143
rows = sData$hour==hour & sData$dow %in% weekdays & as.character(sData$lanenumber)==lane
142144
if(sum(rows)>1){
143145
sub = sData[rows,]
144146
if(quant == "volume"){
145-
q = mean(sub$volume)
147+
q = mean(sub$volume, na.rm = TRUE)
146148
}else if (quant =="occupancy"){
147-
q = mean(sub$occupancy)
149+
q = mean(sub$occupancy, na.rm = TRUE)
148150
}else if (quant == "speed"){
149-
q = mean(sub$speed)
151+
q = mean(sub$speed, na.rm = TRUE)
150152
}
151153
pf$quantity[i]=q
152154
}else{
@@ -159,12 +161,12 @@ shinyServer(function(input, output, session) {
159161
pf$station_id[i]=NA
160162
pf$quantity[i]=NA
161163
}
162-
164+
163165
}
164166
}
165167
pf$out = NA
166168
comp = pf[complete.cases(pf[,1:2]),]
167-
169+
168170
if(nrow(comp)>0){
169171
quantiles = quantile(comp$quantity,c(0.25,0.75),na.rm=TRUE)
170172
iqr = as.numeric(quantiles[2]-quantiles[1])
@@ -174,64 +176,64 @@ shinyServer(function(input, output, session) {
174176
comp$out[(comp$quantity <fences[1])|(comp$quantity >fences[4])]="Major"
175177
comp$out=factor(comp$out,ordered = TRUE)
176178
}
177-
179+
178180
return(comp)
179181
})
180-
182+
181183
plt = reactive({
182184
quant = input$quant
183-
185+
184186
#print(quant)
185-
187+
186188
if(quant=="Speed"){
187189
xAxis = "Speed (mph)"
188-
190+
189191
}else if(quant == "Volume"){
190192
xAxis = "Volume (vph)"
191193
}else if (quant=="Occupancy"){
192194
xAxis = "Occupancy (% of time)"
193195
}
194-
196+
195197
h <- plotFrame %>% ggvis(x = ~quantity,fill= ~out) %>% group_by(out) %>%
196-
#layer_histograms(width=input$hist) %>%
198+
layer_histograms(width=input$hist) %>%
197199
scale_nominal("fill", label = "Outlier Status",
198200
domain = c("OK", "Minor", "Major"),
199201
range = c("green", "yellow", "red")) %>%
200-
set_options(width = img.width, height = img.height) %>%
202+
set_options(width = img.width, height = img.height) %>%
201203
add_axis("x", title = xAxis)%>%
202-
add_axis("y", title = "Frequency")
203-
204+
add_axis("y", title = "Frequency")
205+
204206
return(h)
205207
})
206-
208+
207209
densityPlot = reactive({
208210
quant = input$quant
209-
211+
210212
#print(quant)
211-
213+
212214
if(quant=="Speed"){
213215
xAxis = "Speed (mph)"
214-
216+
215217
}else if(quant == "Volume"){
216218
xAxis = "Volume (vph)"
217219
}else if (quant=="Occupancy"){
218220
xAxis = "Occupancy (% of time)"
219221
}
220-
222+
221223
h <- plotFrame %>% ggvis(x = ~quantity) %>%
222-
set_options(width = img.width, height = img.height) %>%
224+
set_options(width = img.width, height = img.height) %>%
223225
add_axis("x", title = xAxis)%>%
224226
add_axis("y", title = "Probability Density") %>%
225227
layer_densities(
226228
adjust = input$bandwidth,kernel="gaussian")
227-
229+
228230
return(h)
229231
})
230-
232+
231233
plt %>% bind_shiny("ggvis", "ggvis_ui")
232-
234+
233235
densityPlot %>% bind_shiny("ggvis_d", "ggvis_ui_d")
234-
236+
235237
output$mytable = renderDataTable({
236238
df = plotFrame()
237239
quantity = input$quant
@@ -247,18 +249,18 @@ shinyServer(function(input, output, session) {
247249
for (i in 1:nrow(df)){
248250
locations[i]= stationMeta$locationtext[stationMeta$stationid==df$`Station ID`[i]][1]
249251
}
250-
252+
251253
createLink <- function(val) {
252254
sprintf('<a href="http://portal.its.pdx.edu/Portal/index.php/stations/view/id/%s/" target="_blank" class="btn btn-primary">%s</a>',val,val)
253255
}
254-
256+
255257
links = createLink(df$`Station ID`)
256-
258+
257259
outTable = cbind(links,locations,df[,2:3])
258260
colnames(outTable)= c("Station ID","Location",qLab,"Outlier Status")
259261
datatable(outTable,escape = FALSE) %>% formatStyle("Outlier Status",backgroundColor = styleEqual(c("OK","Minor","Major"),c("white","yellow","red")))
260262
})
261-
263+
262264
output$sumTable = renderDataTable({
263265
df = plotFrame()
264266
statSum = as.data.frame(as.matrix(summary(df$quantity)))
@@ -274,6 +276,6 @@ shinyServer(function(input, output, session) {
274276
colnames(final)=c("Statistic","Value")
275277
datatable(final) %>% formatStyle("Statistic",backgroundColor = styleEqual(c("Lower Outer Fence","Lower Inner Fence","Upper Inner Fence","Upper Outer Fence"),c("red","yellow","yellow","red")))
276278
})
277-
279+
278280
})
279281

‎_shiny/speedValidation/.Rapp.history

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
load("/Users/bblanc/OneDrive/_ODOT/_Portal/investigations/_shiny/speedValidation/processedSpeedData.rds")

‎_shiny/speedValidation/legend.png

13.8 KB
Loading

‎_shiny/speedValidation/server.R

+7-2
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,11 @@ dataLabs$label = c("Observed","Same-time PORTAL Data","10-Week Historical Averag
1717

1818
shinyServer(function(input,output,session){
1919

20+
output$legend <- renderImage({
21+
# Return a list containing the filename
22+
list(src = "legend.png")
23+
}, deleteFile = FALSE)
24+
2025
extract = function(index,agg){
2126
speed = speeds[[index]]
2227
data = speed$melted
@@ -50,7 +55,7 @@ shinyServer(function(input,output,session){
5055
dmn = c(min(ranges),max(ranges))
5156

5257
p = agged %>% ggvis(x=~time,y=~value, fill=~label,stroke=~label) %>% group_by(variable) %>% layer_smooths(se=TRUE) %>%
53-
layer_points() %>% add_axis("y",title="Speed (mph)") %>% add_legend(scales = c("stroke","fill"),title="Data Source") %>%
58+
layer_points() %>% add_axis("y",title="Speed (mph)") %>% hide_legend(scales = c("stroke","fill")) %>%
5459
set_options(height = 400, width = "100%") %>% scale_numeric("y",domain= dmn, nice = TRUE)%>% add_title(title = lane, x_lab = "Time")
5560
#%>% #add_tooltip(tFunk)
5661

@@ -69,7 +74,7 @@ shinyServer(function(input,output,session){
6974
dmn = c(min(ranges),max(ranges))
7075

7176
p = agged %>% ggvis(x=~time,y=~value, fill=~label,stroke=~label) %>% group_by(variable) %>% layer_smooths(se=TRUE) %>%
72-
layer_points() %>% add_axis("y",title="Speed (mph)") %>% add_legend(scales = c("stroke","fill"),title="Data Source") %>%
77+
layer_points() %>% add_axis("y",title="Speed (mph)") %>% hide_legend(scales = c("stroke","fill")) %>%
7378
set_options(height = 400, width = "100%") %>% scale_numeric("y",domain= dmn, nice = TRUE)%>%add_title(title = lane, x_lab = "Time")
7479

7580
return(p)

‎_shiny/speedValidation/ui.R

+5-2
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,10 @@ locVec = unique(locVec)
1414

1515
shinyUI(
1616
fluidPage(
17-
titlePanel(title="Speed Validation Explorer"),
17+
fixedRow(
18+
column(8,h1("Speed Validation Explorer")),
19+
column(4,imageOutput("legend", height ="10px",inline = TRUE))
20+
),
1821
fixedRow(column(6,
1922
uiOutput("ggvis_ui_1"),ggvisOutput("ggvis_1")
2023
),
@@ -24,7 +27,7 @@ shinyUI(
2427
),
2528
fixedRow(column(12,
2629
wellPanel(selectInput("loc","Location",choices=locVec,selected=locVec[1]),
27-
sliderInput("agg","Aggregation (minutes)",min=1,max=5,step=1,value=3))
30+
sliderInput("agg","Aggregation (minutes)",min=1,max=5,step=1,value=2))
2831
)
2932
)
3033

‎brainscan.png

166 KB
Loading

‎sampleSpeedHeat.pdf

75.6 KB
Binary file not shown.

0 commit comments

Comments
 (0)
Please sign in to comment.