-
Notifications
You must be signed in to change notification settings - Fork 2
/
0_functions.R
416 lines (241 loc) · 15.6 KB
/
0_functions.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
# cycling probabilities
pcyc21 <-function(age,sex,dist,ebikes,equity,MS) {
#intervals for distance binning
distIntervals <-c(0.5,1.5,2.5,3.5,4.5,5.5,6.5,9.5,12.5,15.5,20.5,30.5,40.5,10000)
#get interval to use as nrow
nrow <- findInterval(dist,distIntervals)+1 # starts @ 0, add 1
prob <- 0
if (ebikes == 0) {
ncol <- paste(sex,age,sep="_")
prob <- pcycl_baseline[nrow,ncol]
} #end ebikes=0
else { #ebikes=1
ncol <- 'ebike' #same w or w/o equity
prob <- pcycl_baseline[nrow,ncol]
}
pcyc <- prob
pcyc
}
# speed by age/gender
tripspeed <-function(age,sex,biketype) {
#ageIntervals <-c(16,30,45,60,70,80)
# cat(age, " : ", sex, "\n")
if (biketype == 0) {
if (sex == 'Female'){
if (age == '16.59')
speed = 10.12
else
speed = 8.27
}
else #sex=male
{
if (age == '16.59')
speed = 10.87
else
speed = 9.08}
}
if (biketype == 1)
speed = 11.58
tripspeed = speed
}
# converts odds > prob
oddsp <- function (x){
podds <- x/(x+1)
}
# converts prob > odds
podds <- function (x)
{ podds<- x/(1-x) }
#calculates prob of using pushbike/ebike
bikechoice <-function(dist, tripsebike) {
#calculates prob of switch to cycling depending on: [age-sex-trip distance]
#intervals for distance binning
distIntervals <-c(0.5,1.5,2.5,3.5,4.5,5.5,6.5,9.5,12.5,15.5,20.5,30.5,40.5,10000)
#get interval to use as nrow
nrow <- findInterval(dist,distIntervals)+1 # starts @ 0, add 1
# Comment out hard coded trips ebike probabilities
# probstrip <- c(0.550,0.680,0.751,0.815,0.889,0.889,0.905,0.929,0.947,0.919,0.919,1.000,1.000,0.000)
# Read tripsebike from the pcycl_baseline variable tripsebike
probstrip <- tripsebike
result <- probstrip[nrow]
x <- runif(1,0,1)
bikechoice <- ifelse(x<result,1,0)
}
# calculates which individuals become potential cyclists
# Return IDs of all ppl (including also these who were cyclist already) who became potential cyclist using relative risk approach
directProbRRPPLIDs <- function(baselineSubset, DP, ebikes, equity, pcycl_baseline, region) {
# if DP == 1 -> don't process just return all IDs assuming that there is no population in which cyclists are 100%
if (DP == 1){
return(unique(baselineSubset$ID))
}
# calc number of cyclist in baselineSubset
totalNumberOfCyclistInBaselineSubset <- length(unique(baselineSubset[baselineSubset$Cycled == 1,]$ID))
# if observed rounded proportion of cyclist in baselineSubset >= DP value -> don't process, just return IDs of all cyclist, print info in a console.
# These cases could be filtered out in UI
shareOfCyclistInBaselineSubset <- totalNumberOfCyclistInBaselineSubset / length(unique(baselineSubset$ID))
# double rounding to deal with eg. 0.0453004622496148 -> should be rounded to 0.04, while
# 0.0493522774759716 -> 0.05
shareOfCyclistInBaselineSubset <- round(round(shareOfCyclistInBaselineSubset, digits = 3), digits = 2)
# >= because of rounding usage
if (shareOfCyclistInBaselineSubset >= DP){
# save that case in directProbCasesAboveGivenPerc
directProbCasesAboveGivenPerc[nrow(directProbCasesAboveGivenPerc) + 1, ] <<- list(DP, ebikes, equity, region)
# print info
print('Observed > DP')
print(shareOfCyclistInBaselineSubset)
return(unique(baselineSubset[baselineSubset$Cycled == 1,]$ID))
}
# just in case reset cyclist column
baselineSubset$cyclist <- 0
# init vector with IDs of ppl who are cyclist already
IDOfPplAlreadyCyclist <- c()
# init vector with IDs of ppl who are going to become cyclist
IDOfPplBecomingCyclist <- c()
# init vector with IDs for output (combining IDOfPplAlreadyCyclist + IDOfPplBecomingCyclist)
IDOfPplAllCyclistOutput <- c()
# calc how many cyclists should be drawn excluding # of ppl who already cycle
howManyCyclistNeeded <- round(DP * length(unique(baselineSubset$ID)), digits = 0) - totalNumberOfCyclistInBaselineSubset
# just in case check if number exceeds # of all ppl
howManyCyclistNeeded <- ifelse(howManyCyclistNeeded > length(unique(baselineSubset$ID)), length(unique(baselineSubset$ID)), howManyCyclistNeeded)
# cyclists in a population should be marked as cyclists for all trips
IDOfPplAlreadyCyclist <- unique(baselineSubset[baselineSubset$Cycled == 1, ]$ID)
baselineSubset[baselineSubset$ID %in% IDOfPplAlreadyCyclist, ]$cyclist <- 1
if (equity == 0) {
# init counter of remaining ppl (ppl that should be pick up from other subgroups because of lack of ppl in particular subgroups)
remainingCyclistsCounter <- 0
# work out proportion of cyclists by age-sex subgroups in baselineSubset, also store number of observations in every subgroup
cyclistsPropBySubgroups <- data.frame(agesex = c('16.59Male','16.59Female','60plusMale','60plusFemale'), stringsAsFactors = FALSE)
for (i in seq_len(nrow(cyclistsPropBySubgroups))){
cyclistsPropBySubgroups[i, c('ppl')] <- length(unique(baselineSubset[baselineSubset$agesex == cyclistsPropBySubgroups$agesex[i], ]$ID))
cyclistsPropBySubgroups[i, c('pplCyclist')] <- length(unique(baselineSubset[baselineSubset$Cycled == 1 & baselineSubset$agesex == cyclistsPropBySubgroups$agesex[i], ]$ID))
cyclistsPropBySubgroups[i, c('pplNonCyclist')] <- cyclistsPropBySubgroups[i, ]$ppl - cyclistsPropBySubgroups[i, ]$pplCyclist
cyclistsPropBySubgroups[i, c('prop')] <- round(cyclistsPropBySubgroups[i, ]$pplCyclist/cyclistsPropBySubgroups[i, ]$ppl, digits = 10)
}
# work out ratio, referencing (ratio=1) group is this with the largest number of ppl
referencingValue <- cyclistsPropBySubgroups[which.max(cyclistsPropBySubgroups$ppl), ]$prop
cyclistsPropBySubgroups$ratio <- mapply(function(propValue){
propValue/referencingValue
}, cyclistsPropBySubgroups$prop)
# calc working column
cyclistsPropBySubgroups$working <- mapply(function(ratio, pplNonCyclist){
ratio * pplNonCyclist
}, cyclistsPropBySubgroups$ratio, cyclistsPropBySubgroups$pplNonCyclist)
# calc working sum
workingSum <- sum(cyclistsPropBySubgroups$working)
# iterate over subgroups - calc pplAdditionalCyclists, pplAfterCyclistsSub
for (i in seq_len(nrow(cyclistsPropBySubgroups))){
cyclistsPropBySubgroups[i, c('pplAdditionalCyclists')] <- cyclistsPropBySubgroups[i, ]$working / workingSum * howManyCyclistNeeded
cyclistsPropBySubgroups[i, c('pplAfterCyclistsSub')] <- cyclistsPropBySubgroups[i, ]$pplNonCyclist - cyclistsPropBySubgroups[i, ]$pplAdditionalCyclists
# check if there are enough ppl from subgroup in a population; if more are selected -> use total number of subgroup members
realCyclistsInSubgroup <- round(ifelse(round(cyclistsPropBySubgroups[i, ]$pplAdditionalCyclists, digits = 0) > cyclistsPropBySubgroups[i, ]$pplNonCyclist, cyclistsPropBySubgroups[i, ]$pplNonCyclist, cyclistsPropBySubgroups[i, ]$pplAdditionalCyclists), digits = 0)
# pick up ppl who become cyclist but are not cyclist already
subgroupIDsOfPplBecomeCyclist <- sample(unique(baselineSubset[baselineSubset$cyclist != 1 & baselineSubset$agesex == as.character(cyclistsPropBySubgroups[i, ]$agesex),]$ID), realCyclistsInSubgroup, replace = F)
IDOfPplBecomingCyclist <- append(IDOfPplBecomingCyclist, subgroupIDsOfPplBecomeCyclist)
# work out remaining diff (if value > 0 this means that sample should be filled with ppl from other subgroups)
remainingCyclistsCounter <- remainingCyclistsCounter + ifelse(round(cyclistsPropBySubgroups[i, ]$pplAdditionalCyclists, digits = 0) - length(subgroupIDsOfPplBecomeCyclist) > 0, round(cyclistsPropBySubgroups[i, ]$pplAdditionalCyclists, digits = 0) - length(subgroupIDsOfPplBecomeCyclist), 0)
}
# print(cyclistsPropBySubgroups)
# fill scenario with ppl from other subgroups if remaining ppl exist
if (remainingCyclistsCounter > 0){
# just in case check if there is enough remaining ppl (rounding issues)
remainingPplCounter <- length(unique(baselineSubset[baselineSubset$cyclist != 1 & !(baselineSubset$ID %in% IDOfPplBecomingCyclist),]$ID))
if (remainingCyclistsCounter > remainingPplCounter){
print('remainingCyclistsCounter > remainingPplCounter')
remainingCyclistsCounter <- remainingPplCounter
}
# pick up remaining cyclists
filledIDsOfPplBecomeCyclist <- sample(unique(baselineSubset[baselineSubset$cyclist != 1 & !(baselineSubset$ID %in% IDOfPplBecomingCyclist),]$ID), remainingCyclistsCounter, replace = F)
IDOfPplBecomingCyclist <- append(IDOfPplBecomingCyclist, filledIDsOfPplBecomeCyclist)
}
# IDOfPplAlreadyCyclist are not included thus it means that trips which belong to already cyclist
# but are not cycled will be never drawn
IDOfPplAllCyclistOutput <- IDOfPplBecomingCyclist
# return IDs
return(IDOfPplAllCyclistOutput)
} else {
# pick up randomly ppl who are not cyclist using same prob. for all
IDOfPplBecomingCyclist <- sample(unique(baselineSubset[baselineSubset$cyclist != 1,]$ID), howManyCyclistNeeded, replace = F)
# IDOfPplAlreadyCyclist are not included thus it means that trips which belong to already cyclist
# but are not cycled will be never drawn
IDOfPplAllCyclistOutput <- IDOfPplBecomingCyclist
# return IDs
return(IDOfPplAllCyclistOutput)
}
}
#' Return IDs of all ppl (including also these who were cyclist already) who became potential cyclist using proportions of cyclists group
directProbProportionsPPLIDs <- function(baselineSubset, DP, ebikes, equity, pcycl_baseline, region) {
# if DP == 1 -> don't process just return all IDs assuming that there is no population in which cyclists are 100%
if (DP == 1){
return(unique(baselineSubset$ID))
}
# calc number of cyclist in baselineSubset
totalNumberOfCyclistInBaselineSubset <- length(unique(baselineSubset[baselineSubset$Cycled == 1,]$ID))
# if observed rounded proportion of cyclist in baselineSubset >= DP value -> don't process, just return IDs of all cyclist, print info in a console.
# These cases could be filtered out in UI
shareOfCyclistInBaselineSubset <- totalNumberOfCyclistInBaselineSubset / length(unique(baselineSubset$ID))
# double rounding to deal with eg. 0.0453004622496148 -> should be rounded to 0.04, while
# 0.0493522774759716 -> 0.05
shareOfCyclistInBaselineSubset <- round(round(shareOfCyclistInBaselineSubset, digits = 3), digits = 2)
# >= because of rounding usage
if (shareOfCyclistInBaselineSubset >= DP){
# save that case in directProbCasesAboveGivenPerc
directProbCasesAboveGivenPerc[nrow(directProbCasesAboveGivenPerc) + 1, ] <<- list(DP, ebikes, equity, region)
# print info
print('Observed > DP')
print(shareOfCyclistInBaselineSubset)
return(unique(baselineSubset[baselineSubset$Cycled == 1,]$ID))
}
# just in case reset cyclist column
baselineSubset$cyclist <- 0
# init vector with IDs of ppl who are cyclist already
IDOfPplAlreadyCyclist <- c()
# init vector with IDs of ppl who are going to become cyclist
IDOfPplBecomingCyclist <- c()
# init vector with IDs for output (combining IDOfPplAlreadyCyclist + IDOfPplBecomingCyclist)
IDOfPplAllCyclistOutput <- c()
# init counter of remaining ppl (ppl that should be pick up from other subgroups because of lack of ppl in particular subgroups)
remainingCyclistsCounter <- 0
# work out proportion of cyclists by age-sex subgroups in baselineSubset
cyclistsPropBySubgroups <- data.frame(agesex = c('16.59Male','16.59Female','60plusMale','60plusFemale'))
cyclistsPropBySubgroups$prop <-mapply(function(whichGroup) {
round(length(unique(baselineSubset[baselineSubset$Cycled == 1 & baselineSubset$agesex == whichGroup,]$ID))/totalNumberOfCyclistInBaselineSubset, digits = 2)
}, cyclistsPropBySubgroups$agesex)
# calc how many cyclists should be drawn excluding # of ppl who already cycle
howManyCyclistNeeded <- round(DP * length(unique(baselineSubset$ID)), digits = 0) - totalNumberOfCyclistInBaselineSubset
# just in case check if number exceeds # of all ppl
howManyCyclistNeeded <- ifelse(howManyCyclistNeeded > length(unique(baselineSubset$ID)), length(unique(baselineSubset$ID)), howManyCyclistNeeded)
# cyclists in a population should be marked as cyclists for all trips
IDOfPplAlreadyCyclist <- unique(baselineSubset[baselineSubset$Cycled == 1, ]$ID)
baselineSubset[baselineSubset$ID %in% IDOfPplAlreadyCyclist, ]$cyclist <- 1
if (equity == 0) {
for (i in seq_len(nrow(cyclistsPropBySubgroups))){
# calc how many cyclists should be drawn, taking into account cyclists prop
projectedCyclistsInSubgroup <- round(as.numeric(cyclistsPropBySubgroups[i, ]$prop) * howManyCyclistNeeded, digits = 0)
# check if there are enough ppl from subgroup in a population; if more are selected -> use total number of subgroup members
realCyclistsInSubgroup <- ifelse(projectedCyclistsInSubgroup > length(unique(baselineSubset[baselineSubset$cyclist != 1 & baselineSubset$agesex == as.character(cyclistsPropBySubgroups[i, ]$agesex), ]$ID)), length(unique(baselineSubset[baselineSubset$cyclist != 1 & baselineSubset$agesex == as.character(cyclistsPropBySubgroups[i, ]$agesex), ]$ID)), projectedCyclistsInSubgroup)
# pick up ppl who become cyclist but are not cyclist already
subgroupIDsOfPplBecomeCyclist <- sample(unique(baselineSubset[baselineSubset$cyclist != 1 & baselineSubset$agesex == as.character(cyclistsPropBySubgroups[i, ]$agesex),]$ID), realCyclistsInSubgroup, replace = F)
IDOfPplBecomingCyclist <- append(IDOfPplBecomingCyclist, subgroupIDsOfPplBecomeCyclist)
# work out remaining diff (if value > 0 this means that sample should be filled with ppl from other subgroups)
remainingCyclistsCounter <- remainingCyclistsCounter + ifelse(projectedCyclistsInSubgroup - length(subgroupIDsOfPplBecomeCyclist) <= 0, 0, projectedCyclistsInSubgroup - length(subgroupIDsOfPplBecomeCyclist))
}
# fill scenario with ppl from other subgroups if remaining ppl exist
if (remainingCyclistsCounter > 0){
filledIDsOfPplBecomeCyclist <- sample(unique(baselineSubset[baselineSubset$cyclist != 1 & !(baselineSubset$ID %in% IDOfPplBecomingCyclist),]$ID), remainingCyclistsCounter, replace = F)
IDOfPplBecomingCyclist <- append(IDOfPplBecomingCyclist, filledIDsOfPplBecomeCyclist)
}
# IDOfPplAlreadyCyclist are not included thus it means that trips which belong to already cyclist
# but are not cycled will be never drawn
IDOfPplAllCyclistOutput <- IDOfPplBecomingCyclist
# return IDs
return(IDOfPplAllCyclistOutput)
} else {
# pick up randomly ppl who are not cyclist using same prob. for all
IDOfPplBecomingCyclist <- sample(unique(baselineSubset[baselineSubset$cyclist != 1,]$ID), howManyCyclistNeeded, replace = F)
# IDOfPplAlreadyCyclist are not included thus it means that trips which belong to already cyclist
# but are not cycled will be never drawn
IDOfPplAllCyclistOutput <- IDOfPplBecomingCyclist
# return IDs
return(IDOfPplAllCyclistOutput)
}
}
## END FUNCTIONS