/
Likelihood and Simulation Functions.R
executable file
·1755 lines (1726 loc) · 90.9 KB
/
Likelihood and Simulation 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
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
## Calculate likelihood for given parameters of detection function
## given carcass & road data.
library(distr) # for function truncate
library(Matrix)
allcues <- c("avian","mamm","cstate25" ,"cstate67","cstate8")
## file.folder <- "~/Documents/R files/dist samp/frequentist from cefe/"
file.folder <- ""
## ## prepare real data
## source("carc prepPC.r")
## start <- as.POSIXct("2010-02-01")
## end <- as.POSIXct("2010-05-31")
## carc.file <- "~/Documents/R files/dist samp/UCB Mortality Data 110702-cln111220.xls"
## dat <- carc.prep(carc.file = carc.file, period = TRUE, start = start,end = end, max.dist = 1.2, browse=F)
## carc <- dat[[1]]; head(carc,2)
## seff <- dat[[2]]
## seff <- seff[seff$Driver != "RZ",]
## carc <- carc[carc$driver != "RZ",]
## ## choose Roads
## load("roads.df.Rdata")
## roads.df.all <- roads.df #for backup
## roads.df <- roads.df.all[roads.df.all$rdID %in% rrs,]
## roads.df$p <- roads.df$LENGTH / sum(roads.df$LENGTH)
## ## Choose time period
## d.min <- min(carc$nday)
## d.max <- max(carc$nday)
## dseq <- (d.min-btrack):d.max
## d.pdf <- data.frame(date = dseq, p = 1/length(dseq))
## ## select subsets
## seff <- seff[seff$nday >= (d.min-btrack) & seff$nday <= d.max,]
## rrs <- unique(seff$Road)
## seff <- seff[seff$Road %in% rrs,]
## ## correct time in of 2:15 instead of 1415
## seff[seff$tin < seff$tout,"tin"] <- as.POSIXct("2009-03-19 14:15:00")
## seff <- seff[order(seff$nday),]
## out.real <- list(carc = carc, seff = seff, d.min = d.min, d.max = d.max,
## roads.df = roads.df, d.pdf = d.pdf, rrs = rrs)
## dr.out.master <- ddrr.fun(out.real, btrack = 5, browse = F)
## save(dr.out.master, file ="~/Documents/R files/dist samp/frequentist from cefe/all dr.out.Rdata")
## save(out.real, file = "realcarc120105.Rdata")
## save(seff, file = "seff.Rdata")
load("all dr.out.Rdata") # load surveillance
load("roads.df.Rdata") # load road network GIS data
btrack <- 5 # carcasses only visible for 5 days
load("realcarc120105.Rdata") # load real carcass data
load("seff.Rdata") # load prepped surveillance effort data
roads.df.all <- roads.df # for backup
## ## Fix time zone
## seff$tout <- format(seff$tout - 3600*9, usetz=F)
## seff$tin <- format(seff$tin - 3600*9, usetz=F)
## save(seff, file = "seff.Rdata")
######################################################################
## Detection probability given distance and sighting cue
######################################################################
h.fun <- function(xx, # distance from road
cc, # sighting cue
browse = FALSE,
sig.v, sig.m, sig25, d.shape,
...)
{
if(browse) browser()
allcues <- c("avian","mamm","cstate25" ,"cstate67","cstate8")
allcues <- allcues[1:3]
whicher <- allcues==cc
denom <- c(sig.v,sig.m,sig25)[whicher]
out <- exp( -(xx/denom)^d.shape )
out
}
######################################################################
## Vectorize h.fun
######################################################################
vec.h <- function(xx,cc,
sig.v, sig.m, sig25, d.shape)
{
Vectorize(h.fun, vectorize.args = c("xx","cc", "sig.v", "sig.m", "sig25", "d.shape"))
}
h.fun.v <- vec.h()
## Extract tripmat that shows # of times each trip type
## (tt=0,-1,-2,...) was driven in the last 5 days.
carcddrr <- function(out, btrack, verbose = F, browse = F) # d.min/max??
{
carc <- out$carc
seff <- out$seff
if(browse) browser()
tripmat <- matrix(0, nrow = nrow(carc), ncol = btrack+1)
colnames(tripmat) <- 0:-btrack
if(nrow(carc)>0)
{
for(ii in 1:nrow(carc))
{
on.road <- seff$Road == carc$roadwhich[ii]
temp.seff <- seff[on.road,]
temp.seff <- temp.seff[rev(order(temp.seff$nday)),]
temp.ddiff <- carc[ii,"nday"] - temp.seff$nday
in.window <- temp.ddiff >= 0 & temp.ddiff <= btrack # changed second exp to <=, not sure if it is right
temp.seff <- temp.seff[in.window,]
temp.seff$dsf <- temp.seff$nday - carc$nday[ii]
temp.tab <- xtabs(~temp.seff$dsf)
## feed the # of times each trip type (tt=0,...,-5) was driven into tripmat
tripmat[ii, match(names(temp.tab), colnames(tripmat))] <- temp.tab
## calculate how many trips on day it was found were before the trip
## note this removes trip of detection too because time in > time out
samedayaft <- sum(temp.seff$dsf == 0 & temp.seff$todin > carc$tod[ii])
tripmat[ii,1] <- tripmat[ii,1] - samedayaft
}
}
return( tripmat)
}
## Construct matrix of ddrr.output that corresponds to each carcass
## (if carc dd=7, rr = 192, we want tripmat for dd=2:7 rr=192, and
## repeat down vector for each carc. gets fed into g.fun. This
## handles the summation over d_i = (l_i-5, l_i) in the numerator
## NOTE: in the pr.functions I basically redid this again just copying
## the info from ddrr in a more straightforward way)
carcdrforward <- function(out, ddrr.output, btrack, verbose = F, browse = F)
{
if(browse) browser()
carc <- out$carc
ddrr <- ddrr.output$ddrr
tripmat <- ddrr.output$tripmat
ind <- NULL
for(ii in 1:nrow(carc))
{
for(tt in 0:btrack)
{
if(length(which(ddrr$dd == (carc$ll[ii]-tt) & ddrr$rr == carc$roadwhich[ii]))==0) browser()
ind <- c(ind, which(ddrr$dd == (carc$ll[ii]-tt) & ddrr$rr == carc$roadwhich[ii]))
}
}
tr.for <- tripmat[ind,]
ddrr.for <- ddrr[ind,]
tr.for <- tr.for[,1:max(ddrr.for$numtrips)]
ddrr.for$carc <- rep(1:nrow(carc), each = btrack + 1)
ddrr.for$yy <- rep(carc$roaddist, each = btrack + 1)
ddrr.for$cc <- rep(carc$cue, each = btrack + 1)
ddrr.for$ll <- rep(carc$ll, each = btrack + 1)
return(list(ddrr.for = ddrr.for, tr.for = tr.for))
}
## Calculate numerator of likelihood. Two main steps, first must
## calculat [t_i][d_i], then must calculate g(y,c,d,r) for each
## potential d,t combination
g.fun <- function(out, cdr.output, foreff.output,
sig.v, sig.m, sig25, d.shape,
gamma.y = F, st.like = T,
temp.gamm,
max.dist,
cue.trips,
browse = F)
{
if(browse) browser()
carc <- out$carc
seff <- out$seffs
## Calculate p det | each cue type at that distance
pdet.allcues <- h.fun.v(xx = rep(carc$roaddist, each = length(allcues[1:3])), cc = rep(allcues[1:3], nrow(carc)),
sig.v = sig.v, sig.m = sig.m, sig25 = sig25, d.shape = d.shape)
pdet.allcues <- matrix(pdet.allcues, nr = length(allcues[1:3]), nc = nrow(carc))
## calculate p det | given trip day (using camera trap p(cues | trip day)
p.margbytrip <- cue.trips %*% pdet.allcues
p.margbytrip.vec <- as.vector(p.margbytrip)
nr <- btrack + 1
nc <- nrow(carc)
ctripmat <- cdr.output
######################################################################
## Part 1
######################################################################
## Calculate [t] given road effort: probability of detection on
## trip * p of und on all previous days carcass existed
p.undmat <- matrix(1, nrow = nr, ncol = nc)
## for each possible age of the carcass (0,btrack)
for(ii in 1:nr)
{
## take the probability of undetection on all previous days
for(jj in 1:ii)
{
p.undmat[ii,] <- p.undmat[ii,] * (1-p.margbytrip[jj,])^ctripmat[,ii-jj+1]
}
}
## probability of detection given the cue (independent of time bc cue known)
pdet.givecue.vec <- h.fun.v(xx = carc$roaddist, cc = carc$cue,
sig.v = sig.v, sig.m = sig.m, sig25 = sig25, d.shape = d.shape)
pdet.givecue <- matrix(rep(pdet.givecue.vec, each = nrow(p.undmat)), nrow = nr, ncol = nc)
pdet.givecue.vec <- as.vector(pdet.givecue)
## prob of cue given t
p.cue <- cue.trips[,match(carc$cue, allcues)]
## [d] for each day
d.pdf <- out$d.pdf
ind.mat <- matrix(rep(carc$nday, each = nr) - rep(0:btrack, nc), nrow = nr, ncol = nc)
dps <- matrix(d.pdf[match(ind.mat, d.pdf$date), "p"], nr, nc)
## [d][det | cue seen, t, & undetection <t]
pdets.give.td <- p.undmat * p.cue * dps # don't need pdet.givecue here because its the same for all trips
## now we take colsums to give the probability of detecting a
## carcass with this cue on day dd over all carcasses (where we
## ignore [rr] since we can just multiply by it at the end
norm <- matrix(rep(colSums(pdets.give.td), each = nr), nr, nc)
p.t <- pdets.give.td / norm #note [d] is already in [t] now, so don't do it again later
######################################################################
## Part 2
######################################################################
## Now calculate the probability of detecting a carcass at that
## dist yy and with that cue cc for all the possible t's
## similar to the g.dk function below
ddrr.for <- foreff.output$ddrr.for
tr.for <- foreff.output$tr.for
## initialize gdrs (row is for each dd-rr combo, col is for subdivs)
undet <- matrix(1, nr = nr, nc = nc)
gdrs <- matrix(0, nr = nr, nc = nc)
left.trunc <- matrix(0, nr = nr, nc = nc)
for(ii in 1:(ncol(tr.for)-1)) # -1 because last trip cannot be counted as an undetection (must be a detection)
{
is.trip <- ddrr.for$numtrips >= ii
which.trips <- matrix(tr.for[,ii] + 1, nr, nc)
is.trip.mat <- !is.na(which.trips)
# + 1 is because trip 0's correspond to 1st row of
# pmarg.bytrip, need to generalize if add tod
## need vector giving probability of sighting cue on that trip
sel.mat <- cbind(as.vector(which.trips), match(ddrr.for$cc, colnames(cue.trips)))
p.cue.mat <- matrix(cue.trips[sel.mat], nr, nc)
if(ii > 1)
{ # need to add undetection prob for last trip
last.which.trips <- tr.for[is.trip,ii-1] + 1
## because p.margybytip is a nc*nr vector now, need to
## make sure each carcass is matched with its own
## p.margbytrip and not the first one
sel.mat.marg <- which(is.trip.mat, T)
sel.mat.marg[,1] <- last.which.trips
undet[is.trip.mat] <- undet[is.trip.mat]*(1 - p.margbytrip[sel.mat.marg])
}
gdrs[is.trip.mat] <- gdrs[is.trip] + undet[is.trip.mat] * p.cue.mat[is.trip.mat]
## if(sum(gdrs>1)>1) browser()
## Need to left truncate effort outside time window. To do
## this have a separate matrix that will save a snapshot of
## gdrs at the last trip before d.min (the cumulative
## probability of having detected a carcass between d.min)
## which will then be subtracted from gdrs at the end.
## befores <- as.numeric(ddrr.for$dd) + tr.for[,ii] < out$d.min #trips being considered are before
befores <- ind.mat + tr.for[,ii] < out$d.min
if(ii<ncol(tr.for)) #if not at the max numtrips yet see if the next trip is after d.min
{
next.after <- ind.mat + tr.for[,ii+1] >= out$d.min
## next.after <- as.numeric(ddrr.for$dd) + tr.for[,ii + 1] >= out$d.min #& it is the last trip before d.min
}else{ #if at max numtrips, then nextafter is TRUE because we want to subtract all previous prob
next.after <- matrix(TRUE, nr ,nc) # this way, if all trips were before d.min, left.trunc becomes the full marg prob
}
next.after[is.na(next.after)] <- TRUE
left.trunc[is.trip.mat & befores & next.after] <- gdrs[is.trip.mat & befores & next.after]
}
gdrs <- gdrs - left.trunc
## now multiply gdrs by the probability of detecting with that cue * [c|t]
## browser()
gdrs <- gdrs * pdet.givecue.vec
gdrs <- matrix(gdrs, nr = nr, nc = nc)
## multiply by [t][d] but only [d] if doing st.like
pdets.and.td <- gdrs * p.t
if(st.like) pdets.and.td <- pdets.and.td* dps
## sum across t
pdets <- colSums(pdets.and.td)
## add [rr] and [yy]
if(gamma.y)
{ # use truncated gamma to get density
y.pdf <- d(temp.gamm)(carc$roaddist)
}else{
y.pdf <- dunif(carc$roaddist,0,max.dist)
}
## multiply by [r]'s (if st.like only)
pdets.and.ry <- pdets * y.pdf
if(st.like) pdets.and.ry <- pdets.and.ry * out$roads.df[match(carc$roadwhich, out$roads.df$rdID), "p"]
## multiply pdets.and.ry across carcasses in the likelihood function (take logsum really)
return(pdets.and.ry)
## return(list(p.t = p.t, pdets.and.ry = pdets.and.ry) )
}
## note gdrs>1 bc they are prob densities at yy
## Create effort matrices, ddrr giving road-day combos & number of
## subsequent trips w/in btrack days, and tripmat giving which trips
## were done for all d in [d.min-5, d.max]
ddrr.fun <- function(out, btrack, browse = F)
{
seffset <- out$seff
d.min <- out$d.min
d.max <- out$d.max
if(browse) browser()
seffset$nday.fac <- factor(seffset$nday, levels = (d.min-btrack):d.max)
stab <- xtabs(~Road + nday.fac, seffset)
nc <- ncol(stab)
nr <- nrow(stab)
tripmat <-matrix(NA, nrow = nr*nc, ncol = 100) #100 is arbitrary assumed uperbound on # of trips in next btrack days
ddrr <- data.frame(rr = rep(NA, nr*nc), dd = rep(NA, nr*nc), numtrips = rep(NA, nr*nc),
dd.p = rep(NA, nr*nc), rr.p = rep(NA, nr*nc))
stepper <- 0
for(r.ind in 1:nr)
{
for(d.ind in 1:nc)
{
stepper <- stepper + 1
ddrr[stepper,"rr"] <- rownames(stab)[r.ind]
ddrr[stepper,"dd"] <- colnames(stab)[d.ind]
ddrr[stepper,"dd.p"] <- out$d.pdf[out$d.pdf$date == ddrr[stepper, "dd"], "p"]
ddrr[stepper,"rr.p"] <- out$roads.df[out$roads.df$rdID ==ddrr[stepper,"rr"],"p"]
## This ifelse deals with days at the end of time window so rep() statement works
# don't need to worry about truncating effort at end if
# data fed in is from d.min - btrack : d.max. Still need
# to truncate effort at beginning (do it in gd.fun)
if(d.ind + btrack > nc)
{
temp.dmax <- nc
temp.btrack <- btrack - (d.ind + btrack - nc)
}else{
temp.dmax <- d.ind + btrack
temp.btrack <- btrack
}
temp.trip.days <- rep(0:temp.btrack, stab[r.ind, d.ind:temp.dmax])
ddrr[stepper,"numtrips"] <- length(temp.trip.days)
if(ddrr[stepper,"numtrips"] > 0)
{
tripmat[stepper, 1:length(temp.trip.days)] <- temp.trip.days
}
}
}
maxnumtrips <- max(ddrr$numtrips)
tripmat <- tripmat[,1:maxnumtrips]
output <- list(ddrr = ddrr, tripmat = tripmat)
return(output)
}
## ## Create effort matrices, ddrr giving road-day combos & number of
## ## subsequent trips w/in btrack days, and tripmat giving which trips
## ## were done for all d in [d.min-5, d.max]
## ddrr.fun <- function(out, btrack, browse = F)
## {
## seffset <- out$seff
## d.min <- out$d.min
## d.max <- out$d.max
## if(browse) browser()
## seffset$nday.fac <- factor(seffset$nday, levels = (d.min-btrack):d.max)
## stab <- xtabs(~Road + nday.fac, seffset)
## nc <- ncol(stab)
## nr <- nrow(stab)
## tripmat <-matrix(NA, nrow = nr*nc, ncol = 100) #100 is arbitrary assumed uperbound on # of trips in next btrack days
## ddrr <- data.frame(rr = rep(NA, nr*nc), dd = rep(NA, nr*nc), numtrips = rep(NA, nr*nc),
## dd.p = rep(NA, nr*nc), rr.p = rep(NA, nr*nc))
## ddrr[,"rr"] <- rep(rownames(stab), each = nc)
## ddrr[,"dd"] <- as.numeric(rep(colnames(stab), nr))
## matcher <- match(ddrr[,"dd"], out$d.pdf$date)
## ddrr[,"dd.p"] <- out$d.pdf[matcher, "p"]
## matcher <- match(ddrr[,"rr"], out$roads.df$rdID)
## ddrr[,"rr.p"] <- out$roads.df[matcher,"p"]
## ## This ifelse deals with days at the end of time window so rep() statement works
## # don't need to worry about truncating effort at end if
## # data fed in is from d.min - btrack : d.max. Still need
## # to truncate effort at beginning (do it in gd.fun)
## temp.dmax <- ddrr$dd + btrack
## temp.btrack <- rep(btrack, nc*nr)
## grtr <- (as.numeric(ddrr$dd) + btrack) > out$d.max
## temp.dmax[grtr] <- out$d.max
## temp.btrack[grtr] <- out$d.max - ddrr$dd[grtr]
## temp.trip.days <- sapply
## temp.trip.days <- rep(0:temp.btrack, stab[r.ind, d.ind:temp.dmax])
## ddrr[stepper,"numtrips"] <- length(temp.trip.days)
## if(ddrr[stepper,"numtrips"] > 0)
## {
## tripmat[stepper, 1:length(temp.trip.days)] <- temp.trip.days
## }
## }
## }
## maxnumtrips <- max(ddrr$numtrips)
## tripmat <- tripmat[,1:maxnumtrips]
## output <- list(ddrr = ddrr, tripmat = tripmat)
## return(output)
## }
## Select ddrr from master file
ddrr.select <- function(out, btrack,
master.file = "all dr.out.Rdata",
truncate.end = T,
browse = F)
{
if(browse) browser()
load(master.file)
ddrr <- dr.out.master$ddrr
tripmat<- dr.out.master$tripmat
## select for road-days in out
sel <- ddrr[,"rr"] %in% out$roads.df$rdID
sel <- sel & ddrr[,"dd"] %in% (out$d.min - btrack):out$d.max
ddrr <- ddrr[sel,]
tripmat <- tripmat[sel,]
if(truncate.end)
{
for(ii in 0:btrack)
{
temp.ind <- ddrr[,"dd"] == out$d.max - ii
grtr <- tripmat[temp.ind, ] > ii
if(sum(temp.ind)>1)
{
less.trips <- rowSums(grtr, na.rm = T)
}else{
less.trips <- sum(grtr, na.rm = T)
}
ddrr[temp.ind, "numtrips"] <- ddrr[temp.ind, "numtrips"] - less.trips
tripmat[temp.ind,][grtr] <- NA # remove all trips after d.max
}
}
output <- list(ddrr = ddrr, tripmat = tripmat)
return(output)
}
## ## Create ddrr matrix for pr.functions. Just calculate ddrr for all dd-rr within btrack days of a carc
## ddrr.carc <- function(out, btrack, browse = F)
## {
## carc <- out$carc
## seffset <- out$seff
## d.min <- out$d.min
## d.max <- out$d.max
## if(browse) browser()
## seffset$nday.fac <- factor(seffset$nday, levels = (d.min-btrack):d.max)
## stab <- xtabs(~Road + nday.fac, seffset)
## tripmat <-matrix(NA, nrow = (btrack+1)*nrow(carc), ncol = 100) #100 is arbitrary assumed uperbound on # of trips in next btrack days
## ddrr <- data.frame(rr = rep(NA, (btrack+1)*nrow(carc)), dd = rep(NA, (btrack+1)*nrow(carc)), numtrips = rep(NA, (btrack+1)*nrow(carc)),
## dd.p = rep(NA, (btrack+1)*nrow(carc)), rr.p = rep(NA, (btrack+1)*nrow(carc)))
## for(ii in 1:nrow(carc))
## {
## start.ind <- (ii-1)*(btrack+1)+1
## ddrr[start.ind:(start.ind+btrack), "rr"] <- carc$roadwhich[ii]
## ddrr[start.ind:(start.ind+btrack), "dd"] <- carc$ll[ii] - 0:btrack
## }
## ddrr.str <- paste(ddrr$rr, ddrr$dd) #for matching to n.in.eff below
## unq.rows <- !duplicated(ddrr.str)
## unq.ddrr <- ddrr[unq.rows,]
## unq.tripmat <- tripmat[unq.rows,]
## nc <- ncol(stab)
## nr <- nrow(stab)
## for(ii in 1:sum(unq.rows))
## {
## unq.ddrr[ii,"dd.p"] <- out$d.pdf[out$d.pdf$date == unq.ddrr[ii, "dd"], "p"]
## unq.ddrr[ii,"rr.p"] <- out$roads.df[out$roads.df$rdID ==unq.ddrr[ii,"rr"],"p"]
## if(unq.ddrr[ii,"dd"] + btrack > out$d.max)
## {
## temp.dmax <- out$d.max
## temp.btrack <- btrack - (unq.ddrr[ii,"dd"] + btrack - out$d.max)
## }else{
## temp.dmax <- unq.ddrr[ii,"dd"] + btrack
## temp.btrack <- btrack
## }
## temp.trip.days <- rep(0:temp.btrack, stab[rownames(stab)==unq.ddrr[ii,"rr"], colnames(stab) %in% unq.ddrr[ii,"dd"]:temp.dmax])
## unq.ddrr[ii,"numtrips"] <- length(temp.trip.days)
## if(unq.ddrr[ii,"numtrips"] > 0)
## {
## unq.tripmat[ii, 1:length(temp.trip.days)] <- temp.trip.days
## }
## }
## maxnumtrips <- max(unq.ddrr$numtrips)
## unq.tripmat <- unq.tripmat[,1:maxnumtrips]
## matcher <- match(ddrr.str, ddrr.str[unq.rows])
## ddrr <- unq.ddrr[matcher,]
## tripmat <- unq.tripmat[matcher,]
## output <- list(ddrr = ddrr, tripmat = tripmat)
## return(output)
## }
## Calculate the probability of detecting each carcass that was
## detected given only r and d, for use in the likelihood that does
## not account for spatiotemporal patterns (i.e. no
## [r,d]). Denominator for non-sptemp likelihood
pr.fun <- function(out, cdr.output, ddrr.output,
sig.v, sig.m, sig25, d.shape,
yys = yy.seq, # quadrature subdivisions
gamma.y = F,
temp.gamm, max.dist, cue.trips,
browse = F)
{
if(browse) browser()
carc <- out$carc
## Calculate p det | each cue type at quadtrature distances
pdet.allcues <- h.fun.v(xx = rep(yys, each = length(allcues[1:3])), cc = rep(allcues[1:3], length(yys)),
sig.v = sig.v, sig.m = sig.m, sig25 = sig25, d.shape = d.shape)
pdet.allcues <- matrix(pdet.allcues, nr = length(allcues[1:3]), nc = length(yys))
## calculate p det | given trip day (using camera trap p(cues | trip day)
p.margbytrip <- cue.trips %*% pdet.allcues
## p.margbytrip.vec <- as.vector(p.margbytrip)
nr <- btrack + 1
nc <- nrow(carc)
ctripmat <- cdr.output
######################################################################
## Part 1
######################################################################
## Calculate [t] given road effort: probability of detection on
## trip * p of und on all previous days carcass existed
p.undmat <- array(1, dim =c(nr, nc, length(yys)))
## for each possible age of the carcass (0,btrack)
for(ii in 1:nr)
{
## take the probability of undetection on all previous days
for(jj in 1:ii)
{
is.trip <- which(ctripmat[,ii-jj+1]>0) #which carcasses had trip on that day (for speed)
temp.trips <- ctripmat[rep(is.trip, length(yys)),ii-jj+1]
p.undmat[ii,is.trip,] <- p.undmat[ii,is.trip,] * (1-p.margbytrip[rep(jj,length(is.trip)),]) ^temp.trips
}
}
## Calculate probability of detection on that day
## probability of detection given the cue (independent of time bc cue known)
## pdet.givecue <- pdet.allcues[match(carc$cue, allcues[1:3]),]
## prob of cue given t
p.cue <- cue.trips[,match(carc$cue, allcues[1:3])]
## [d] for each day
d.pdf <- out$d.pdf
ind.mat <- matrix(rep(carc$nday, each = nr) - rep(0:btrack, nc), nrow = nr, ncol = nc)
dps <- matrix(d.pdf[match(ind.mat, d.pdf$date), "p"], nr, nc)
## [d][det | cue seen, t, & undetection <t]
# don't need pdet.givecue here because its the same for all trips
# and so it divides out when we normalize below (basicaly [t] is
# just the prob of not observing previously for each day
pdets.give.td <- abind(lapply(1:length(yys), function(kkk) p.undmat[,,kkk] * p.cue * dps), along = 3)
## now we take colsums to give the probability of detecting a
## carcass with this cue on day dd over all carcasses (where we
## ignore [rr] since we can just multiply by it at the end
norm <- array(rep(colSums(pdets.give.td), each = nr), dim = c(nr, nc, length(yys)))
p.t <- pdets.give.td / norm #note [d] is already in [t] now, so don't do it again later
######################################################################
## Part 2
######################################################################
## Now calculate the probability of detecting a carcass at each
## yys dist for each trip and for each possible days old of the
## carcass
## Select the future btrack effort from the ddrr matrix that
## matches to the btrack days behind each carcass
ddrr <- ddrr.output$ddrr
tripmat <- ddrr.output$tripmat
ddrr.str <- paste(ddrr$rr, ddrr$dd) #for matching to n.in.eff below
## match ddrr.for and tr.for rows to corresponding rr-dd from carc
carc.str <- paste(rep(carc$roadwhich, each = nr), as.vector(ind.mat))
matcher <- match(carc.str, ddrr.str)
ddrr <- ddrr[matcher,]
tripmat <- tripmat[matcher,]
## initialize gdrs (row is for each dd-rr combo, col is for subdivs)
gdrs <- matrix(0, nr = nrow(ddrr), ncol = length(yys))
left.trunc <- matrix(0, nr = nrow(ddrr), ncol = length(yys))
for(ii in 1:ncol(tripmat)) # -1 because last trip cannot be counted as an undetection (must be a detection)
{
## if there are still trips for that dd-rr combo
is.trip <- ddrr$numtrips >= ii
## which trips are they (classified by t_i) but we add + 1 to
## allow us to index the t=0 trips as the first row of the
## p.margybytrip matrix
which.trips <- tripmat[is.trip,ii] + 1
## the probability of detection is the accumulated probability
## of detection + (1-the accumulated probability of
## detection)*(the marginal probability of detection on the
## next trip classified by t)
gdrs[is.trip,] <- gdrs[is.trip,] + (1-gdrs[is.trip,]) * p.margbytrip[which.trips,]
## Need to left truncate effort outside time window. To do
## this have a separate matrix that will save a snapshot of
## gdrs at the last trip before d.min (the cumulative
## probability of having detected a carcass between d.min)
## which will then be subtracted from gdrs at the end.
befores <- as.numeric(ddrr$dd[is.trip]) + tripmat[is.trip,ii] < out$d.min #trips being considered are before
if(ii<ncol(tripmat)) #if not at the max numtrips yet see if the next trip is after d.min
{
next.after <- as.numeric(ddrr$dd[is.trip]) + tripmat[is.trip,ii + 1] >= out$d.min #& it is the last trip before d.min
}else{ #if at max numtrips, then nextafter is TRUE because we want to subtract all previous prob
next.after <- TRUE # this way, if all trips were before d.min, left.trunc becomes the full marg prob
}
next.after[is.na(next.after)] <- TRUE
if(sum(is.trip)==1) #separate if statement if it is a vector not a matrix
{
left.trunc[is.trip,][befores & next.after] <- gdrs[is.trip,][befores & next.after]
}else{
left.trunc[is.trip,][befores & next.after,] <- gdrs[is.trip,][befores & next.after,]
}
}
gdrs <- gdrs - left.trunc
## re-order so it matches the p.t dimensions
gdrs.arr <- array(gdrs, dim = c(nr, nc, length(yys)))
## multiply by p.t to collapse across the nr (potential days since death) dimension
gdrs.t <- gdrs.arr * p.t
## multiply by y.pdf to collapse across the length(yys) dimension
if(gamma.y)
{
## y.pdf <- d(temp.gamm)(yy.seq)
y.pdf <- p(temp.gamm)(yy.seq + int/2) - p(temp.gamm)(yy.seq - int/2)
}else{
y.pdf <- punif(yy.seq + int/2, 0, max.dist) - punif(yy.seq - int/2, 0, max.dist)
## y.pdf <- dunif(yy.seq, 0, max.dist)
}
## now have marginal probability of detecting the carcass that was detected
carc.probs <- colSums(gdrs.t) %*% y.pdf
return(carc.probs)
}
## Calculate the probability of detecting each carcass that was
## detected given rr, dd, AND yy. For use in Horvitz-Thompson
## estimator without spatiotemporal patterns (i.e. no [r,d]).
pr.fun.yspec <- function(out, cdr.output, ddrr.output,
sig.v, sig.m, sig25, d.shape,
yys = yy.seq, # quadrature subdivisions
gamma.y = F,
temp.gamm = NULL, cue.trips,
browse = F, late.br = F)
{
if(browse) browser()
carc <- out$carc
## Calculate p det | each cue type at quadtrature distances
pdet.allcues <- h.fun.v(xx = rep(carc$roaddist, each = length(allcues[1:3])), cc = rep(allcues[1:3], nrow(carc)),
sig.v = sig.v, sig.m = sig.m, sig25 = sig25, d.shape = d.shape)
pdet.allcues <- matrix(pdet.allcues, nr = length(allcues[1:3]), nc = nrow(carc))
## calculate p det | given trip day (using camera trap p(cues | trip day)
p.margbytrip <- cue.trips %*% pdet.allcues
## p.margbytrip.vec <- as.vector(p.margbytrip)
nr <- btrack + 1
nc <- nrow(carc)
ctripmat <- cdr.output
######################################################################
## Part 1
######################################################################
## Calculate [t] given road effort: probability of detection on
## trip * p of und on all previous days carcass existed
p.undmat <- matrix(1, nrow = nr, ncol = nc)
## for each possible age of the carcass (0,btrack)
for(ii in 1:nr)
{
## take the probability of undetection on all previous days
for(jj in 1:ii)
{
p.undmat[ii,] <- p.undmat[ii,] * (1-p.margbytrip[jj,])^ctripmat[,ii-jj+1]
}
}
## prob of cue given t
p.cue <- cue.trips[,match(carc$cue, allcues[1:3])]
## [d] for each day
d.pdf <- out$d.pdf
ind.mat <- matrix(rep(carc$nday, each = nr) - rep(0:btrack, nc), nrow = nr, ncol = nc)
dps <- matrix(d.pdf[match(ind.mat, d.pdf$date), "p"], nr, nc)
## [d][det | cue seen, t, & undetection <t]
pdets.give.td <- p.undmat * p.cue * dps # don't need pdet.givecue here because its the same for all trips
## now we take colsums to give the probability of detecting a
## carcass with this cue on day dd over all carcasses (where we
## ignore [rr] since we can just multiply by it at the end
norm <- matrix(rep(colSums(pdets.give.td), each = nr), nr, nc)
p.t <- pdets.give.td / norm #note [d] is already in [t] now, so don't do it again later
######################################################################
## Part 2
######################################################################
## Now calculate the probability of detecting a carcass given its
## rr, dd, yy for each trip and for each possible days old of the
## carcass. Select the future btrack effort from the ddrr matrix
## that matches to the btrack days behind each carcass
ddrr <- ddrr.output$ddrr
tripmat <- ddrr.output$tripmat
ddrr.str <- paste(ddrr$rr, ddrr$dd) #for matching to n.in.eff below
## match ddrr.for and tr.for rows to corresponding rr-dd from carc
carc.str <- paste(rep(carc$roadwhich, each = nr), as.vector(ind.mat))
matcher <- match(carc.str, ddrr.str)
ddrr <- ddrr[matcher,]
tripmat <- tripmat[matcher,]
## initialize gdrs (row is for each dd-rr combo, col is for subdivs)
gdrs <- rep(0, nrow(ddrr))
left.trunc <- rep(0, nrow(ddrr))
for(ii in 1:ncol(tripmat)) # -1 because last trip cannot be counted as an undetection (must be a detection)
{
## if there are still trips for that dd-rr combo
is.trip <- ddrr$numtrips >= ii
## which trips are they (classified by t_i) but we add + 1 to
## allow us to index the t=0 trips as the first row of the
## p.margybytrip matrix
which.trips <- tripmat[is.trip,ii] + 1
## the probability of detection is the accumulated probability
## of detection + (1-the accumulated probability of
## detection)*(the marginal probability of detection on the
## next trip classified by t)
trip.carc.ind <- cbind(which.trips, rep(1:nc, each = nr)[is.trip])
gdrs[is.trip] <- gdrs[is.trip] + (1-gdrs[is.trip]) * p.margbytrip[trip.carc.ind]
## Need to left truncate effort outside time window. To do
## this have a separate matrix that will save a snapshot of
## gdrs at the last trip before d.min (the cumulative
## probability of having detected a carcass between d.min)
## which will then be subtracted from gdrs at the end.
befores <- as.numeric(ddrr$dd[is.trip]) + tripmat[is.trip,ii] < out$d.min #trips being considered are before
if(ii<ncol(tripmat)) #if not at the max numtrips yet see if the next trip is after d.min
{
next.after <- as.numeric(ddrr$dd[is.trip]) + tripmat[is.trip,ii + 1] >= out$d.min #& it is the last trip before d.min
}else{ #if at max numtrips, then nextafter is TRUE because we want to subtract all previous prob
next.after <- TRUE # this way, if all trips were before d.min, left.trunc becomes the full marg prob
}
next.after[is.na(next.after)] <- TRUE
left.trunc[is.trip][befores & next.after] <- gdrs[is.trip][befores & next.after]
}
## subtract off probability accumulated before d.min
gdrs <- gdrs - left.trunc
## re-order so it matches the p.t dimensions
gdrs.arr <- matrix(gdrs, nr, nc)
## multiply by p.t to collapse across the nr (potential days since death) dimension
gdrs.t <- 1 /gdrs.arr * p.t
gdrs.t[is.na(gdrs.t)] <- 0
## now have probability of detecting observed carcasses given dd, rr, yy
carc.prob <- 1 / colSums(gdrs.t) # effective carcasses
if(late.br) browser()
return(carc.prob)
# sum(p.t / grds.arr )
}
## Calculate denominator
g.dk <- function(ddrr.output, # output of ddrr
out, #
only.obs = FALSE, # modify to calculate p of det given it could have been detected (i.e. within range of seff)
yys = yy.seq, # quadrature subdivisions
sig.v, sig.m, sig25, d.shape,
gamma.y = F, temp.gamm, max.dist, cue.trips,
verbose = F, browse = F)
{
if(browse) browser()
if(verbose) print(list(sig.v,sig.m,sig25,d.shape))
pdet.allcues <- h.fun.v(xx = rep(yys, each = length(allcues[1:3])), cc = rep(allcues[1:3], length(yys)),
sig.v = sig.v, sig.m = sig.m, sig25 = sig25, d.shape = d.shape)
pdet.allcues <- matrix(pdet.allcues, nr = length(allcues[1:3]), nc = length(yys))
## Calculate marginal probability of finding carcass for each trip type (t = 0, 1 , etc, or by time later on)
pmarg.bytrip <- cue.trips %*% pdet.allcues
ddrr <- ddrr.output$ddrr
tripmat <- ddrr.output$tripmat
## initialize gdrs (row is for each dd-rr combo, col is for subdivs)
gdrs <- matrix(0, nr = nrow(ddrr), ncol = length(yys))
## initialize left.trunc matrix which will let us subtract off
## probability accumulated from effort <d.min at the end.
left.trunc <- matrix(0, nr = nrow(ddrr), ncol = length(yys))
for(ii in 1:ncol(tripmat))
{
if(verbose) print(ii)
## if there are still trips for that dd-rr combo
is.trip <- ddrr$numtrips >= ii
## which trips are they (classified by t_i) but we add + 1 to
## allow us to index the t=0 trips as the first row of the
## p.margybytrip matrix
which.trips <- tripmat[is.trip,ii] + 1
## the probability of detection is the accumulated probability
## of detection + (1-the accumulated probability of
## detection)*(the marginal probability of detection on the
## next trip classified by t)
gdrs[is.trip,] <- gdrs[is.trip,] + (1-gdrs[is.trip,]) * pmarg.bytrip[which.trips,]
## Need to left truncate effort outside time window. To do
## this have a separate matrix that will save a snapshot of
## gdrs at the last trip before d.min (the cumulative
## probability of having detected a carcass between d.min)
## which will then be subtracted from gdrs at the end.
befores <- as.numeric(ddrr$dd[is.trip]) + tripmat[is.trip,ii] < out$d.min #trips being considered are before
if(ii<ncol(tripmat)) #if not at the max numtrips yet see if the next trip is after d.min
{
next.after <- as.numeric(ddrr$dd[is.trip]) + tripmat[is.trip,ii + 1] >= out$d.min #& it is the last trip before d.min
}else{ #if at max numtrips, then nextafter is TRUE because we want to subtract all previous prob
next.after <- TRUE # this way, if all trips were before d.min, left.trunc becomes the full marg prob
}
next.after[is.na(next.after)] <- TRUE
if(sum(is.trip)==1) #separate if statement if it is a vector not a matrix
{
left.trunc[is.trip,][befores & next.after] <- gdrs[is.trip,][befores & next.after]
}else{
left.trunc[is.trip,][befores & next.after,] <- gdrs[is.trip,][befores & next.after,]
}
}
## subtract off probability accumulated before d.min
gdrs <- gdrs - left.trunc
## multiply by [y] and sum rows so we now have sum across dy for each ddrr combo
## first calculate y.pdf using gamma or unifrm
if(gamma.y)
{
y.pdf <- d(temp.gamm)(yy.seq)
## y.pdf <- p(temp.gamm)(yy.seq + int/2) - p(temp.gamm)(yy.seq - int/2)
}else{
## y.pdf <- punif(yy.seq + int/2, 0, max.dist) - punif(yy.seq - int/2, 0, max.dist)
y.pdf <- dunif(yy.seq, 0, max.dist)
}
gdrs <- gdrs %*% y.pdf
## for each dd-rr combo, multiply by [dd][rr]
dd.p <- ddrr$dd.p
rr.p <- ddrr$rr.p
ddrr.p <- dd.p*rr.p
if(only.obs) # normalize by rr-dd in window
{
gdrs <- gdrs[ddrr$numtrips>0,]
ddrr.p <- ddrr.p[ddrr$numtrips>0]
ddrr.p <- ddrr.p / sum(ddrr.p)
}
# i can only do this because gdrs dd-rr organization matches that
# of ddrr. and where gdrs = 0, it doesn't matter that we're
# normalizing. so sum(ddrr.p) > 0 when there are trips included
# that didn't have any effort in ddrr, but many are already
# deleted since empty roads don't show up from non-factor usage of
# xtabs above
gdrs <- gdrs * ddrr.p
quadsum <- sum(gdrs)*int
}
############################################################
## 9. Nll function
nll.fun <- function(pars = c( # optimizing over pars
lsig.v = log(.8),
lsig.m = log(.3),
lsig25 = log(.2),
ld.shape = log(2)),
st.like = TRUE, # use spatiotemporally explicit form of likelihood
gamma.y = F,
max.dist,
only.obs = F,
temp.gamm, cue.trips,
out, # carc, seff, seffs, d.min, d.max, d.pdf, roads.df
ddrr.output, # output from ddrr.fun()
cdr.output, # output from carc.ddrr()
foreff.output,
show.pars = F,
lower.shape.bound = 2,
pen.scale = 8*10^4, # scale for penalty of boundary
verbose = FALSE,
timer = TRUE,
browse = FALSE)
{
if(timer) start.time <- proc.time()[3]
if(browse) browser()
if(show.pars) print(exp(pars))
# initialize negative log likelihood
nll <- 0
## add smooth penalty to ridiculous parameters
if(pars["lsig.v"] > log(1.5))
{
nll <- nll + pen.scale * (pars["lsig.v"] - log(1.5))^2
pars["lsig.v"] <- log(1.5)
}
if(pars["lsig.m"] > log(1.5))
{
nll <- nll + pen.scale * (pars["lsig.m"] - log(1.5))^2
pars["lsig.m"] <- log(1.5)
}
if(pars["lsig25"] > log(1.5))
{
nll <- nll + pen.scale * (pars["lsig25"] - log(1.5))^2
pars["lsig25"] <- log(1.5)
}
if(pars["ld.shape"] > log(5))
{
nll <- nll + pen.scale * (pars["ld.shape"] - log(5))^2
pars["ld.shape"] <- log(5)
}
if(pars["ld.shape"] < log(lower.shape.bound))
{
nll <- nll + pen.scale * (pars["ld.shape"] - log(lower.shape.bound))^2
pars["ld.shape"] <- log(lower.shape.bound)
}
indiv.carc.L <- g.fun(out = out, cdr.output = cdr.output, foreff.output = foreff.output,
sig.v = exp(pars["lsig.v"]), sig.m = exp(pars["lsig.m"]), sig25 = exp(pars["lsig25"]),
d.shape = exp(pars["ld.shape"]),
gamma.y = gamma.y, temp.gamm = temp.gamm, cue.trips = cue.trips,
max.dist = max.dist, st.like = st.like,
browse = F)
if(st.like)
{
## The denominator of the likelihood (proportion of carcasses detected)
quadsum <- g.dk(ddrr.output, out, yys = yy.seq,
sig.v = exp(pars["lsig.v"]), sig.m = exp(pars["lsig.m"]), sig25 = exp(pars["lsig25"]),
d.shape = exp(pars["ld.shape"]),
gamma.y = gamma.y, temp.gamm = temp.gamm, max.dist = max.dist, only.obs = only.obs,
cue.trips = cue.trips,
browse = F)
## The numerator of the likelihood: comes from the carcass data
nll <- nll + nrow(out$carc) * log(quadsum) - sum(log(indiv.carc.L))
}else{
denoms <- pr.fun(out = out, cdr.output = cdr.output,
ddrr.output = ddrr.output,
sig.v = exp(pars["lsig.v"]), sig.m = exp(pars["lsig.m"]), sig25 = exp(pars["lsig25"]),
d.shape = exp(pars["ld.shape"]), yys = yy.seq,
gamma.y = gamma.y, temp.gamm = temp.gamm, max.dist = max.dist,
cue.trips = cue.trips,
browse = F)
nll <- nll + sum(log(denoms)) - sum(log(indiv.carc.L))
}
if(timer) end.time <- proc.time()[3]
if(timer) print(paste("nll calc took", end.time - start.time, "s"))
return(nll)
}
## ## Vectorize nll over parameters if interested in looking at contours
## nll.w <- function(x,y, pars,...)
## {
## ## pars["lsig.v"] <- log(x)
## pars["ld.shape"] <- log(y)
## nll.fun(pars, out, ddrr.output = dr.out, cdr.output = cdr.out, show.pars = F, verbose = F, timer = F, browse = F)
## }
## nll.v <- Vectorize(nll.w, vectorize.args=c("x","y"))
## xs <- seq(.2,1,l=10)
## ys <- seq(.5,9,l=10)
## contour(outer(xs,ys,nll.v, pars = init.true))
## Simulate carcass data given real effort data in a given time window, rrs, etc
data.sim <- function(rrs = 192,
only.in.eff = TRUE,
ddrr.str = NULL,
d.min = min(seff$nday) + 5,
d.max = min(seff$nday) + 50,
set.dist = F, # fix dist for troubleshooting
to.set = .1,
set.dd = F,
rand.dd.p = F, # add temporal variability in carcass distribution
rand.rr.p = F, # add spatial variability in carcass distribution (note no s-t variability at this point)
wrong.rr.p = F, # use uniform rr.p to fit heterogenous rr.p
dd.set = NULL,
get.eff=F,
sim.vals = c(sig.v = NULL, sig.m = NULL, sig25 = NULL, d.shape = NULL),
max.dist, btrack = 5,
gamma.y = F, temp.gamm, cue.trips,
N = 300, browse = F)
{
if(browse) browser()
## Load road length and calculate [r] proportional to road length (for now)
roads.df <- roads.df.all[roads.df.all$rdID %in% rrs,]
roads.df$p <- roads.df$LENGTH / sum(roads.df$LENGTH)
seff.int <- seff
seff.int <- seff.int[seff.int$Road %in% rrs,]
seff.int <- seff.int[seff.int$nday <= d.max & seff.int$nday >= (d.min- btrack),]
if(rand.rr.p)
{
## multiply by gamm distr scaling factor (retain original 1/length to preserve that longer roads still cover more area)
roads.df$p <- roads.df$p * rgamma(nrow(roads.df), shape = 1, scale = .5) # aggregated carcass distr in time
roads.df$p <- roads.df$p / sum(roads.df$p)
## roads.df$p[1] <- .99
## roads.df$p[-1] <- rep(.01, nrow(roads.df)-1)
## roads.df$p <- roads.df$p / sum(roads.df$p)
}
dseq <- (d.min-btrack):d.max
d.pdf <- data.frame(date = dseq, p = 1/length(dseq))
d.pdf$p[dseq<d.min] <- 0
# d.pdf$p[(d.max - dseq)<6 ] <- 0
d.pdf$p <- d.pdf$p / sum(d.pdf$p)
if(rand.dd.p)
{
d.pdf$p <- rgamma(length(dseq), shape = 1, scale = .5) # aggregated carcass distr in time
d.pdf$p[dseq<d.min] <- 0
d.pdf$p <- d.pdf$p / sum(d.pdf$p)
}
## d.pdf <- rbind(data.frame(date = (min(dseq)-btrack):(min(dseq)-1), p = 0),d.pdf)
## Set up matrix to use for runif(1) easily so that if x < first val
## => avian, etc
## temp.frame <- day.frame[1:(btrack+1),allcues[1:3]]
temp.frame <- cue.trips
crand.frame <- cue.trips
crand.frame[,2] <- rowSums(temp.frame[,1:2])
crand.frame[,3] <- rowSums(temp.frame)
crand.frame <- data.frame(day = 0:btrack, crand.frame)
## Initialize the covariates
if(gamma.y)
{ # simulate from truncated gamma using library(distr)
yy <- r(temp.gamm)(N)
}else{ # uniform dist
yy <- runif(N, 0, max.dist)
}
if(!only.in.eff)
{
dd <- rep(dseq, as.vector(rmultinom(1, N, prob = d.pdf$p))) # floor(runif(N, min(dseq), max(dseq)+1))
rr <- rep(roads.df$rdID, as.vector(rmultinom(1,N, prob = roads.df$p)))
}else{
## if only generating carcasses in the period with effort
dds.rep <- d.pdf[rep(1:nrow(d.pdf), each = nrow(roads.df)),]
rrs.rep <- roads.df[rep(1:nrow(roads.df), nrow(d.pdf)),]
rrs.rep <- rrs.rep[,5:6]
ddrr.dist <- cbind(dds.rep, rrs.rep)
ddrr.dist$drp <- ddrr.dist[,2]*ddrr.dist[,3]
ddrr.all <- paste(ddrr.dist[,"rdID"], ddrr.dist[,"date"])
in.eff <- ddrr.all %in% ddrr.str
ddrr.dist <- ddrr.dist[in.eff,]
ddrr.dist$drp <- ddrr.dist$drp / sum(ddrr.dist$drp)
indices <- rep(1:nrow(ddrr.dist), as.vector(rmultinom(1, N, prob = ddrr.dist$drp)))
dd <- ddrr.dist$date[indices]
rr <- ddrr.dist$rdID[indices]
}
#if(set.dist) yy <- rep(to.set, N)
#if(set.dd) dd <- rep(dd.set, N)
## if analyzing with the wrong rr.p, reset to based on length
if(wrong.rr.p) roads.df$p <- roads.df$LENGTH / sum(roads.df$LENGTH)
det <- rep(FALSE,N) #if detected
cc <- rep(NA,N)
ll <- rep(NA,N)
tt <- rep(NA,N)
driver <- factor(rep(NA,N), levels = levels(seff.int$Driver))
tin <- as.POSIXct(rep(NA,N))
tout <- as.POSIXct(rep(NA,N))
tms <- rep(NA,N)
obs <- rep(NA,N)
dateTime <- as.POSIXct(rep(NA,N) )
tod <- rep(NA,N)
## loop through carcasses
for(ii in 1:N)
{ # find seff.int in window of dd
day.diff <- seff.int$nday - dd[ii]
in.window <- day.diff >= 0 & day.diff <= btrack
in.window <- in.window & seff.int$Road == rr[ii]