-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolitary_bee_analysis.R
2069 lines (1774 loc) · 92.2 KB
/
solitary_bee_analysis.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
#ANALYSIS FOR PAUL, INVESTIGATING SOLITARY BEE - CANOLA OVERLAP, AND HOW THIS INFLUENCES YEAR-TO-YEAR PERSISTANCE
# Load everything ----------------------------------------------------------
library(ggplot2)
library(dplyr)
library(tidyr)
library(beepr)
#ggplot theme
prestheme <- theme(legend.position='right',
legend.text=element_text(size=15),
axis.text=element_text(size=15),
axis.title=element_text(size=20),
title=element_text(size=20),
panel.grid.major=element_line(size=0.5,colour='black',linetype='dotted'),
panel.grid.minor=element_blank(),
panel.border=element_rect(size=1,colour='black'),
strip.text=element_text(size=15))
theme_set(theme_bw()+prestheme) #Sets graph theme to B/Ws + prestheme
rm(prestheme)
setwd('~/Projects/UofC/wildbee_canola_project')
#load('arthropod.Rdata') #Has 793 more records; not sure why...
load('arthropodJoinLandscape.Rdata')
load('trap.Rdata')
#load('flower.Rdata') #Precise flower data doesn't exist for 2015
trap=df3
rm(df3)
year2year <- mutate(df2,year=paste0('y',year)) %>% #Traps that were used in both years
group_by(year,BLID) %>%
summarize(count=n()) %>%
spread(year,count,fill=NA) %>%
filter(!is.na(y2015)&!is.na(y2016)) %>%
select(BLID) %>%
.$BLID
#Known solitary cleptoparasites:
parasitoids <- c('Coelioxys','Epeolus','Holcopasites','Melecta','Nomada','Sphecodes','Stelis','Triepeolus')
#Agricultural bees
agricultural <- c('Apis mellifera','Megachile rotundata')
df2 <- df2 %>%
mutate_at(vars(family:species),as.character) %>% #Convert to character
mutate_at(vars(family:species),list(~sub(' ','',.))) %>% #Strips white space
mutate_at(vars(family:species),list(~sub('Megachildae','Megachilidae',.))) %>% #Fixes spelling
mutate_at(vars(family:species),list(~sub('Colleditae','Colletidae',.))) %>%
mutate_at(vars(family:species),list(~sub('Agopostemon','Agapostemon',.))) %>%
filter(genus!='Bombus') %>% #Get rid of bumblebees
mutate_at(vars(family:species),list(~sub('variolosus','variolosa',.))) %>% #NOT SURE IF THESE ARE 2 SEPARATE SPP.
mutate_at(vars(family:species),factor) %>% #Convert to factor
select(-length_mm,-caste,-intertegular_mm) %>%
filter(BLID %in% year2year)
bees <- select(df2,BLID:latTrap) %>% #Bees/trapping data
unite(genSpp,genus,species,sep=' ',remove=F) %>%
mutate(parasitoid=ifelse(genus %in% parasitoids,T,F)) %>%
mutate(agricultural=ifelse(genSpp %in% agricultural,T,F)) %>%
#Aggregates dates
mutate(startDate=paste(year,startJulian,sep='-'),endDate=paste(year,endJulian,sep='-')) %>%
mutate(startDate=as.POSIXct(startDate,format='%Y-%j'),endDate=as.POSIXct(endDate,format='%Y-%j')) %>%
select(-startMonth,-startJulian,-endMonth,-endJulian)
landscape <- select(df2,BLID,lcRuralDeveloped_100m:aafcOtherCrop_2016_4000m) %>% #Landscape data
distinct()
trap <- trap %>%
filter(BLID %in% year2year) %>%
mutate(year=startYear) %>%
select(-startNESWPhoto_DSC,-endNESWPhoto_DSC,-lonTrap,-latTrap,-elevTrap) %>%
select(-startHour,-startMinute,-endHour,-endMinute) %>%
unite(startDate,startYear:startDay,sep='-') %>%
unite(endDate,endYear:endDay,sep='-') %>%
mutate(startDate=as.POSIXct(startDate,format='%Y-%m-%d'),endDate=as.POSIXct(endDate,format='%Y-%m-%d'))
text2perc<-function(intext){
if(is.na(intext)|intext=='NA'|intext==''){
return(NA)
}
if(grepl(',',intext)|grepl('-',intext)) { #If there is a comma or dash
intext=strsplit(unlist(strsplit(intext,',')),'-') #Split into pieces
}
intext=lapply(intext,FUN=function(x) mean(as.numeric(x),na.rm=T))
return(mean(unlist(intext)))
}
#Fixes measurements of canola bloom %
temp2015 <- trap %>%
filter(year==2015) %>%
rename(canolaBloom=percentCanolaBloom) %>%
mutate(canolaAdjacent=as.character(canolaAdjacent),
canolaBloom=as.character(canolaBloom)) %>%
mutate(canolaAdjacent=grepl('yes',canolaAdjacent)) %>%
mutate(canolaBloom=ifelse(grepl('<',canolaBloom),2,canolaBloom)) %>%
mutate(canolaBloom=gsub('PP','',canolaBloom)) %>%
mutate(canolaBloom=gsub('NotMeasured',NA,canolaBloom)) %>%
mutate(canolaBloom=ifelse(grepl('(to [sS]eed|past bloom)',canolaBloom),0,canolaBloom)) %>%
mutate(canolaBloom=gsub('[NESW]{1,2}:','',canolaBloom)) %>%
mutate(canolaBloom=gsub(' ','',canolaBloom)) %>%
mutate(canolaBloom=ifelse(canolaBloom=='','0',canolaBloom)) %>%
rowwise() %>%
mutate(canolaBloom=text2perc(canolaBloom)) %>% #Canola perc bloom for 2015
ungroup() %>%
mutate(canolaBloom=(100/max(canolaBloom))*canolaBloom) %>% #Scales by maximum measured bloom (makes max==100%)
select(BTID,BLID,pass,replicate,startDate:endDate,year,canolaBloom)
temp2016 <- trap %>%
filter(year==2016) %>%
filter(pass!=0) %>%
select(-canolaAdjacent:-deployedNotes,-locationType) %>%
select(-adjMowed,-oppMowed) %>%
unite(adjCrop,adjCrop,adjCropBloom) %>%
unite(oppCrop,oppCrop,oppCropBloom) %>%
gather('crop','bloom',adjCrop:oppCrop) %>%
separate(bloom,c('croptype','perc'),sep='_') %>%
mutate(perc=ifelse(croptype!='canola',NA,perc)) %>%
rowwise() %>%
mutate(perc=text2perc(perc)) %>%
unite(croptype,croptype,perc) %>%
spread(crop,croptype) %>%
separate(adjCrop,c('adjCrop','adjPerc'),sep='_') %>%
separate(oppCrop,c('oppCrop','oppPerc'),sep='_') %>%
mutate(adjPerc=as.numeric(adjPerc),oppPerc=as.numeric(oppPerc)) %>%
rowwise() %>%
mutate(canolaBloom=mean(c(adjPerc,oppPerc),na.rm=T)) %>%
mutate(canolaBloom=ifelse(adjCrop=='canola'||oppCrop=='canola',canolaBloom,0)) %>%
mutate(canolaBloom=ifelse(is.nan(canolaBloom),NA,canolaBloom)) %>%
select(BTID,BLID,pass,replicate,startDate:endDate,year,canolaBloom)
trap <- bind_rows(temp2015,temp2016) %>% #Puts 2015 and 2016 trap data together
mutate(traptime=as.numeric(difftime(endDate,startDate,units='days'))) %>%
mutate(startDate=as.numeric(format(startDate,format='%j'))) %>%
mutate(endDate=as.numeric(format(endDate,format='%j'))) %>%
rowwise() %>%
mutate(midDate=mean(c(startDate,endDate)))
rm(temp2015,temp2016)
#Landscape variables of interest (percent cover), at radii of 100,250,500m
landscape <- landscape %>%
select(BLID,contains('Canola',ignore.case=T),contains('Forest'),
contains('Shrubland'),contains('Grassland'),contains('Pasture')) %>%
# select(BLID,contains('100m'),contains('250m'),contains('500m')) %>%
select(BLID,contains('2015'),contains('2016')) %>%
gather('class','area',-1) %>%
separate(class,c('class','year','radius')) %>%
mutate(class=gsub('aafc','',class),radius=gsub('m','',radius)) %>%
spread(class,area) %>%
mutate(Seminatural=Forest+NativeGrassland+Shrubland) %>% #All "seminatural" land
rename(Pasture=PastureForageCrop) %>% #Hay crops
# select(-Forest,-NativeGrassland,-Shrubland) %>%
mutate(totalArea=(pi*as.numeric(radius)^2)) %>%
mutate_at(vars(Canola:Seminatural),list(~./totalArea)) %>%
select(-totalArea) %>%
mutate_at(vars(Canola:Seminatural),list(~round(.,4))) %>%
gather('class','proportion',Canola:Seminatural) %>%
mutate(proportion=ifelse(proportion>1,1,proportion)) %>%
unite(class,class,radius) %>%
spread(class,proportion)
# #Checking to make sure that traps with 0% canola recorded actually had 0% canola around them
# #Answer: not really. There are occasional fields that have canola near them but the bloom wasn't recorded. Probably should do some kind of overall estimate, or random effect.
# landscape %>%
# select(-contains('Pasture')) %>%
# select(-contains('Seminatural')) %>%
# unite(siteYear,BLID:year) %>%
# left_join(select(trap,BLID,year,canolaBloom) %>%
# unite(siteYear,BLID:year) %>%
# group_by(siteYear) %>%
# summarize(sumPercBloom=as.numeric(sum(canolaBloom,na.rm=T)>0)),by='siteYear') %>%
# gather('Radius','Measured',contains('Canola')) %>%
# mutate(Radius=paste('Radius',gsub('Canola_','',Radius),'m')) %>%
# separate(siteYear,c('site','year'),sep='_') %>%
# ggplot(aes(Measured,sumPercBloom,col=year))+geom_point(position=position_jitter(width=0.01,height=0.01))+facet_wrap(~Radius,ncol=1)+
# geom_smooth(method='glm',method.args=list(family='binomial'))+
# labs(y='%Bloom Measured?',x='Actual amount of canola in landscape')
# #Canola abundance with pass. Looks like bloom may have been missed at:
# #12000, 12754, 14025, 15208, 20001 in 2015 - first observation only
# #10781, 2nd obs?
# #14376 in 2016 - 1st and 3rd obs.
# ggplot(trap,aes(midDate,canolaBloom,col=factor(year)))+
# geom_line()+geom_point()+
# facet_wrap(~BLID)+
# scale_colour_manual(values=c('red','blue'))+labs(col='Year')+
# theme(axis.text=element_text(size=7),strip.text=element_text(size=10))
#Sets "suspicious" 0 bloom values to NA
trap[trap$BLID==12000 & trap$year==2015 & trap$pass==1,'canolaBloom'] <- NA
trap[trap$BLID==12754 & trap$year==2015 & trap$pass==1,'canolaBloom'] <- NA
trap[trap$BLID==14025 & trap$year==2015 & trap$pass==1,'canolaBloom'] <- NA
trap[trap$BLID==15208 & trap$year==2015 & trap$pass==1,'canolaBloom'] <- NA
trap[trap$BLID==20001 & trap$year==2015 & trap$pass==1,'canolaBloom'] <- NA
trap[trap$BLID==10781 & trap$year==2015 & trap$pass==2,'canolaBloom'] <- NA
trap[trap$BLID==14376 & trap$year==2016 & (trap$pass==1|trap$pass==3),'canolaBloom'] <- NA
#Get distance matrix from trap latitude and longitude
library(sp)
library(maptools)
library(rgdal)
library(rgeos)
trapCoords <- df2 %>% select(BLID:lat) %>% group_by(BLID) %>% #Get lat and lon
summarize(lon=first(lon),lat=first(lat)) %>%
data.frame()
coordinates(trapCoords)=~lon+lat
proj <- CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0") #Initial projection (latlon) to set
proj4string(trapCoords) <- proj #Set projection
newproj <- CRS("+init=epsg:32612") #CRS for UTM 12
trapCoords <- spTransform(trapCoords,newproj) #Transform to UTM 12
# writeOGR(trapCoords,"C:\\Users\\Samuel\\Documents\\Shapefiles\\Field map\\BlueVaneTrap Locations","BVTraps_2015_2016_Continuous",driver="ESRI Shapefile") #Writes trap coordinates to shapefile directory
distMat <- gDistance(trapCoords,byid=T) #Get distance matrix between sites
colnames(distMat) <- rownames(distMat) <- trapCoords$BLID #Rename rows and columns
distMat <- distMat/10000 #Scales distances to 10s of kms
# #Detach spatial stats packages
# detach("package:rgdal", unload=TRUE)
# detach("package:sp", unload=TRUE)
# detach("package:maptools", unload=TRUE)
# detach("package:rgeos", unload=TRUE)
#Convenience functions
logit <- function(x){
return(log(x/(1-x)))
}
invLogit <- function(x){
i <- exp(x)/(1+exp(x))
i[is.nan(i)] <- 1 #If x is large enough, becomes Inf/Inf = NaN, but Lim(invLogit) x->Inf = 1
return(i)
}
#Posterior predictive plots
PPplots <- function(resid,predResid,actual,pred,main=NULL){
par(mfrow=c(2,1))
plot(resid~predResid,ylab='Sum actual residuals',xlab='Sum simulated residuals',main=main)
x <- sum(resid<predResid)/length(resid)
legend('topleft',paste('p =',round(min(x,1-x),3)))
abline(0,1,col='red') #PP plot
plot(actual~pred, #Predicted vs Actual
xlab=paste('Predicted',main),ylab=paste('Actual',main))
abline(0,1,col='red')
abline(lm(actual~pred),col='red',lty=2)
par(mfrow=c(1,1))
}
#Faster pair plots, using extracted lists
fastPairs <- function(l){ #List l
pairs(l,gap=0,lower.panel=function(x,y){
par(usr=c(0,1,0,1))
text(0.5, 0.5, round(cor(x,y),2), cex = 1 * exp(abs(cor(x,y))))})
}
#Fix names of morphospecies (if subgenus listed)
#eg. "Lasioglossum dialictus_sp17" -> "Lasioglossum (Dialictus) spp.17"
#eg. "Lasioglossum_dialictus_sp17" -> "Lasioglossum (Dialictus) spp.17"
fixNames <- function(a){
if(length(a)>1) stop('Name not specified correctly')
if(!grepl('_',a)) stop('No underscores found')
#Extract substrings
#If more than 1 underscore, use underscore as splitting character rather than space
splitchar <- ifelse(nchar(a)-nchar(gsub('_','',a))>1,'_',' ') #Splitting character
pt1 <- strsplit(a,splitchar)[[1]][1] #Genus name
pt2 <- strsplit(strsplit(a,splitchar)[[1]][2],'_')[[1]][1] #Subgenus name (non-capitalized)
pt3 <- strsplit(a,'_')[[1]][length(strsplit(a,'_')[[1]])] #Spp + Number
pt2 <- paste0(toupper(substr(pt2,0,1)),substr(pt2,2,nchar(pt2))) #Capitalize subgenus name
pt3 <- paste0('spp.',substr(pt3,3,nchar(pt3))) #Add spp. to pt3
return(paste0(pt1,' (',pt2,') ',pt3)) #Paste parts 1-3 together
}
#Posterior p-values (percent overlapping zero)
postP <- function(a){
upr <- sum(a>0)/length(a)
lwr <- sum(a<0)/length(a)
both <- c(upr,lwr); names(both) <- c('upr','lwr')
return(both)
}
# Basic abundance plots ---------------------------------------------------
#Summary of species
p1 <- group_by(bees,genSpp) %>%
filter(agricultural==F) %>% #Filter agricultural
summarize(number=n(),parasitoid=first(parasitoid)) %>%
filter(number>5) %>% arrange(desc(number)) %>%
rowwise() %>%
mutate(genSpp=ifelse(grepl('_',genSpp),fixNames(genSpp),genSpp)) %>%
mutate(genSpp=factor(genSpp,levels=.$genSpp)) %>% ungroup() %>%
arrange(genSpp) %>%
mutate(parasitoid=factor(parasitoid,labels=c('Non-parasitic','Nest parasite'))) %>%
ggplot(aes(genSpp,number,fill=parasitoid))+geom_col()+
theme(axis.text.x=element_text(angle=90,vjust=0.25,size=7))+
labs(x='Species',y='Count',fill='Cleptoparasite')+scale_fill_manual(values=c('black','red'))+
# scale_y_sqrt()+
theme(panel.grid.major=element_line(size=0.5,colour='grey90',linetype='solid'),
panel.grid.minor=element_blank(),axis.text.x=element_text(hjust=1))+
theme(legend.position=c(0.8,0.9),legend.background=element_rect(fill='white',colour='black',linetype='solid'),
legend.title=element_blank(),legend.text=element_text(size=12))
ggsave('./Figures/countsSpp.png',p1,width=10,height=6)
#Broken down by family
group_by(bees,genSpp) %>%
filter(agricultural==F) %>% #Filter agricultural
summarize(number=n(),parasitoid=first(parasitoid),family=first(family)) %>%
filter(number>5) %>%
arrange(desc(number)) %>%
mutate(genSpp=factor(genSpp,levels=.$genSpp)) %>%
ggplot(aes(genSpp,number,fill=parasitoid))+geom_col()+
theme(axis.text.x=element_text(angle=90,vjust=0.25,size=7),
strip.text=element_text(size=7))+
labs(x='Spp',y='Count')+scale_fill_manual(values=c('black','red'))+
facet_wrap(~family,scales='free_x',nrow=1)
#Summary of genera
group_by(bees,genus) %>%
filter(agricultural==F) %>% #Filter agricultural
summarize(number=n(),parasitoid=first(parasitoid)) %>%
#filter(number>5) %>%
arrange(desc(number)) %>%
mutate(genus=factor(genus,levels=.$genus)) %>%
ggplot(aes(genus,number,fill=parasitoid))+geom_col()+
theme(axis.text.x=element_text(angle=90,vjust=0.25,size=7))+
labs(x='Genus',y='Count')+scale_fill_manual(values=c('black','red'))
#Genus counts broken down by family & year
p1 <- group_by(bees,genus,year) %>%
filter(agricultural==F) %>% #Filter agricultural
summarize(number=n(),parasitoid=first(parasitoid),family=first(family)) %>%
ungroup() %>% arrange(desc(number)) %>%
mutate(parasitoid=factor(parasitoid,labels=c('Non-parasitic','Nest parasite'))) %>%
mutate(genus=factor(genus,levels=unique(genus))) %>%
ggplot(aes(genus,number,fill=parasitoid))+geom_col()+
theme(axis.text.x=element_text(angle=90,vjust=0.25,size=7))+
labs(x='Genus',y='Count',fill='Cleptoparasite')+scale_fill_manual(values=c('black','red'))+
facet_grid(year~family,scales='free_x')+
theme(panel.grid.major=element_line(size=0.5,colour='grey90',linetype='solid'),
panel.grid.minor=element_blank(),axis.text.x=element_text(hjust=1,size=10))+
theme(legend.position=c(0.9,0.9),legend.background=element_rect(fill='white',colour='black',linetype='solid'),
legend.title=element_blank(),legend.text=element_text(size=12))
ggsave('./Figures/countsFamilyYear.png',p1,width=10,height=8)
#Summary statistics
#Catches per week - lower in 2016, but large SD
bees %>% filter(!parasitoid,!agricultural) %>%
group_by(BLID,BTID,year) %>%
summarize(count=n(),weeks=first(deployedHours)/(24*7)) %>%
ungroup() %>% select(-BTID) %>% group_by(BLID,year) %>%
summarize(catchRate=sum(count)/sum(weeks)) %>%
# group_by(year) %>% summarize(meanCatch=mean(catchRate),sdCatch=sd(catchRate),seCatch=sdCatch/sqrt(n()))
mutate(year=paste0('y',year)) %>% spread(year,catchRate) %>%
mutate(diff=y2016-y2015) %>% #with(.,{qqnorm(diff);qqline(diff)}) #Looks normal-ish
with(.,t.test(diff))
# ggplot(aes(y2015,y2016))+geom_point()+
# geom_abline(intercept=0,slope=1)+geom_smooth(method='lm')
bees %>% filter(!parasitoid,!agricultural) %>%
group_by(BLID,BTID,year) %>%
summarize(count=n(),weeks=first(deployedHours)/(24*7),catchRate=count/weeks) %>%
ungroup() %>% select(-BTID,-count,-weeks) %>% mutate(year=paste0('y',year))
# Other plots -------------------------------------------------------------
#Shows year-to-year transitions of canola (lots), pastures (not a lot), and SNL (not a lot)
landscape %>%
#select(BLID,year,contains('Canola')) %>%
gather('TypeRadius','Proportion',contains('_')) %>%
mutate(year=paste0('y',year)) %>%
spread(year,Proportion) %>%
separate(TypeRadius,c('Type','Radius'),convert=T) %>%
ggplot(aes(y2015,y2016))+geom_jitter()+geom_smooth(method='lm',se=F)+facet_wrap(Type~Radius)+
geom_abline(intercept=0,slope=1,linetype='dashed')+labs(y='2016',x='2015')+
theme(axis.text=element_text(size=10))
trap %>% #canolaBloom on centered endDate
filter(BLID %in% unique(trap$BLID)[with(trap,tapply(canolaBloom,BLID,mean,na.rm=T))>0]) %>%
ggplot(aes(endDate-206,canolaBloom,group=BLID))+geom_line()+facet_wrap(~year)+
theme(axis.text=element_text(size=7),strip.text=element_text(size=10))+
labs(x='Centered bloom date',y='Percent Bloom')
# Hypotheses --------------------------------------------------------------
#Spp that use canola will see a boost in populations in the year after. This will be dependent on:
# a) Overlap in flight time and canola bloom period, as well as population in that year
# b) Body size/tongue length? (Kind of Jen's question...) - likely related to usage of canola
#Specific tests:
#Standardized overlap (area under curve using similar flight time)
# Test with top 4 spp caught in year-to-year traps -------------------------------------------
#Names of top4 wild spp
top4=filter(bees,BLID %in% year2year,!agricultural) %>%
mutate(year=paste0('y',year)) %>%
group_by(year,genSpp) %>%
summarize(number=n()) %>%
spread(year,number,fill=0) %>%
mutate(notZero=(y2015>0&y2016>0),diff=abs(y2015-y2016),total=y2015+y2016) %>%
filter(notZero) %>% #Filter years with zero in one year
filter((diff/total)<0.5) %>% #Filter sp where magnitude of yearly difference is less than 50% of total count
arrange(desc(total)) %>%
top_n(4,total) %>%
.$genSpp
#Occurance data for top 4 bees
top4bees=filter(bees,BLID %in% year2year) %>%
filter(genSpp %in% top4)
#Trapping occurance data (start and end of passes)
passes=trap %>%
filter(BLID %in% year2year) %>%
select(BLID,pass,year,startDate,midDate,endDate,canolaBloom) %>%
group_by(BLID,pass,year) %>%
summarize(start=first(startDate),midDate=first(midDate),end=first(endDate)) %>%
unite(ID,BLID:year,remove=F) %>%
arrange(year,BLID,pass)
temp=group_by(top4bees,genSpp,BLID,pass,year) %>% #Abundance by date & trap
summarize(count=n()) %>%
unite(ID,BLID:year) %>%
spread(genSpp,count) %>%
full_join(passes,by='ID') %>%
gather('genSpp','count',2:5) %>%
mutate(count=ifelse(is.na(count),0,count)) %>% #Changes NAs to zeros
select(-ID) %>%
mutate(BLID=factor(BLID)) %>%
arrange(genSpp,year,BLID,pass)
#Absence/presence plot
temp %>%
mutate(status=ifelse(count==0,'Absent','Present')) %>%
mutate(status=factor(status,levels=c('Present','Absent'))) %>%
ggplot(aes(midDate,BLID))+
geom_point(aes(fill=status),shape=21)+
theme(axis.text.y=element_text(size=8))+
geom_point(aes(start,BLID,size=NULL),col='black',shape=124)+
geom_point(aes(end,BLID,size=NULL),col='black',shape=124)+
facet_grid(year~genSpp)+
scale_fill_manual(values=c('black','white')) +
labs(shape='Empty',x='Day of year',fill='Status')
#Abundance plot
temp %>%
mutate(status=ifelse(count==0,'Absent','Present')) %>%
mutate(status=factor(status,levels=c('Present','Absent'))) %>%
ggplot(aes(midDate,BLID))+
geom_point(aes(fill=status,size=(count/(end-start))),shape=21)+
theme(axis.text.y=element_text(size=8))+
geom_point(aes(start,BLID,size=NULL),col='black',shape=124,show.legend=F)+
geom_point(aes(end,BLID,size=NULL),col='black',shape=124,show.legend=F)+
facet_grid(year~genSpp)+
scale_fill_manual(values=c('black','white')) +
labs(shape='Empty',x='Day of year',fill='Status',size='Count')
group_by(top4bees,genSpp,year,midJulian) %>% #Abundance by date and year
summarize(count=n()) %>%
ggplot(aes(midJulian,count))+geom_point()+
geom_smooth(method='gam',formula=y~s(x),method.args=list(family='nb'))+
facet_grid(year~genSpp)
mutate(top4bees,year=paste0('y',year)) %>% #Do populations in year 2015 relate to year 2016?
group_by(genSpp,year,BLID) %>%
summarize(count=n()) %>%
spread(year,count,fill=0) %>%
filter(!is.na(y2015)&!is.na(y2016)) %>%
ggplot(aes(y2015,y2016))+geom_jitter()+geom_abline(slope=1,intercept=0)+
facet_wrap(~genSpp,scales='free')+geom_smooth(method='lm')+
#xlim(0,100)+ylim(0,100)+
labs(x='Number in 2015',y='Number in 2016')
#Weird outlier patterns...looks like 2016 was a bad year for some spp, but it might have just been because trapping was done at a different time. Should compare shortest overlapping time period.
# Single-year model of wild bees - test using JAGS ---------------
#Names of top4 wild spp
top4=filter(bees,BLID %in% year2year,!agricultural) %>%
mutate(year=paste0('y',year)) %>%
group_by(year,genSpp) %>%
summarize(number=n()) %>%
spread(year,number,fill=0) %>%
mutate(notZero=(y2015>0&y2016>0),diff=abs(y2015-y2016),total=y2015+y2016) %>%
filter(notZero) %>% #Filter years with zero in one year
filter((diff/total)<0.5) %>% #Filter sp where magnitude of yearly difference is less than 50% of total count
arrange(desc(total)) %>%
top_n(4,total) %>%
.$genSpp
#Occurance data for top 4 bees
top4bees=filter(bees,BLID %in% year2year) %>%
filter(genSpp %in% top4)
#Trapping occurance data (start and end of passes)
passes=trap %>%
select(BLID,pass,replicate,year,startDate,midDate,endDate,canolaBloom) %>%
distinct() %>%
unite(ID,BLID:year,remove=F) %>%
arrange(year,BLID,pass)
#Anthophora model from 2015 only
temp=group_by(top4bees,genSpp,BLID,pass,replicate,year) %>% #Abundance by date & trap
summarize(count=n()) %>%
unite(ID,BLID:year) %>%
spread(genSpp,count) %>%
full_join(passes,by='ID') %>%
gather('genSpp','count',2:5) %>%
mutate(count=ifelse(is.na(count),0,count)) %>% #Changes NAs to zeros
select(-ID) %>%
mutate(BLID=factor(BLID)) %>%
arrange(genSpp,year,BLID,pass) %>%
filter(year==2015,genSpp=='Anthophora terminalis')
setwd("~/Projects/UofC/wildbee_canola_project/Models")
library(coda)
library(jagsUI)
datalist=with(temp, #Data to feed into JAGS
list(
N=nrow(temp), #Number of total samples
Nsite=length(unique(BLID)), #Number of sites
count=count, #Count of bees
site=as.numeric(BLID), #site index
traplength=(endDate-startDate)/7, #offset (in weeks)
centDate=midDate-mean(midDate) #Centered midDate
)
)
#Starting values for chains (GLMM version)
start=function() list(alpha.mean=dunif(1,-10,10),
alpha.sd=dunif(1,-10,10),
beta=rnorm(1,0,1))
mod1=jags(data=datalist,inits=start,c('alpha.mean','alpha','beta','fit','fit.new'),
model.file='poissonGLMM_jags.txt',
n.chains=3,n.adapt=2000,n.iter=10000,n.burnin=1000,n.thin=10,parallel=T)
summary(mod1)
#xyplot(mod1)
#traceplot(mod1) # Many plots...
densityplot(mod1)
pp.check(mod1,'fit','fit.new') #Bad fit... actual doesn't match predicted at all
mod1fit=mod1$samples[[1]] #Results from mod1
b0=mod1fit[,'alpha.mean']
b1=mod1fit[,'beta']
centDate=-23:25
res1=data.frame(date=centDate,fit=NA,upr=NA,lwr=NA)
for(i in 1:nrow(res1)){ #Predictions
res1$fit[i]=exp(median(b0)+median(b1)*centDate[i])
res1[i,3:4]=quantile(exp(b0+b1*centDate[i]),c(0.0275,0.975))
}
ggplot(res1,aes(centDate+mean(temp$midDate),fit))+
geom_point(data=temp,aes(x=midDate,y=count*7/(endDate-startDate)))+
#geom_line(data=temp,aes(x=midDate,y=count,group=BLID))+
geom_line(col='red',size=1)+geom_ribbon(aes(ymax=upr,ymin=lwr),alpha=0.3)+
labs(x='Day of year',y='Predicted count',title='Poisson GLMM')+ylim(0,10)
#NB GLM model - takes longer, but has identical estimates, and better n.eff.
datalist=with(temp, #Data to feed into JAGS
list(
N=nrow(temp), #Number of total samples
Nsite=length(unique(BLID)), #Number of sites
count=count, #Count of bees
site=as.numeric(BLID), #site index
traplength=(endDate-startDate), #offset (in days)
centDate=midDate-mean(midDate) #Centered midDate
)
)
start=function() list(alpha.mean=rnorm(1,0,1),
alpha.sd=runif(1,0,10),
beta=rnorm(1,0,.1),
logtheta=rnorm(1,0,.1) #Dispersion
)
mod2a=jags(data=datalist,inits=start,c('alpha.mean','alpha','beta','logtheta','theta','fit','fit.new'),
model.file='nbGLMM_jags.txt',
n.chains=3,n.adapt=2000,n.iter=10000,n.burnin=1000,n.thin=10,parallel=T)
summary(mod2a)
pp.check(mod2a,'fit','fit.new') #Model fits pretty well - p ~ 0.6ish
traceplot(mod2a)
mod2afit=mod2a$samples[[1]] #Results from mod2a
b0=mod2afit[,'alpha.mean']
theta=mod2afit[,'theta']
b1=mod2afit[,'beta']
centDate=-23:25
res2=data.frame(date=centDate,fit=NA,upr=NA,lwr=NA)
for(i in 1:nrow(res2)){ #Predictions
res2$fit[i]=exp(median(b0)+median(b1)*centDate[i])
res2[i,3:4]=quantile(exp(b0*theta+b1*centDate[i]),c(0.0275,0.975))
}
#Overall
ggplot(res2,aes(centDate+mean(temp$midDate),fit))+
geom_point(data=temp,aes(x=midDate,y=count*7/(endDate-startDate)),position=position_jitter())+
#geom_line(data=temp,aes(x=midDate,y=count,group=BLID))+
geom_line(col='red',size=1)+geom_ribbon(aes(ymax=upr,ymin=lwr),alpha=0.3)+
labs(x='Day of year',y='Predicted count',title='NB GLMM')+ylim(0,10)
#Gaussian process model - no assumptions based on time
# Single-year estimation of canola bloom ----------------------------------
setwd("~/Projects/UofC/wildbee_canola_project/Models")
library(coda)
library(jagsUI)
#Names of top4 wild spp
top4=filter(bees,BLID %in% year2year,!agricultural) %>%
mutate(year=paste0('y',year)) %>%
group_by(year,genSpp) %>%
summarize(number=n()) %>%
spread(year,number,fill=0) %>%
mutate(notZero=(y2015>0&y2016>0),diff=abs(y2015-y2016),total=y2015+y2016) %>%
filter(notZero) %>% #Filter years with zero in one year
filter((diff/total)<0.5) %>% #Filter sp where magnitude of yearly difference is less than 50% of total count
arrange(desc(total)) %>%
top_n(4,total) %>%
.$genSpp
#Occurance data for top 4 bees
top4bees=filter(bees,BLID %in% year2year) %>%
filter(genSpp %in% top4)
#Trapping occurance data (start and end of passes)
passes=trap %>%
select(BLID,pass,replicate,year,startDate,midDate,endDate,canolaBloom) %>%
distinct() %>%
unite(ID,BLID:year,remove=F) %>%
arrange(year,BLID,pass)
#Anthophora model from 2015 only
temp=group_by(top4bees,genSpp,BLID,pass,replicate,year) %>% #Abundance by date & trap
summarize(count=n()) %>%
unite(ID,BLID:year) %>%
spread(genSpp,count) %>%
full_join(passes,by='ID') %>%
gather('genSpp','count',2:5) %>%
mutate(count=ifelse(is.na(count),0,count)) %>% #Changes NAs to zeros
select(-ID) %>%
mutate(BLID=factor(BLID)) %>%
arrange(genSpp,year,BLID,pass) %>%
filter(year==2016,genSpp=='Anthophora terminalis')
# #Fixed effects: each site has mu, sigma
# datalist=with(temp, #Data to feed into JAGS
# list(
# N=nrow(temp), #Number of total samples
# Nsite=length(unique(BLID)), #Number of sites
# # count=count, #Count of bees
# site=as.numeric(BLID), #site index
# # traplength=(endDate-startDate)/7, #offset (in weeks)
# centEndDate=endDate-mean(midDate), #Centered midDate (using mean of midDate)
# canolaBloom=canolaBloom, #Bloom
# nearCanola=as.numeric(with(temp,tapply(canolaBloom,BLID,sum,na.rm=T))>0), #Is field near canola?
# lwrRange=-40, #Range of dates to integrate over
# uprRange=30,
# intWidth=1 #Width of rectangles to integrate across
# )
# )
# #Sets all fields with zero canola to NA
# datalist$canolaBloom[temp$BLID %in% with(temp,unique(BLID)[tapply(canolaBloom,BLID,sum)==0])]=NA
#
# #Starting values
# start=function() list(mu.canola=rnorm(1,0,0.01),
# sigma.canola=runif(1,10,20),
# resid.canola=rgamma(1,0.1,0.1))
# mod3=jags(data=datalist,inits=start,c('mu.canola','sigma.canola','resid.canola'),
# model.file='canolaGaussian.txt',
# n.chains=3,n.adapt=500,n.iter=2000,n.burnin=500,n.thin=5,parallel=F)
# summary(mod3) #This model works OK - very small sigma, though
# xyplot(mod3)
# densityplot(mod3)
#
# mod3fit=mod3$samples[[1]] #Results from mod3
#
# mu.canola=mod3fit[,'mu.canola']
# sigma.canola=mod3fit[,'sigma.canola']
# centDate=-20:27
#
# res3=data.frame(date=centDate,fit=NA,upr=NA,lwr=NA)
#
# for(i in 1:nrow(res3)){ #Predictions
# res3$fit[i]=100*exp(-0.5*((centDate[i]-median(mu.canola))/median(sigma.canola))^2)
# res3[i,3:4]=quantile(100*exp(-0.5*((centDate[i]-mu.canola)/sigma.canola)^2),c(0.0275,0.975))
# }
#
# #Looks OK, but lots of site-to-site variability
# ggplot(res3,aes(centDate+mean(temp$midDate),fit))+
# geom_point(data=temp,aes(x=endDate,y=canolaBloom))+
# geom_line(data=temp,aes(x=endDate,y=canolaBloom,group=BLID))+
# geom_line(col='red',size=1)+geom_ribbon(aes(ymax=upr,ymin=lwr),alpha=0.3)+
# labs(x='Day of year',y='Predicted bloom')
#Mixed-effects: each site can have a different mu and sigma
datalist=with(temp, #Data to feed into JAGS
list(
N=nrow(temp), #Number of total samples
Nsite=length(unique(BLID)), #Number of sites
# count=count, #Count of bees
site=as.numeric(BLID), #site index
# traplength=(endDate-startDate)/7, #offset (in weeks)
centStartDate=endDate-206, #Centered startDate
centEndDate=endDate-206, #Centered midDate
canolaBloom=canolaBloom, #Proportion Bloom
nearCanola=as.numeric(with(temp,tapply(canolaBloom,BLID,sum,na.rm=T))>0), #Is field near canola?
lwrRange=-40, #Range of dates to integrate over
uprRange=30,
intWidth=1, #Width of rectangles to integrate across (days)
NintRange=30-(-40)/1, #Number of rectangles (days)
BloomThresh=0.15 #Threshold value (15%), after which foragers can use canola
)
)
#Sets all fields with zero canola to NA
datalist$canolaBloom[temp$BLID %in% with(temp,unique(BLID)[tapply(canolaBloom,BLID,sum)==0])]=NA
start=function() list(mu.canola=rnorm(1,-15,0.1),
sigma.mu.site=rgamma(1,1,0.5),
resid.canola=rgamma(1,0.1,0.1),
sigma.canola=rgamma(1,3,.1),
sigma.sigma.site=rgamma(1,3,1)
)
mod4=jags(data=datalist,
inits=start,c('mu.canola','sigma.mu.site', #Overall
'resid.canola',
'sigma.canola','sigma.sigma.site',
'mu.site.canola','sigma.site.canola', #Site-level
'totalCanola',
'fit','fit.new'), #PP-checks
model.file='canolaGaussianMixed.txt',
n.chains=1,n.adapt=2000,n.iter=23000,n.burnin=3000,n.thin=20,parallel=T)
summary(mod4)
traceplot(mod4,parameters=c('mu.canola','sigma.mu.site',
'resid.canola','sigma.canola','sigma.sigma.site'))
pp.check(mod4,'fit','fit.new') #Looks OK once residuals near boundary conditions have been dealt with
mod4fit=as.mcmc(mod4$samples[[1]]) #1st chain
#Trace of mean of canola bloom (in fields near canola)
plot(mod4fit[,grepl('mu.site',colnames(mod4fit))][,which(datalist$nearCanola==1)]+mod4fit[,'mu.canola'])
#Trace of sigma of canola bloom (in fields near canola)
plot(mod4fit[,grepl('sigma.site',colnames(mod4fit))][,which(datalist$nearCanola==1)]+mod4fit[,'sigma.canola'])
#Trace of integral of canola (in fields near canola)
plot(mod4fit[,grepl('totalCanola',colnames(mod4fit))][,which(datalist$nearCanola==1)])
round(HPDinterval(mod4fit),2)
mod4fit=mod4$samples[[1]] #Results from 1st chain of mod4
pars=apply(mod4fit,2,median)
pars=pars[grepl('site.canola',names(pars))] #Strips out everything except site estimates
pars=matrix(pars,ncol=2,dimnames=list(unique(temp$BLID),c('mu','sigma')))
pars=pars[which(datalist$nearCanola>0),]
centDate=-20:27
#Cheapo way of binding dataframes
res4=matrix(NA,length(centDate),nrow(pars),dimnames=list(centDate,rownames(pars)))
#Predictions
for(i in 1:nrow(res4)){ #For each date
for(j in 1:ncol(res4)){ #For each site
res4[i,j]=round(100*exp(-0.5*((centDate[i]-pars[j,1])/pars[j,2])^2),2)
}
}
res4=data.frame(centDate=centDate,res4)
res4=gather(res4,'BLID','fit',2:13)
res4$BLID=gsub('X','',res4$BLID)
#Looks OK
# ggplot(res4,aes(centDate+mean(temp$midDate),fit,group=BLID))+
ggplot(res4,aes(centDate,fit,group=BLID))+
geom_point(data=temp,aes(x=endDate-mean(temp$midDate),y=canolaBloom,group=BLID))+
#geom_line(data=temp,aes(x=endDate,y=canolaBloom,group=BLID))+
geom_line(col='red',size=1)+
facet_wrap(~BLID)+
labs(x='Day of year',y='Percent bloom')+
theme(axis.text=element_text(size=7),strip.text=element_text(size=10))
#Fixed effects: each field can have a different mu & sigma, and is estimated independently (no hyperprior)
#Which fields are near canola
whichNearCanola <- as.numeric(with(temp,tapply(canolaBloom,BLID,sum,na.rm=T))>0)
whichNearCanola[whichNearCanola==1] <- 1:sum(whichNearCanola) #Index of means to estimate
datalist=with(temp, #Data to feed into JAGS
list(
N=nrow(temp), #Number of total samples
# Nsite=length(unique(BLID)), #Number of sites
# count=count, #Count of bees
site=as.numeric(BLID), #site index
# traplength=(endDate-startDate)/7, #offset (in weeks)
centEndDate=endDate-206, #Centered midDate
canolaBloom=canolaBloom, #Proportion Bloom
whichNearCanola=whichNearCanola+1, #Which fields are near canola (>0), and what their order is
muField=rep(-5,sum(whichNearCanola>0)+1), #Mean bloom time (for all site with canola)
precMuField=diag(0.05,sum(whichNearCanola>0)+1), #Precision for mu
# sigmaField=rep(1,sum(with(temp,tapply(canolaBloom,BLID,sum,na.rm=T))>0)), #Spread of bloom time
# precSigmaField=diag(0.1,sum(with(temp,tapply(canolaBloom,BLID,sum,na.rm=T))>0)) #Precision for sigma
sigmaField=2, #Spread of bloom time
precSigmaField=0.1 #Precision for sigma
# lwrRange=-40, #Range of dates to integrate over
# uprRange=30,
# intWidth=1, #Width of rectangles to integrate across
# NintRange=30-(-40)/1 #Number of rectangles
)
)
#Sets all fields with zero canola to NA
datalist$canolaBloom[temp$BLID %in% with(temp,unique(BLID)[tapply(canolaBloom,BLID,sum)==0])]=NA
start=function() list(mu.canola=rnorm(sum(whichNearCanola>0)+1,-5,0.1),
sigma.canola=rep(10,sum(whichNearCanola>0)+1))
mod4=jags(data=datalist,
inits=start,c('mu.canola','sigma.canola', #Overall
'resid.canola'),
model.file='canolaGaussianMixed3.txt',
n.chains=1,n.adapt=2000,n.iter=21000,n.burnin=1000,n.thin=20,parallel=F)
summary(mod4)
plot(mod4)
#Get predictions from models
sampMod4 <- mod4$samples[[1]] #Chain 1
pred <- expand.grid(Date=c(-23:36),Field=c(1:8),fit=NA,upr=NA,lwr=NA) #Data frame for predictions
predfun <- function(day,mu,sigma) {
return(round(quantile(100*exp(-0.5*((day-mu)/sigma)^2),c(0.5,0.05,0.95)),2))
}
for(i in 1:nrow(pred)){
pred[i,c(3:5)] <- predfun(pred$Date[i],
sampMod4[,grep('mu',colnames(sampMod4))[pred$Field[i]]],
sampMod4[,grep('sigma',colnames(sampMod4))[pred$Field[i]]])
}
plotdata=filter(temp,as.numeric(temp$BLID) %in% which(whichNearCanola>0)) %>%
mutate(Field=droplevels(BLID))
filter(pred,Field!=1) %>% mutate(Field=factor(Field-1,labels=levels(plotdata$Field))) %>%
ggplot(aes(Date+206,fit))+geom_ribbon(aes(ymax=upr,ymin=lwr),alpha=0.3)+
geom_line()+facet_wrap(~Field)+
geom_point(data=plotdata,aes(x=endDate,y=canolaBloom))+
labs(y='Canola bloom',x='Day of Year')
# Main model run in JAGS ----------------------------------------------------------
setwd("~/Projects/UofC/Wild bee time project/Models")
library(coda)
library(jagsUI)
#Names of top4 wild spp
top4=filter(bees,BLID %in% year2year,!agricultural) %>%
mutate(year=paste0('y',year)) %>%
group_by(year,genSpp) %>%
summarize(number=n()) %>%
spread(year,number,fill=0) %>%
mutate(notZero=(y2015>0&y2016>0),diff=abs(y2015-y2016),total=y2015+y2016) %>%
filter(notZero) %>% #Filter years with zero in one year
filter((diff/total)<0.5) %>% #Filter sp where magnitude of yearly difference is less than 50% of total count
arrange(desc(total)) %>%
top_n(4,total) %>%
.$genSpp
#Occurance data for top 4 bees
top4bees=filter(bees,BLID %in% year2year) %>%
filter(genSpp %in% top4)
#Trapping occurance data (start and end of passes)
passes=trap %>%
select(BLID,pass,replicate,year,startDate,midDate,endDate,canolaBloom) %>%
distinct() %>%
unite(ID,BLID:year,remove=F) %>%
arrange(year,BLID,pass)
#Anthophora model from both years
temp=group_by(top4bees,genSpp,BLID,pass,replicate,year) %>% #Abundance by date & trap
summarize(count=n()) %>%
unite(ID,BLID:year) %>%
spread(genSpp,count) %>%
full_join(passes,by='ID') %>%
gather('genSpp','count',2:5) %>%
mutate(count=ifelse(is.na(count),0,count)) %>% #Changes NAs to zeros
select(-ID) %>%
mutate(BLID=factor(BLID)) %>%
arrange(genSpp,year,BLID,pass) %>%
filter(genSpp=='Anthophora terminalis') %>%
select(-genSpp)
#Landscape stuff at 250m radius, for each site
templandscape=landscape %>%
gather('type','proportion',Canola_100:Seminatural_500) %>%
filter(grepl('_250',type)) %>%
unite(type,type,year) %>%
spread(type,proportion) %>%
rowwise() %>%
mutate(Seminatural_250=mean(Seminatural_250_2015,Seminatural_250_2016)) %>%
select(-Seminatural_250_2015,-Seminatural_250_2016)
centDateOffset=median(temp$midDate) #Median day to use in all analysis
temp2015=temp %>% #Data from 2015
filter(year==2015) %>%
select(-year) %>%
mutate(nearCanola=BLID %in% with(templandscape,BLID[Canola_250_2015>0])) %>%
mutate(canolaBloom=ifelse(nearCanola,canolaBloom,NA)) %>%
mutate(traplength=endDate-startDate)
temp2016=temp %>% #Data from 2016
filter(year==2016) %>%
select(-year) %>%
mutate(nearCanola=BLID %in% with(templandscape,BLID[Canola_250_2016>0])) %>%
mutate(canolaBloom=ifelse(nearCanola,canolaBloom,NA)) %>%
mutate(traplength=endDate-startDate)
datalist=list(
Nsite=nrow(templandscape), #Number of sites
N2015=nrow(temp2015), #N samples
N2016=nrow(temp2016),
sites2015=as.numeric(temp2015$BLID), #Site indices
sites2016=as.numeric(temp2016$BLID),
prop.canola2015=templandscape$Canola_250_2015, #Proportion of canola in landscape
prop.canola2016=templandscape$Canola_250_2016,
prop.SNL=templandscape$Seminatural_250, #Proportion of SNL
centEndDate2015=temp2015$endDate-centDateOffset, #Date of collection
centEndDate2016=temp2016$endDate-centDateOffset,
centMidDate2015=temp2015$midDate-centDateOffset, #Midpoint b/w collections
centMidDate2016=temp2016$midDate-centDateOffset,
traplength2015=temp2015$traplength, #Trapping length (days)
traplength2016=temp2016$traplength,
canolaBloom2015=temp2015$canolaBloom, #Canola bloom
canolaBloom2016=temp2016$canolaBloom,
#canolaSites2015=unname(which(with(temp2015,tapply(nearCanola,BLID,sum)>0))), #Sites near canola
#canolaSites2016=unname(which(with(temp2016,tapply(nearCanola,BLID,sum)>0))),
count2015=temp2015$count, #Anthophora terminalis count
count2016=temp2016$count,
NintRange=max(temp$endDate-centDateOffset)-min(temp$startDate-centDateOffset), #Range of days
lwrRange=min(temp$startDate-centDateOffset)#,
#uprRange=max(temp$endDate-centDateOffset)
)
start=function() list(
mu.canola2015 = rnorm(1,-12,0.5), #Prior for mean of bloom
sigma.mu.site2015 = rgamma(1,1,0.5), #Precision for mean of bloom (1/SD^2)
sigma.canola2015 = rgamma(1,3,.1), #Shape factor for generating SD of bloom
sigma.sigma.site2015 = rgamma(1,3,1), #Rate for generating SD
resid.canola2015 = rgamma(1,0.1,0.1), #Precision for "Residual"
intN2015.mean = rnorm(1,0,0.1), #Intercept mean
intN2015.prec = rgamma(1,0.1,0.1), #Precision of Intercept SD
slopeN2015 = rnorm(1,0,0.1), #Slope of Count-Time relationship
logDispN2015 = rnorm(1,0.5,0.1), #Dispersion parameter
mu.canola2016 = rnorm(1,-6,0.5), #Prior for mean of bloom
sigma.mu.site2016 = rgamma(1,1,0.5), #Precision for mean of bloom (1/SD^2)
sigma.canola2016 = rgamma(1,3,.1), #Shape factor for generating SD of bloom
sigma.sigma.site2016 = rgamma(1,3,1), #Rate for generating SD
resid.canola2016 = rgamma(1,0.1,0.1), #Precision for "Residual"
intN2016.mean = rnorm(1,0,0.1), #Intercept mean
intN2016.prec = rgamma(1,0.1,0.1), #Precision of Intercept SD
slopeN2016 = rnorm(1,0,0.1), #Slope of Count-Time relationship
logDispN2016 = rnorm(1,0.5,0.1), #Dispersion parameter
canola.slope = rnorm(1,0,0.1), #Slope of canola bloom on count (0 = neutral, + = repelling, - = attracting)
carryover.slope2015 = rnorm(1,1,0.1), #Slope of carryover due to last year's population
SNL.slope2015 = rnorm(1,1,0.1), # Slope of SNL effect on Site-level Intercept
SNL.slope2016 = rnorm(1,0,0.1), # Slope of SNL effect on Site-level Intercept
overlap.slope = rnorm(1,0,0.1) #Slope of total overlap (2015) on intercept (2016)
)
library(beepr)
mainMod=jags(data=datalist,
inits=start,parameters.to.save=