/
echoice2.R
4054 lines (3369 loc) · 120 KB
/
echoice2.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
# echoice2
# Notes -------------------------------------------------------------------
# ec_ functions work for both discrete demand (dd) and volumetric demand (vd)
# vd_ functions are specific to volumetric demand models
# dd_ functions are specific to discrete choice models
# Namespace ---------------------------------------------------------------
#' @importFrom magrittr %>%
NULL
#' @importFrom dplyr group_by
NULL
#' @importFrom dplyr select
NULL
#' @importFrom dplyr select_if
NULL
#' @importFrom dplyr filter
NULL
#' @importFrom dplyr mutate
NULL
#' @importFrom dplyr mutate_if
NULL
#' @importFrom dplyr mutate_all
NULL
#' @importFrom dplyr transmute
NULL
#' @importFrom dplyr n_distinct
NULL
#' @importFrom dplyr left_join
NULL
#' @importFrom dplyr arrange
NULL
#' @importFrom dplyr summarise
NULL
#' @importFrom dplyr summarise_all
NULL
#' @importFrom dplyr summarise_if
NULL
#' @importFrom dplyr across
NULL
#' @importFrom dplyr pull
NULL
#' @importFrom dplyr one_of
NULL
#' @importFrom dplyr arrange
NULL
#' @importFrom dplyr bind_rows
NULL
#' @importFrom dplyr bind_cols
NULL
#' @importFrom dplyr relocate
NULL
#' @importFrom dplyr rename_all
NULL
#' @importFrom dplyr group_split
NULL
#' @importFrom dplyr group_keys
NULL
#' @importFrom dplyr ntile
NULL
#' @importFrom dplyr rename
NULL
#' @importFrom tidyr pivot_longer
NULL
#' @importFrom tidyr pivot_wider
NULL
#' @importFrom stringr str_subset
NULL
#' @importFrom stringr str_remove
NULL
#' @importFrom stringr str_extract
NULL
#' @importFrom forcats fct_relabel
NULL
#' @importFrom forcats fct_recode
NULL
#' @importFrom purrr map
NULL
#' @importFrom purrr map_dfr
NULL
#' @importFrom purrr map_df
NULL
#' @importFrom purrr imap_dfr
NULL
#' @importFrom purrr map2
NULL
#' @importFrom purrr map_dbl
NULL
#' @importFrom purrr reduce
NULL
#' @importFrom tidyselect any_of
NULL
#' @importFrom tidyselect all_of
NULL
#' @importFrom tidyselect contains
NULL
#' @importFrom tidyselect last_col
NULL
#' @importFrom tidyselect everything
NULL
#' @importFrom tibble tibble
NULL
#' @importFrom tibble as_tibble
NULL
#' @importFrom tibble add_row
NULL
#' @importFrom tibble add_column
NULL
#' @importFrom tibble rowid_to_column
NULL
#' @importFrom tibble enframe
NULL
#' @importFrom stats cov2cor
NULL
#' @importFrom stats model.matrix.lm
NULL
#' @importFrom stats quantile
NULL
#' @importFrom stats rnorm
NULL
#' @importFrom stats sd
NULL
#' @importFrom graphics par
NULL
#' @importFrom ggplot2 ggplot
NULL
#' @importFrom ggplot2 geom_boxplot
NULL
#' @importFrom ggplot2 geom_line
NULL
#' @importFrom ggplot2 coord_flip
NULL
#' @importFrom ggplot2 facet_wrap
NULL
#' @importFrom ggplot2 aes
NULL
#' @importFrom ggplot2 guides
NULL
#' @importFrom utils combn
NULL
utils::globalVariables(c(".", ".MAE", ".MSE", ".bias", ".demdraws", ".hp", ".hpall",
"lvl","id","reference", "reference_lvl",
"rowid", "x",
".isfocal", ".prodid", ".s", "alt", "attr_level",
"attribute", "draw", "n", "task", "value", "xp", "part",
"p", "MAE", ".screendraws"))
# Utilities ---------------------------------------------------------------
#' Get the attribute of an object
#'
#' @param obj The object to get the attribute from.
#' @param attrname The name of the attribute to get.
#'
#' @return The attribute of the object.
#'
#' @examples
#' obj <- list(a = 1, b = 2)
#' attributes(obj)$test="hello"
#' `%.%`(obj, "test")
#'
#' @export
`%.%` <- function(obj,attrname) (attributes(obj))[[attrname]]
#' Log Marginal Density (Newton-Raftery)
#'
#' This function uses the quick-and-dirty Newton-Raftery approximation for log-marginal-density.
#'
#' Approximation of LMD based on Newton-Raftery.
#' It is not the most accurate, but a very fast method.
#'
#' @param ll A vector of log-likelihood values (i.e., draws)
#' @return A single numeric value representing the log marginal density
#'
#'
#' @examples
#' logll_values <- c(-4000, -4001, -4002)
#' logMargDenNRu(logll_values)
#' @export
logMargDenNRu=function(ll)
{
med = stats::median(ll)
return(med - log(mean(exp(-ll + med))))
}
#' Obtain Log Marginal Density from draw objects
#'
#' This is a helper function to quickly obtain log marginal density from a draw object
#'
#' Draws are split in 4 equal parts from start to finish, and LMD
#' is computed for each part. This helps to double-check convergence.
#'
#'
#' @param est 'echoice2' draw object
#' @return tibble with LMDs (first 25% of draws, next 25% of draws, ...)
#' @examples
#' data(icecream)
#' #run MCMC sampler (use way more than 50 draws for actual use)
#' icecream_est <- icecream %>% dplyr::filter(id<100) %>% vd_est_vdm(R=20, cores=2)
#' #obtain LMD by quartile of draws
#' ec_lmd_NR(icecream_est)
#'
#' @export
ec_lmd_NR=function(est){
return(
drop(est$loglike) %>%
enframe(name = 'draw') %>%
mutate(part=ntile(draw,4)) %>%
group_by(part) %>% summarise(lmd=logMargDenNRu(value), .groups='drop') %>%
mutate(part=part/4)
)
}
# Data manipulation -------------------------------------------------------
#clean data
vd_janitor=function(vd,
maxquant=999){
`%!in%` <- Negate(`%in%`)
#remove too high volumes
fid_toomuch = vd %>% dplyr::filter(x>maxquant) %>% dplyr::pull(id) %>% unique
#remove all0s
fid_toolittle = vd %>% group_by(id) %>% summarise(.s=sum(x)) %>% dplyr::filter(.s==0) %>% pull(id)
#combine filter
fid_all = base::intersect(fid_toolittle, fid_toomuch)
filter_summary=
tibble(
`overall`=fid_all%>%n_distinct,
`large quantities`=fid_toolittle%>%n_distinct,
`all 0` = fid_toolittle %>% n_distinct())
#filter and return
vd = vd %>% dplyr::filter(id %!in% fid_all)
attributes(vd)$filter=filter_summary
return(vd)
}
#' Dummy-code a categorical variable
#'
#'
#' @param data one column of categorical data to be dummy-coded
#' @return tibble with dummy variables
#' @examples
#' mytest=data.frame(attribute=factor(c('a','a','b','c','c')))
#' dummyvar(mytest)
#' @export
dummyvar<-function(data){
#note: retains missing values as NA
out = model.matrix.lm(~.-1,
data=data,
na.action = "na.pass")
attributes(out)[c("assign", "contrasts")]=NULL
return(as_tibble(out))
}
#' Create dummy variables within a tibble
#'
#'
#' @param dat A \code{tibble} with the data.
#' @param sel A character vector with the name(s) of the variables to be dummied.
#' @return tibble with dummy variables
#' @examples
#' mytest=data.frame(A=factor(c('a','a','b','c','c')), B=1:5)
#' dummify(mytest,"A")
#'
#' @export
dummify=function(dat, sel){
dat=as_tibble(dat)
for(i in seq_along(sel)){
selv=sel[i]
dummidata <- dat %>% select(all_of(selv)) %>% dummyvar()
dat<- dat %>% add_column(dummidata, .before = selv) %>%
select(-all_of(selv)) %>%
rename_all(gsub,
pattern = paste0("^(",selv,")"),
replacement = paste0(selv,":"))
}
return(dat)
}
#' Obtain attributes and levels from tidy choice data with dummies
#'
#'
#' @param tdc A tibble with choice data
#' @return tibble
#' @examples
#' mytest=data.frame(A=factor(c('a','a','b','c','c')), B=1:5)
#' dummied_data = dummify(mytest,"A")
#' get_attr_lvl(dummied_data)
#'
#' @export
get_attr_lvl=function(tdc){
tdc %>%
select(-any_of(c('id','task','alt','p','x')))%>%
names %>% tibble::enframe() %>%
mutate(attribute=stringr::str_extract(.$value,"^.*?(?=\\:)")) %>%
mutate(lvl=stringr::str_remove(.$value, .$attribute)) %>%
mutate(lvl=stringr::str_remove(.$lvl,"^(:)")) %>%
group_by(across("attribute")) %>%
mutate(reference_lvl=dplyr::first(lvl)) %>%
mutate(reference=ifelse(lvl==reference_lvl,1,0))%>%
mutate(lvl_abbrv=abbreviate(lvl))%>%
rename(attr_level=value)
}
#' Generate tidy choice data with dummies from long-format choice data
#'
#'
#' @param longdata tibble
#' @return tibble
#' @examples
#' data(icecream)
#' vd_long_tidy(icecream)
#'
#' @export
vd_long_tidy<-function(longdata){
#find categorical variables
catvars <-
longdata %>% select(tidyselect::where(is.factor)) %>% names
#dummify categorical variables
dummified <-
longdata %>%
dummify(catvars)
#get list of attribute levels
attrs <-
dummified %>% get_attr_lvl
#find reference categories in dummy coding
refcats <-
attrs %>% dplyr::filter(reference==1) %>% pull(attr_level)
#generate output, then add attributes
out <-
dummified %>% select(-any_of(refcats)) %>% add_column(int=1,.after='p')
attributes(out)$ec_data = list(choice_type='volumetric',
data_type='vd_tidy_choice',
attributes=attrs)
attributes(out)$Af = dummified %>% select_if(!(colnames(.)%in%c('id','task','alt','p','x')))
return(out)
}
#' Prepare choice data for analysis
#'
#' This utility function prepares tidy choice data for fast MCMC samplers.
#'
#' Note: This function is only exported because it makes it easier to tinker with this package.
#' This function re-arranges choice data for fast access in highly-optimized MCMC samplers.
#' It Pre-computes task-wise total expenditures `sumpsx` and generates indices `xfr`,`xto`,`lfr`,`lto` for fast data access.
#'
#' @param dt tidy choice data (columns: id, task, alt, x, p, attributes)
#' @param Af (optional) contains a full design matrix (for attribute-based screening), or, more generally, a design matrix used for attribute-based screening
#'
#' @return list containing information for estimation functions
#'
#' @examples
#' #minimal data example
#' dt <- structure(list(id = c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L,
#' 2L, 2L),
#' task = c(1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L),
#' alt = c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L),
#' x = c(1, 0, 2, 1, 0, 1, 2, 3, 1, 1, 0, 1),
#' p = c(0, 1, 1, 1, 2, 0, 2, 2, 1, 2, 1, 1),
#' attr2 = c(1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0),
#' attr1 = c(0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1)),
#' class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,-12L))
#' #run prep function
#' test <- dt %>% vd_prepare
#'
#' @export
vd_prepare <- function(dt, Af=NULL){
#arrange
dt <- dt %>%
mutate(id=as.integer(id)) %>%
arrange(as.numeric(id),task,alt) %>% mutate(xp=x*p)
#sumpxs+nalts
sumpxs_nalts <- dt %>% group_by(id,task) %>%
summarise(sumpxs=sum(xp),nalts=n(), .groups="drop")
#ntasks
ntasks<-dt %>% group_by(id) %>%
summarise(ntasks=n_distinct(task), .groups="drop") %>% pull(ntasks)
#xfr-xto
xfr_xto<-dt %>% group_by(id) %>% rowid_to_column() %>%
summarise(xfr=min(rowid),xto=max(rowid), .groups="drop")
#lfr-lto
lfr_lto<-sumpxs_nalts %>% group_by(id) %>%
rowid_to_column() %>%
summarise(lfr=min(rowid),lto=max(rowid), .groups="drop")
#tlens
tlens<-dt %>% group_by(id) %>% summarise(tlens=n_distinct(task), .groups='drop') %>% pull(tlens)
out=list(XX=dt$x,
PP=dt$p,
AA=dt %>% select(-id,-task,-alt,-x,-p,-xp)%>% as.matrix(),
nalts=sumpxs_nalts$nalts,
sumpxs=sumpxs_nalts$sumpxs,
ntasks=ntasks,
xfr=xfr_xto$xfr,xto=xfr_xto$xto,
lfr=lfr_lto$lfr,lto=lfr_lto$lto,
tlens=tlens,
idx=select(dt,id,task,alt))
#meta-information
ec_data = attributes(dt)$ec_data
ec_data$data_type="vdm_choice"
#full attribute data, screening lower limit
if(!is.null(Af)){
if(all(c("id","task","alt") %in% colnames(Af) )){
out$AAf=Af%>%select(-id,-task,-alt)%>% as.matrix()
foo <- dt %>% select(id,task,alt,x) %>% left_join(Af,by=c("id","task","alt")) %>% arrange(as.numeric(id),task,alt)
foo_check<-foo %>% select(-id,-task,-alt,-x) %>% is.na %>% sum
if(foo_check==0){
tauconst=1-(foo %>% dplyr::filter(x>0) %>%group_by(id) %>% summarise_all(max) %>% select(-id,-task,-alt,-x))
}else{
stop("Could not match full attribute tibble with choice data")
}
#bind_cols(Af)%>% filter(x>0) %>%group_by(id) %>% summarise_all(max) %>% select(-id,-task,-alt,-x)
}else{
message("Af does not contain id, task, alt columns. Assuming that attribute columns are properly sorted...")
out$AAf=Af%>% as.matrix()
tauconst=1-(dt %>% select(id,task,alt,x) %>%bind_cols(Af)%>% dplyr::filter(x>0) %>%group_by(id) %>% summarise_all(max) %>% select(-id,-task,-alt,-x))
}
out$tauconst=tauconst
#meta-information
ec_data$screening='attribute-based'
}
attributes(out)$ec_data = ec_data
attributes(out)$Af = attributes(dt)$Af
return(out)
}
#' Prepare choice data for analysis (without x being present)
#'
#' This utility function prepares tidy choice data (without x) for fast data access.
#'
#' Note: This function is only exported because it makes it easier to tinker with this package.
#' This function re-arranges choice data for fast access, mainly for demand prediction.
#'
#' @param dt tidy choice data (columns: id, task, alt, p, attributes)
#' @param Af (optional) contains a full design matrix (for attribute-based screening), or, more generally, a design matrix used for attribute-based screening
#'
#' @return list containing information for prediction functions
#'
#' @examples
#' #Minimal example:
#' #One attribute with 3 levels, 2 subjects, 3 alternatives, 2 tasks
#' dt <- structure(list(id = c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L,
#' 2L, 2L),
#' task = c(1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L),
#' alt = c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L),
#' x = c(1, 0, 2, 1, 0, 1, 2, 3, 1, 1, 0, 1),
#' p = c(0, 1, 1, 1, 2, 0, 2, 2, 1, 2, 1, 1),
#' attr2 = c(1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0),
#' attr1 = c(0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1)),
#' class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,-12L))
#' test <- dt %>% dplyr::select(-all_of("x")) %>% vd_prepare_nox()
#'
#' @export
vd_prepare_nox <- function(dt, Af=NULL){
`%!in%` = Negate(`%in%`)
#arrange
dt <- dt %>%
mutate(id=as.integer(id)) %>%
arrange(as.numeric(id),task,alt)
#ntasks
ntasks<-dt %>% group_by(id) %>%
summarise(ntasks=n_distinct(task), .groups="drop") %>% pull(ntasks)
#xfr-xto
xfr_xto<-dt %>% group_by(id) %>% rowid_to_column() %>%
summarise(xfr=min(rowid),xto=max(rowid), .groups="drop")
#sumpxs+nalts
sump_nalts <- dt %>% group_by(id,task) %>%
summarise(sump=sum(p),nalts=n(), .groups="drop")
#lfr-lto
lfr_lto<-sump_nalts %>% group_by(id) %>%
rowid_to_column() %>%
summarise(lfr=min(rowid),lto=max(rowid), .groups="drop")
#tlens
tlens<-dt %>% group_by(id) %>% summarise(tlens=n_distinct(task), .groups='drop') %>% pull(tlens)
#select_if(colnames(.) %in% c("a","c","d","e"))
out=list(PP=dt$p,
AA=dt %>% select_if((colnames(.) %!in% c('id','task','alt','p','x')))%>% as.matrix(),
nalts=sump_nalts$nalts,
ntasks=ntasks,
xfr=xfr_xto$xfr,xto=xfr_xto$xto,
lfr=lfr_lto$lfr,lto=lfr_lto$lto,
tlens=tlens,
idx=select(dt,id,task,alt))
#meta-information
ec_data = attributes(dt)$ec_data
#full attribute data, screening lower limit
if(!is.null(Af)){
if(all(c("id","task","alt") %in% colnames(Af) )){
out$AAf=Af%>%select(-id,-task,-alt)%>% as.matrix()
foo <- dt %>% select(id,task,alt,x) %>% left_join(Af,by=c("id","task","alt")) %>% arrange(as.numeric(id),task,alt)
foo_check<-foo %>% select(-id,-task,-alt,-x) %>% is.na %>% sum
if(foo_check==0){
tauconst=1-(foo %>% dplyr::filter(x>0) %>%group_by(id) %>% summarise_all(max) %>% select(-id,-task,-alt,-x))
}else{
stop("Could not match full attribute tibble with choice data")
}
#bind_cols(Af)%>% filter(x>0) %>%group_by(id) %>% summarise_all(max) %>% select(-id,-task,-alt,-x)
}else{
message("Af does not contain id, task, alt columns. Assuming that attribute columns are properly sorted...")
out$AAf=Af%>% as.matrix()
tauconst=1-(dt %>% select(id,task,alt,x) %>%bind_cols(Af)%>% dplyr::filter(x>0) %>%group_by(id) %>% summarise_all(max) %>% select(-id,-task,-alt,-x))
}
out$tauconst=tauconst
#meta-information
ec_data$screening='attribute-based'
}
# if('attributes_levels' %in% names(attributes(dt))){
# out$attributes_levels=attributes(dt)$attributes_levels
# }
# ec_data$attributes=
attributes(out)$ec_data = ec_data
attributes(out)$Af = attributes(dt)$Af
return(out)
}
#utility function
#input checker
vd_check_long=function(dat){
check1 <- all(c("id","task",'alt',"x","p") %in% colnames(dat))
return(check1)
}
dd_check_long=function(dat){
check1 <- all(c("id","task",'alt',"x","p") %in% colnames(dat))
return(check1)
}
#' Summarize attributes and levels
#'
#' Summarize attributes and levels in tidy choice data containing categorical attributes (before dummy-coding)
#'
#' This functions looks for categorical attributes and summaries their levels
#' This is helpful when evaluating a new choice data file.
#'
#'
#' @param data_in A tibble, containing long-format choice data
#' @return A tibble with one row per attribute, and a list of the levels
#' @examples
#' data(icecream)
#' ec_summarize_attrlvls(icecream)
#'
#' @export
ec_summarize_attrlvls<-function(data_in){
return(
data_in %>% select(-any_of(c('id','task','alt','p','x'))) %>%
map(table) %>%
map(names) %>%
map(paste,collapse=', ') %>%
as_tibble() %>%
pivot_longer(everything()) %>% rlang::set_names(c('attribute','levels')) )
}
#' @rdname ec_summarize_attrlvls
#' @export
ec_summarise_attrlvls <- ec_summarize_attrlvls
# Working with estimates and draw objects ---------------------------------
#' Obtain upper level model estimates
#'
#'
#' @param est is an 'echoice2' draw object (list)
#' @param quantiles quantile for CI
#' @return tibble with MU (upper level) summaries
#' @examples
#' data(icecream)
#' #run MCMC sampler (use way more than 20 draws for actual use)
#' icecream_est <- icecream %>% dplyr::filter(id<20) %>% vd_est_vdm(R=20, cores=2)
#' #Upper-level summary
#' icecream_est %>% ec_estimates_MU
#' @export
ec_estimates_MU=function(est, quantiles=c(.05,.95)){
quantiles_name=paste0("CI-",quantiles*100,"%")
parnames=est$parnames
estimates=
est$MUDraw %>%
as_tibble(.name_repair = ~make.names(seq_along(.), unique=TRUE)) %>%
rlang::set_names(parnames) %>%
pivot_longer(everything(),names_to='par') %>%
mutate(par=factor(par,levels=parnames)) %>%
group_by(par) %>%
summarise(mean=mean(value),
sd=sd(value),
!!(quantiles_name[1]):=quantile(value,probs=quantiles[1]),
!!(quantiles_name[2]):=quantile(value,probs=quantiles[2]),
sig=(prod(quantile(value,probs=quantiles))>0),
.groups='drop')
estimates$model=est$ec_type_short
estimates$error=est$error_specification
#add attribute groups
chk<-attributes(est)$ec_data$attributes %>% pull(attribute) %>% n_distinct()
if(chk>0){
estimates<-
estimates %>%
left_join(attributes(est)$ec_data$attributes %>%
select(attr_level,attribute,lvl,reference_lvl),
by=c('par'='attr_level')) %>%
relocate(attribute,.before=par) %>%
relocate(lvl,.before=par) %>% mutate(parameter=ifelse(!is.na(lvl),lvl,par))
}
#attr
return(estimates)
}
#' Obtain posterior mean estimates of upper level correlations
#'
#'
#' @param est is an 'echoice2' draw object (list)
#' @return estimates of upper level correlations
#' @examples
#' data(icecream)
#' #run MCMC sampler (use way more than 20 draws for actual use)
#' icecream_est <- icecream %>% dplyr::filter(id<20) %>% vd_est_vdm(R=20, cores=2)
#' icecream_est %>% ec_estimates_SIGMA_corr %>% round(2)
#' @export
ec_estimates_SIGMA_corr=function(est){
parnames=est$parnames
rownames(est$SIGMADraw)=parnames
colnames(est$SIGMADraw)=parnames
return(est$SIGMADraw %>% apply(1:2,mean) %>% cov2cor)
}
#' Obtain posterior mean estimates of upper level covariance
#'
#'
#' @param est is an 'echoice2' draw object (list)
#' @return estimates of upper level covariance
#' @examples
#' data(icecream)
#' #run MCMC sampler (use way more than 20 draws for actual use)
#' icecream_est <- icecream %>% dplyr::filter(id<50) %>% vd_est_vdm(R=20, cores=2)
#' icecream_est %>% ec_estimates_SIGMA %>% round(2)
#' @export
ec_estimates_SIGMA=function(est){
parnames=est$parnames
rownames(est$SIGMADraw)=parnames
colnames(est$SIGMADraw)=parnames
return(est$SIGMADraw %>% apply(1:2,mean))
}
#' Summarize attribute-based screening parameters
#'
#' Summarize attribute-based screening parameters from an attribute-based screening model in 'echoice2'
#'
#'
#' @param est is an 'echoice2' draw object (list) from a model with attribute-based screening
#' @param quantiles quantile for CI
#' @return tibble with screening summaries
#' @importFrom rlang :=
#' @examples
#' #run MCMC sampler (use way more than 20 draws for actual use)
#' data(icecream)
#' est_scr_icecream <- vd_est_vdm_screen(icecream%>%dplyr::filter(id<30), R=20, cores=2)
#' #summarise draws of screening probabilities
#' ec_estimates_screen(est_scr_icecream)
#' #Note: There is no variance in this illustrative example - more draws are needed
#'
#' @export
ec_estimates_screen=function(est,quantiles=c(.05,.95)){
quantiles_name=paste0("CI-",quantiles*100,"%")
out<-
est$deltaDraw %>%
as_tibble(.name_repair = ~make.names(seq_along(.), unique=TRUE)) %>%
rlang::set_names(colnames(attributes(est)$Af)) %>%
pivot_longer(cols = everything(), names_to = 'par') %>%
group_by(par) %>%
summarise(mean=mean(value),
sd=sd(value),
!!(quantiles_name[1]):=quantile(value,probs=quantiles[1],na.rm=TRUE),
!!(quantiles_name[2]):=quantile(value,probs=quantiles[2],na.rm=TRUE),
.groups='drop')
#add limits (maximum possible screening probability)
if(!is.null(est$dat)){
out<- out %>%
left_join(est$dat$tauconst %>%
colMeans() %>% enframe(name = 'par', value = 'limit'),
by = "par")
}
#add attribute groups
chk<-attributes(est)$ec_data$attributes %>% pull(attribute) %>% n_distinct()
if(chk>0){
out<-
out %>%
left_join(attributes(est)$ec_data$attributes %>%
select(attr_level,attribute,lvl),
by=c('par'='attr_level')) %>%
relocate(attribute,.before=par) %>%
relocate(lvl,.before=par)
}
return(out)
}
# The Models --------------------------------------------------------------
# vd_ functions are specific to volumetric demand models
# dd_ functions are specific to discrete choice models
# _est_ are estimation functions, i.e. they run the corresponding MCMC sampler
# _LL_ obtain the log lilelihood
# _dem_ generates demand prediction
# Key model variants
# - vdm: standard volumetric demand model
# - vdm_screen: attribute-based screening
# - vdm_screenpr: including price
# - vdm_ss: set size variation
# Volumetric Demand Estimation --------------------------------------------
#' Estimate volumetric demand model
#'
#'
#' @param vd A tibble, containing volumetric demand data (long format)
#' @param tidy A logical, whether to apply 'echoice2' tidier function (default: TRUE)
#' @param R A numeric, no of draws
#' @param keep A numeric, thinning factor
#' @param cores An integer, no of CPU cores to use (default: auto-detect)
#' @param error_dist A string defining the error term distribution, 'EV1' or 'Normal'
#' @param control A list containing additional settings
#'
#' @return An 'echoice2' draw object, in the form of a list
#'
#' @seealso [vd_dem_vdm()] to generate demand predictions based on this model
#' @seealso [vd_est_vdm_screen()] to estimate a volumetric demand model with screening
#'
#' @examples
#' data(icecream)
#' #run MCMC sampler (use way more than 10 draws for actual use)
#' icecream_est <- icecream %>% dplyr::filter(id<50) %>% vd_est_vdm(R=10, cores=2)
#' @export
vd_est_vdm=
function(vd,
tidy=TRUE,
R=100000,
keep=10,
cores=NULL,
error_dist="EV1",
control=list(include_data=TRUE)){
#check input data
if(!vd_check_long(vd)) stop("Check data")
#error dist: either Normal or EV1
if(!(error_dist=="Normal")){
error_dist="EV1"
}
#integer variables
vd<-vd %>% mutate(task=as.integer(.$task),
alt =as.integer(.$alt))
#Multicore settings
if(is.null(cores)){
cores=parallel::detectCores(logical=FALSE)
}
message(paste0("Using ",cores," cores"))
#re-arrange data
if(tidy){
dat <-
vd %>%
vd_long_tidy %>% vd_prepare
}else{
dat <-
vd %>% vd_prepare
}
#Prior
Bbar=matrix(rep(0,ncol(dat$AA)+3), ncol=ncol(dat$AA)+3)
A=0.01*diag(1)
nu=ncol(dat$AA)+9
V=(ncol(dat$AA)+9)*diag(ncol(dat$AA)+3)
Prior=list(Bbar=Bbar,A=A,nu=nu,V=V)
#Run model
if(error_dist=="EV1"){
out=
loop_vd2_RWMH( dat$XX,
dat$PP,
dat$AA,
dat$nalts,
dat$sumpxs,
dat$ntasks,
dat$xfr-1,
dat$xto-1,
dat$lfr-1,
dat$lto-1,
p=ncol(dat$AA)+3,
N=length(dat$xfr),
R=R,
keep=keep,
Bbar=Bbar,
A=A,
nu=nu,
V=V,
tuneinterval = 30, steptunestart=.15, tunelength=10000, tunestart=500,
progressinterval=100, cores=cores)
}else{
out=