-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsmart_data_occupancy_analyses.Rmd
1578 lines (1162 loc) · 64.8 KB
/
smart_data_occupancy_analyses.Rmd
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
---
title: "SMART data occupancy analyses"
author: "L. Marescot, A. Lyet, R. Singh, N. Carter, and O. Gimenez"
date: '`r Sys.time()`'
output:
html_document:
code_folding: hide
pdf_document: default
---
<style>
/* Style the linenumber div */
.linenumbers {
border: 1px solid #ccc;
border-radius: 4px;
background-color: #EBEBEB;
text-align: center;
padding: 0px 3px;
font-family: monospace;
float: left;
position: absolute;
transform:translate(-125%);
font-size: inherit !important;
}
<!-- https://stackoverflow.com/questions/34259171/how-can-i-implement-a-spoiler-quote-with-just-css -->
.spoiler, .spoiler > * { transition: color 0.5s, opacity 0.5s }
.spoiler:not(:hover) { color: transparent }
.spoiler:not(:hover) > * { opacity: 0 }
/* fix weird transitions on Chrome: */
blockquote, blockquote > *:not(a) { color: black }
</style>
Here we used the SMART data and a mutlispecies dynamic occupancy model to identify co-occurence patterns of poachers and wildlife and infer their interaction.
# a) loading the libraries, the SMART data and the shapefiles
We load the library necessary for the analysis
tydyverse and lubridate helps reformating exploring the raw data
maptool, rgeos and rgdal are treating GIS shape files and data points with spatial coordinates
msm is used for the calculation of standard error associated to the parameter estimates
```{r message=FALSE, warning=FALSE, include=FALSE, paged.print=FALSE}
library(tidyverse)
library(lubridate)
library(sf)
library(raster)
library(rgdal)
library(maptools)
library(msm)
library(rgeos)
library(geosphere)
```
## Data import
Here we combined and format the data of the Phnom Prich Wildlife Sancturary PPWS (named smart_data) and SWS (named smart_data2) study area. Eventually, we perfom a joint analysis of the dynamic occupancy of multiple species across the two study sites.
```{r}
path = 'C:/Users/Marescot/Documents/GitHub/poaching_occupancy-master/SMART_DATA_2013-2017/'
smart_data <- read.csv(paste0(path,'AllPatrol_2013-2016.csv'),sep=',',header=T)
path2 = 'C:/Users/Marescot/Documents/GitHub/poaching_occupancy-master/SMART_DATAMPF_2013-2017'
smart_data2 <- read.csv(paste0(path2,'MPF_AllPatrol_2013-2016.csv'),sep=',',header=T)
```
We first need to make sense of the shapefiles, in particular to make sure that all of them are in the same system of coordinates. Notice that the shapefiles are all converted at the CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0").
```{r message=FALSE, warning=FALSE, paged.print=FALSE}
patr <- shapefile(paste0(path,"PATRL.shp"))
road <- shapefile(paste0(path,"Road_20in_20PPWS.shp"))
stream <- shapefile(paste0(path,"Stream_20in_20PPWS.shp"))
station <- shapefile(paste0(path,"PPWS_20Outpost.shp"))
crs(patr) <- CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0")
stream<-spTransform(stream, CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"))
road<-spTransform(road, CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"))
station<-spTransform(station, CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"))
patr2 <- shapefile(paste0(path2,"PATRL.shp"))
road2 <- shapefile(paste0(path2,"Road_20in_20MPF.shp"))
stream2 <- shapefile(paste0(path2,"Stream_20in_20MPF.shp"))
station2 <- shapefile(paste0(path2, "MPF_20Outpost.shp"))
stream2<-spTransform(stream2, CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"))
road2<-spTransform(road2, CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"))
crs(patr2) <- CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0")
station2<-spTransform(station2, CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"))
```
# b) data description and selection
The next step consists in selecting the columns we're interested in, that is the ones we will need to build the occupancy dataset. We also put the begining and end of patrols in an appropriate format for further manipulations (which are so far differing between both data set).
```{r message=FALSE, warning=FALSE, paged.print=FALSE}
smart <- smart_data %>%
dplyr::select(
Patrol.ID,
Patrol.Start.Date,
Patrol.End.Date,
Station,
Patrol.Transport.Type,
X,
Y,
Species,
contains("Observation.Category")) %>% # select columns
mutate(
start_patrol = dmy(Patrol.Start.Date),
end_patrol = dmy(Patrol.End.Date)) # appropriate format for dates
smart2 <- smart_data2 %>%
dplyr::select(
Patrol.ID,
Patrol.Start.Date,
Patrol.End.Date,
Station,
Patrol.Transport.Type,
X,
Y,
Species,
contains("Observation.Category")) %>% # select columns
mutate(
start_patrol = (Patrol.Start.Date),
end_patrol = (Patrol.End.Date)) # appropriate format for dates
smart$start_patrol<-as.Date(smart$start_patrol, "%m/%d/%Y")
smart$end_patrol<-as.Date(smart$end_patrol, "%m/%d/%Y")
smart2$start_patrol<-as.Date(smart2$start_patrol, "%m/%d/%Y")
smart2$end_patrol<-as.Date(smart2$end_patrol, "%m/%d/%Y")
```
In the next section, we would like to have a look to the data of the study area. To do so, we first convert the data we have into a spatial object with the same coordinates as that of the patroling sites (which are polygons). In passing, we count the number of patrols made through each means available (boat, foot, etc...).
```{r}
xy <- smart[,c("X","Y")]
smart_allpoints <- SpatialPointsDataFrame(coords = xy, data = smart,
proj4string = CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"))
fullmap <- over(patr, smart_allpoints)
fullmap %>% count(Patrol.Transport.Type)
xy2 <- smart2[,c("X","Y")]
smart_allpoints2 <- SpatialPointsDataFrame(coords = xy2, data = smart2,
proj4string = CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"))
fullmap2 <- over(patr2, smart_allpoints2)
fullmap2 %>% count(Patrol.Transport.Type)
```
## Focus on animals mainly ungulates
Now let us focus on the animal. As the direct observations of tigers were very scarce, we used the presence of their main prey as a surrogate variable for their occurence. Therefore, we selected any species of ungulates, bovidae or wild pigs. We first wanted to retain observations corresponding to detection of preys that were not moved by humans. To do so, we selected only direct sightings and signs. We displayed the sample size per species first from PPWS and second from the SWS.
```{r message=FALSE, warning=FALSE, paged.print=FALSE}
smart_animals <- smart %>%
filter(
# Observation.Category.0=='Animals')
Observation.Category.1=='Direct Sighting'| Observation.Category.1=='Sign') # uncomment this line if you want to filter and retain only direct sightings/signs
smart_animals <- smart_animals %>%
filter(
Species=="Banteng (Bos javanicus)" |
Species== "Barking Deer, Red Muntjac (Muntiacus muntjak)" |
Species== "Gaur (Bos Gaurus)" |
Species== "Sambar Deer (Rusa unicolor)" |
Species== "Eld's Deer (Rucervus eldii)" |
Species== "Wild Pig, Wild Boar (Sus scrofa)") # filter to retain only ungulates, bovidae, wild pigs
smart_animals %>% count(Species) # check that we have the target species
xy <- smart_animals[,c("X","Y")]
smart_AnimalSites <- SpatialPointsDataFrame(coords = xy, data = smart_animals, proj4string = CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"))
smart_animals2 <- smart2 %>%
filter(
# Observation.Category.0=='Animals')
Observation.Category.1=='Direct Sighting'| Observation.Category.1=='Sign') # uncomment this line if you want to filter and retain only direct sightings/signs
smart_animals2 <- smart_animals2 %>%
filter(
Species=="Banteng (Bos javanicus)" |
Species== "Barking Deer, Red Muntjac (Muntiacus muntjak)" |
Species== "Gaur (Bos Gaurus)" |
Species== "Sambar Deer (Rusa unicolor)" |
Species== "Eld's Deer (Rucervus eldii)" |
Species== "Wild Pig, Wild Boar (Sus scrofa)") # filter to retain only ungulates, bovidae, wild pigs
smart_animals2 %>% count(Species) # check that we have the target species
xy2 <- smart_animals2[,c("X","Y")]
smart_animal2 <- SpatialPointsDataFrame(coords = xy2, data = smart_animals2, proj4string = CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"))
```
## Focus on illegal activity mainly snares
Let us select illegal activity, the traps more precisely and visualize these data:
```{r}
smart_activity <- smart %>%
filter(
Observation.Category.0=='Illegal Activity',
Observation.Category.4=='Trap')
xy <- smart_activity[,c("X","Y")]
smart_poachers <- SpatialPointsDataFrame(coords = xy, data = smart_activity,
proj4string = CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"))
smart_activity2 <- smart2 %>%
filter(
Observation.Category.0=='Illegal Activity',
Observation.Category.4=='Trap')
xy2 <- smart_activity2[,c("X","Y")]
smart_poachers2 <- SpatialPointsDataFrame(coords = xy2, data = smart_activity2,
proj4string = CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"))
```
# c) build and map the occupancy grid
Let us put everything on two grids and later combining them both. We first associate each observation to an occupied site and check where co-occurence of wildlife and poachers occur. Plain dots represent the location of wildlife and black crosses represent poachers. Water streams are characterized by blue lines (not displayed in Figure 1) and roads by grey lines. We represented the ranger permanent stations and temporary campsites with stars. For each observation made (whether signs of animals or paochers), we calculate here the closest distance to road, to patrolling station and to river stream.
```{r}
# build the grid
# create a grid that bounds the study area in other words that covers the full distribution of poacher signs.
bb<-bbox(patr) # this geographic coordinates of the patroling shape file are: longitude (xmin=106.5188, xmax=107.1647, ymin=12.47707, ymax=13.02043 ) which corresponds to a maximum distance of 54km or a 46 km by 28 km grid
cs<-c(0.1, 0.1) # this is the resolution of the patrl shapefile
cc <- bb[, 1] + (cs/2)
cd <- ceiling(diff(t(bb))/cs) # number of cells per direction
grd <- GridTopology(cellcentre.offset=cc, cellsize=cs, cells.dim=cd)
sp_grd <- SpatialGridDataFrame(grd,
data=data.frame(id=1:prod(cd)),
proj4string=CRS(proj4string(patr)))
smart_grid <- SpatialGrid(grd)
polys <- as.SpatialPolygons.GridTopology(grd)
proj4string(polys) <- CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0")
centers <- coordinates(polys)
#points(centers, col="red", pch=16)
plot(smart_grid, main ="PPWS")
plot(smart_AnimalSites, add=T, pch=16)
plot(smart_poachers, add=T, pch=3)
plot(road, add=T, col="grey")
#plot(stream, add=T, col="blue")
plot(station, add=T, pch=8)
df<-over(polys,stream)
df$LENGTH[is.na(df$LENGTH)==TRUE]<-0
streamlength <- df$LENGTH
# uncomment the following line to calculate the distance to road (to save time just use the predefined vector DistToRoad below)
#DistToStream<-NULL
#DistToRoad<-NULL
#for(i in 1:nrow(centers))
#{
#l<-dist2Line(centers[i,], stream, distfun=distHaversine)[1]
#r<-dist2Line(centers[i,], road)[1]
#DistToRoad <- c(DistToRoad,r)
#DistToStream <- c(DistToStream,r)
#}
# DistToStation<-NULL
#
# for(i in 1:nrow(centers))
# {
# l<-dist2Line(centers[i,], station)[1]
# #r<-dist2Line(centers[i,], road)[1]
# DistToStation <- c(DistToStation,l)
# #DistToStream <- c(DistToStream,r)
# }
DistToStation <- c(30791.692111, 24006.793438, 18759.915195, 13404.757881, 8217.937610, 11580.430810, 20882.363116, 24636.780895, 15330.385008,
9080.718822, 3723.421533, 1630.199643, 7086.042683, 17406.475427, 15040.471793, 11768.433693, 1446.146956, 1626.517705, 4620.782415, 3649.206393, 10562.836816, 7829.006935, 1755.059310, 1168.281391, 585.669201, 7.224508, 212.360046, 3261.691807, 11880.363507, 7164.177552, 2882.751076, 1402.491171, 5912.361637, 3224.486885, 7108.188918, 12476.207483, 1909.889418, 1457.862997, 4404.300171, 7546.417244, 7727.457984, 8167.702037)
DistToRoad<-c(28470.98983, 19403.33774, 12080.62050, 8585.18300, 3485.68593, 11282.34092, 20370.00738, 20026.34957, 13226.93722, 4935.65956, 1415.50920, 548.60028, 8048.67626, 16961.62186, 9714.90129, 4859.34844, 697.52490, 6089.36955, 3174.15239, 2535.48533, 9573.08896, 5243.79253, 2276.00314, 9096.38700, 2583.91489, 77.21720, 4609.23605, 3293.19063, 2004.87745, 2462.59855, 40.26665, 667.78384, 3353.72234, 2039.86728, 5421.26747, 4014.11217, 1940.55816, 36.35545, 2627.62993, 3012.23888, 2150.63044, 8019.38451)
# same thing for SWS study area
bb<-bbox(patr2)
cs<-c(0.10, 0.10)
cc <- bb[, 1] + (cs/2)
cd <- ceiling(diff(t(bb))/cs) # number of cells per direction
grd2 <- GridTopology(cellcentre.offset=cc, cellsize=cs, cells.dim=cd)
# this spatial grid data-frame is needed later for the sppolt function that provides dynamic colored map of the expected species distribution
sp_grd2 <- SpatialGridDataFrame(grd2,
data=data.frame(id=1:prod(cd)),
proj4string=CRS(proj4string(patr2)))
smart_grid2 <- SpatialGrid(grd2)
# plot the grid
polys2 <- as.SpatialPolygons.GridTopology(grd2)
proj4string(polys2) <- CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0")
plot(smart_grid2, main ="SWS")
plot(smart_animal2, add=T, pch=16)
plot(smart_poachers2, add=T, pch= 3)
plot(road2, add=T, col="grey")
#plot(stream2, add=T, col="blue")
plot(station2, add=T, pch=8)
centers2 <- coordinates(polys2)
#points(centers2, col="red", pch=16)
df2<-over(polys2,stream2)
df2$LENGTH[is.na(df2$LENGTH)==TRUE]<-0
streamlength2 <- df2$LENGTH
# uncomment the following line to calculate the distance to road (to save time just use the predefined vector DistToRoad below)
#DistToStream<-NULL
# DistToRoad2<-NULL
#
# for(i in 1:nrow(centers2))
# {
#
# r2<-dist2Line(centers2[i,], road2)[1]
# DistToRoad2 <- c(DistToRoad2,r2)
# }
DistToRoad2 <- c(14734.0677, 9142.4231, 7109.6824, 8393.3763, 15446.7631, 15802.7682, 18559.2598, 7443.1685, 1198.7680, 1555.2910, 3490.8576, 5550.5012, 4854.7566, 8960.3871, 4214.5244, 1356.5697, 2378.7269, 1329.8075, 4727.3093, 5750.6648, 6730.0388, 2539.4967, 760.1405, 2426.0919, 1225.3026, 3262.0905, 10294.2685, 15971.4548, 311.2909, 252.9835, 925.8761, 4125.7572, 2520.9452, 4715.4527, 14421.3621, 317.6185, 3306.6249, 1549.0970, 3330.4911, 1463.9356, 6120.4305, 15890.9265, 1751.0739, 2536.7525, 4935.1573, 286.3034, 2331.6609, 12347.4205, 20121.6975, 10634.7618, 3794.5089, 220.2991, 1804.6447, 1270.3573, 9486.6199, 20122.9947)
# DistToStation2<-NULL
#
# for(i in 1:nrow(centers2))
# {
# l2<-dist2Line(centers2[i,], station)[1]
# #r<-dist2Line(centers[i,], road)[1]
# DistToStation2 <- c(DistToStation2,l2)
# #DistToStream <- c(DistToStream,r)
# }
DistToStation2 <- c(49712.7755, 51830.6673, 56004.5776, 61819.4460, 68860.8126, 76792.0270, 85365.4229, 38707.8747, 41393.7831, 46515.8408, 53377.2796,
61397.6937, 70180.8501, 79474.2637, 27749.5828, 31389.0477, 37891.0688, 46058.8928, 55157.3906, 64795.6894, 74324.7210, 16928.4854,22402.9776, 30863.1800, 40478.4013, 50594.3533, 58841.6541, 67105.3806, 6920.7401, 16226.6081, 26550.2878, 36195.7745, 43360.0708,51823.5484, 61048.2372, 2477.0463, 12797.9746, 21053.2747, 27887.4849, 36713.7524, 46409.0905, 56528.0807, 961.3044, 6986.1269, 12468.6345, 22137.5308, 32565.0589, 43205.3832, 53932.7024, 2985.9238, 3557.6160, 10605.1458, 21147.1947, 31903.6123, 42712.7492, 53542.6849)
```
A key aspect of designing occupancy studies is the number of repeated surveys that should be conducted (MacKenzie et al. 2005). After investigating the sensitivity of estimates to different spatial scale of the site, total number of sites along with the sensitivity of estimates to number of repeated measures and primary occasions.
First, we are determining the number of surveys required to have a relatively high probability of detecting the species at a site if it was present, and a low probability of declaring the species as falsely absent in order to have a relatively low bias in occupancy estimates, extinction estimates of preys and colonisation estimates of poachers.
For a 4 years study, we looked at: with monthly repated samples over trimesters, monthly repeated samples over years, trimester repeated samples over years.
The one that gave the highest detection probability was the one considering months as secondary occasions and years as primary
Note that MacKenzie et al. (2005) concluded from a simular simulation study conducted on a static single species occupancy model that for the monitoring a rare species, it is more efficient to survey more sampling units with less repeated measures. Our case is different as it involves several species difficult to detect, one of each (poachers) is likely abundant species while the others are rare species (tiger preys).
The results of our simulation study showed that it is better to sample few sites many times. So we focused on increasing the number of repeated measure rather than the number of spatial sites.
We benefit from the results of the simulation study above to design the occupancy tables: 35 sites in PPWS study site and 46 sites in MPF with secondary occasions defined every month and primary occasion set every year. This means that if both species were dected in the same site in a given month but not necessarily at the same days, we consider that the both co-occurred without providing information on the order of occurence.
```{r}
PixPoachers <-NULL
PixAnimals <-NULL
par(mfrow = c(3,3))
primary<-unique(c(year(smart_animals$start_patrol), year(smart_animals$end_patrol)))
# first case we define the secondary occasions on a monthly period in which colonisation and extinction are both constant
#secondary<-unique(c(months(smart_poachers$start_patrol), months(smart_poachers$end_patrol)))
# second case we define the secondary occasions on a trimestrial period in which colonisation and extinction are both constant
secondary<-c("January", "February" , "March" , "April", "May", "June", "July", "August", "September", "October", "November", "December")
n.primary<-4
n.secondary<-12
# We define an occupancy table with sites sampled monthly over 4 years
patchocc<-array(0, dim=c((nrow(centers)+nrow(centers2)), length(primary), length(secondary)))
smart_animals2$start_patrol<-as.Date(smart_animals2$start_patrol, "%m/%d/%Y")
smart_animals2$end_patrol<-as.Date(smart_animals2$end_patrol, "%m/%d/%Y")
smart_activity2$start_patrol<-as.Date(smart_activity2$start_patrol, "%m/%d/%Y")
smart_activity2$end_patrol<-as.Date(smart_activity2$end_patrol, "%m/%d/%Y")
#patchprey<-array(0, dim=c(dim(list_pixel)[1], length(primary)*length(secondary), length(primary)))
inc1 <- 0
tempcov <-NULL
tempcov2 <-NULL
for(y in sort(primary))
{
inc1<-inc1+1
inc2<-0
for(m in secondary)
{
inc2<- inc2 + 1
# inctrim<-ceiling(inc2/3) # converting the month in a trimester period (only useful to investigate other designs for occupancy tables)
smart_points <- smart %>%
filter((year(start_patrol)==y | year(end_patrol)==y) & (months(start_patrol)==m | months(end_patrol)==m)) #
#patrolling effort in PPWS study area
if(dim(smart_points)[1] > 0)
{
xypts <- smart_points[,c("X","Y")]
smart_pts <- SpatialPointsDataFrame(coords = xypts, data = smart_points, proj4string = CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"))
list_pixel = over(smart_pts, geometry(polys), returnList = FALSE)
lpix<-table(list_pixel)
# here we define a covariate for the patrolling effort defined as the frequency of survey conducted on each site in a given month regardless of what they observed and of the identity of the ranger
# notice that we standardised the covariate at each occasion to better compare spatial effort across time
timepatreffort<-rep(0, nrow(centers))
timepatreffort[as.numeric(names(lpix))]<-lpix/max(lpix)
tempcov<-cbind(tempcov, month=timepatreffort)
colnames(tempcov)[ncol(tempcov)]<-paste0(m,"_",y)
} else
{
noeffort<-rep(0, nrow(centers))
tempcov<-cbind(tempcov, month=noeffort)
colnames(tempcov)[ncol(tempcov)]<-paste0(m,"_",y)
}
# Patrolling effort in SWS case study
smart_points2 <- smart2 %>%
filter((year(start_patrol)==y | year(end_patrol)==y) & (months(start_patrol)==m | months(end_patrol)==m))
if(dim(smart_points2)[1] > 0)
{
xypts2 <- smart_points2[,c("X","Y")]
smart_pts2 <- SpatialPointsDataFrame(coords = xypts2, data = smart_points2, proj4string = CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"))
list_pixel2 = over(smart_pts2, geometry(polys2), returnList = FALSE)
lpix2<-table(list_pixel2)
# here we determine the value of the patrolling effort in terms of number of time agent went our prospecting each site in a given month regardless of what they observed and of the identity of the ranger
# notice that we standardise the covariate at each occasion to better compare spatial effort across time
timepatreffort2<-rep(0, nrow(centers2))
timepatreffort2[as.numeric(names(lpix2))]<-lpix2/max(lpix2)
tempcov2<-cbind(tempcov2, month=timepatreffort2)
colnames(tempcov2)[ncol(tempcov2)]<-paste0(m,"_",y)
} else
{
noeffort2<-rep(0, nrow(centers2))
tempcov2<-cbind(tempcov2, month=noeffort2)
colnames(tempcov2)[ncol(tempcov2)]<-paste0(m,"_",y)
}
# selecting animals and poachers years of occurence in PPWS and SWS
smart_animalsYears <- smart_animals %>%
filter((year(start_patrol)==y | year(end_patrol)==y) & (months(start_patrol)==m | months(end_patrol)==m)) # filter to retain only the year and the month of wildlife presence regardless of how primary and secondary occasions are defined
smart_poachersYears <- smart_activity %>%
filter((year(start_patrol)==y | year(end_patrol)==y) & (months(start_patrol)==m | months(end_patrol)==m)) # filter to retain only the year and the month of poacher presence regardless of how primary and secondary occasions are defined
# same thing in WSW study area
smart_animalsYears2 <- smart_animals2 %>%
filter((year(start_patrol)==y | year(end_patrol)==y) & (months(start_patrol)==m | months(end_patrol)==m))
smart_poachersYears2 <- smart_activity2 %>%
filter((year(start_patrol)==y | year(end_patrol)==y) & (months(start_patrol)==m | months(end_patrol)==m))
# presence of animals in PPWS
if(dim(smart_animalsYears)[1] > 0)
{
xyPrey <- smart_animalsYears[,c("X","Y")]
smart_animalsmap <- SpatialPointsDataFrame(coords = xyPrey, data = smart_animalsYears, proj4string = CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"))
#plot(smart_animalsmap, add=T)
# this way of using the over function : it retrives a table with the pixel number in rows and the data frame attribute as columns. The non na rows show the grid cell that hold a spatial point. Empty pixels retrieve a row of NAs
list_pixelAnimals = over(geometry(polys), smart_animalsmap, returnList = FALSE)
# We determine which sites (rows) the poachers (assigned with a 1) are every month (column) over 4 years (Third dimension)
PixAnimals<-which(!is.na(list_pixelAnimals[,1]))
# here it retrieves a table of length data point at this time occiasion and the pixel number that overlap with spatial location of the data points. If some spatial points fall outside the grid it retrieves a NA
#PixAnimals<-over(smart_animalsYears, geometry(polys), returnList = FALSE)
patchocc[PixAnimals,inc1,inc2]<-2
}
# Presence of animals in SWS
if(dim(smart_animalsYears2)[1] > 0)
{
xyPrey2 <- smart_animalsYears2[,c("X","Y")]
smart_animalsmap2 <- SpatialPointsDataFrame(coords = xyPrey2, data = smart_animalsYears2, proj4string = CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"))
#plot(smart_animalsmap, add=T)
# this way of using the over function : it retrives a table with the pixel number in rows and the data frame attribute as columns. The non na rows show the grid cell that hold a spatial point. Empty pixels retrieve a row of NAs
list_pixelAnimals2 = over(geometry(polys2), smart_animalsmap2, returnList = FALSE)
# We determine which sites (rows) the poachers (assigned with a 1) are every month (column) over 4 years (Third dimension)
PixAnimals2<-which(!is.na(list_pixelAnimals2[,1]))
# here it retrieves a table of length data point at this time occiasion and the pixel number that overlap with spatial location of the data points. If some spatial points fall outside the grid it retrieves a NA
#PixAnimals<-over(smart_animalsYears, geometry(polys), returnList = FALSE)
patchocc[(nrow(centers)+PixAnimals2),inc1,inc2]<-2
}
# occurence of poachers only in PPWS
if(dim(smart_poachersYears)[1] > 0)
{
xyPoach <- smart_poachersYears[,c("X","Y")]
smart_poachersYears <- SpatialPointsDataFrame(coords = xyPoach, data = smart_poachersYears,
proj4string = CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"))
list_pixelPoachers = over(geometry(polys), smart_poachersYears, returnList = FALSE)
PixPoachers<-which(!is.na(list_pixelPoachers[,1]))
#We determine which sites (rows) the poachers (assigned with a 1) are every month (column) over 4 years (Third dimension)
patchocc[PixPoachers,inc1,inc2] <- 1
}
# occurence of poachers only in SWS
if(dim(smart_poachersYears2)[1] > 0)
{
xyPoach2 <- smart_poachersYears2[,c("X","Y")]
smart_poachersYears2 <- SpatialPointsDataFrame(coords = xyPoach2, data = smart_poachersYears2,
proj4string = CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"))
list_pixelPoachers2 = over(geometry(polys2), smart_poachersYears2, returnList = FALSE)
PixPoachers2<-which(!is.na(list_pixelPoachers2[,1]))
#We determine which sites (rows) the poachers (assigned with a 1) are every month (column) over 4 years (Third dimension)
patchocc[(nrow(centers)+PixPoachers2),inc1,inc2] <- 1 # we add the cell number with poachers only in SWS to the total number of cells in PPWS
}
# occurence of both poachers and wildlife in PPWS
if(dim(smart_poachersYears)[1] > 0 & dim(smart_animalsYears)[1] > 0)
{
cooc<-PixPoachers[which(PixPoachers %in% PixAnimals == TRUE)]
#We determine which sites (rows) both species (assigned with a 3) are every month (column) over 4 years (Third dimension)
patchocc[cooc,inc1,inc2]<- 3
}
# occurence of both poachers and wildlife in SWS
if(dim(smart_poachersYears2)[1] > 0 & dim(smart_animalsYears2)[1] > 0)
{
cooc2<-PixPoachers2[which(PixPoachers2 %in% PixAnimals2 == TRUE)]
#We determine which sites (rows) both species (assigned with a 3) are every month (column) over 4 years (Third dimension)
patchocc[(nrow(centers)+cooc2),inc1,inc2]<- 3
}
}
}
# Binding the covariates specific to PPWS and SWS together and standardizing them
tempcov<- rbind(tempcov, tempcov2)
roadcov<- c(DistToRoad, DistToRoad2)
roadcov<-roadcov/(max(roadcov))
streamcov<- c(streamlength, streamlength2)
streamcov<-streamcov/(max(streamcov))
stationcov<-c(DistToStation, DistToStation2)
stationcov<-stationcov/(max(stationcov))
```
We also display the distribution of observed sites in the follwoing states unoccupied (0), occupied by poachers (1), occupied by animal preys (3), occupied by both (4).
```{r}
list_pixelpatr <- over(geometry(polys), patr ,returnList = FALSE)
list_pixelpatr2 <- over(geometry(polys2), patr2 ,returnList = FALSE)
list_pixel<-rbind(list_pixelpatr, list_pixelpatr2)
tempcov<-tempcov[which(!is.na(list_pixel[,1])),]
roadcov<- roadcov[which(!is.na(list_pixel[,1]))]
streamcov<- streamcov[which(!is.na(list_pixel[,1]))]
stationcov<-stationcov[which(!is.na(list_pixel[,1]))]
patchocc2 <- patchocc[which(is.na(list_pixel[,1])),,] # list of sites that were not prospected
patchocc <- patchocc[which(!is.na(list_pixel[,1])),,] # occupanyc table with the prospected sites
OccupancyState <- patchocc
dist <- table(OccupancyState)
dist
sp_grd@data$survey<-rep(0.1,nrow(sp_grd))
list_pixelpatr <- over(geometry(polys), patr ,returnList = FALSE)
sp<-sp_grd@data$id[which(is.na(list_pixelpatr[,1]))]
for (i in which(is.na(list_pixelpatr[,1]))){
sp_grd@data$survey[sp_grd@data$id[i]]<-0.9
}
at_regular = c(0,0.5,1)
p1 = spplot(sp_grd, c("survey"), col.regions = c("white", "black", "grey"), at = at_regular, main = c("PPWS"), col = c("white", "grey"), panel = function(...) {
panel.gridplot(..., border="black")
sp.points(smart_AnimalSites, cex=1.4, pch=16)
sp.points(smart_poachers, cex=1.4, pch=3)
sp.points(station, cex=1.7, col="black", pch=8)
sp.lines(road, cex=1, col="grey")
})
sp_grd2@data$survey<-rep(0.1,nrow(sp_grd2))
list_pixelpatr2 <- over(geometry(polys2), patr2 ,returnList = FALSE)
sp<-sp_grd2@data$id[which(is.na(list_pixelpatr2[,1]))]
for (i in which(is.na(list_pixelpatr2[,1]))){
sp_grd2@data$survey[sp_grd2@data$id[i]]<-0.9
}
# p1 # uncomment to plot the PPWS with the non prosepected cell shaded in grey
at_regular = c(0,0.5,1)
p2 = spplot(sp_grd2, c("survey"), col.regions = c("white", "black", "grey"), at = at_regular, main = c("SWS"), col = c("white", "grey"), panel = function(...) {
panel.gridplot(..., border="black")
sp.points(smart_animal2, cex=1, pch=16)
sp.points(smart_poachers2, cex=1, pch=4)
sp.points(station2, cex=1.5, col="black", pch=8)
sp.lines(road2, cex=0.3, col="grey")
# sp.lines(stream2, cex=0.3, col="blue")
})
# p2 # uncomment to plot the SWS with the non prosepected cell shaded in grey
```
# d) A dynamic two-species patch-occupancy model, formulated as a HMM (Gimenez et al. 2014).
For now, we adopt the Waddle parameterization for occupancy and detection, and the MacKenzie parameterization for transitions (see pages 264-265 in MacKenzie et al. 2006). Hereafter A stands for the poacher and B stands for the prey.
## The model
The states are:
* U = unoccupied
* OP = only poachers present
* OW = only wildlife species are present
* WP = both species present
The observations are:
* 1 = none species observed
* 2 = only Poacher is observed
* 3 = only Wildlife is observed
* 4 = both are observed.
The model is completely specified with 3 pieces:
* Vector of initial state probabilities $\Pi = \Pi_1 \Pi_2$
$$\Pi_1 = \left[\begin{array}
{rrrr}
1-\psi_W & \psi_W \\
\end{array}\right]
$$
$$\Pi_2 = \left[\begin{array}
{rrrr}
1-\psi_{P/\bar{W}} & \psi_{P\bar{W}} & 0 & 0 \\
0 & 0 & 1-\psi_{P/W} &\psi_{P/W} \\
\end{array}\right]
$$
* Transition matrix $T$
$$T = \left[\begin{array}
{rrrr}
1-\gamma_{P}-\gamma_{W}+\gamma_{WP} & \gamma_{P}-\gamma_{WP} & \gamma_{W}-\gamma_{WP} & \gamma_{WP} \\
\epsilon_{P/\bar{W}} & 1-\epsilon_{P/\bar{W}}-\omega_{PW}-\gamma_{W/P}& \omega_{PW} & \gamma_{W/P} \\
\epsilon_{W/\bar{P}} & \omega_{WP} & 1-\epsilon_{W/\bar{P}}-\omega_{WP}-\gamma_{P/W} & \gamma_{P/W} \\
\epsilon_{WP} & \epsilon_W-\epsilon_{WP} & \epsilon_P-\epsilon_{WP} & 1-\epsilon_P-\epsilon_W+\epsilon_{WP}
\end{array}\right]
$$
* Observation matrix
$$\mathbf{B} = \left[\begin{array}
{rrrr}
1 & 0 & 0 & 0 \\
1-p_P & p_P & 0 & 0 \\
1-p_W & 0 & p_W & 0 \\
1-p_{WP} & 0 & 0 & p_{WP}
\end{array}\right]
$$
## Calculating the deviance of a multi-species patch occupancy model
First we loaded the functions showing all the effects tested on the detection, occupancy and transition probabilities. We also load the likelihood functions for the candidate models
```{r}
source('Detection_Effects.R')
source('Occupancy_Effects.R')
source('Transition_Effects.R')
source('Likelihood_detection.R')
source('Likelihood_occupancy.R')
source('Likelihood_transition.R')
```
We define the logprot function to avoid the log likelihood to reach infinite values
```{r}
logprot <- function(v){
# avoid explosion of log(0)
eps <- 2.2204e-016
u <- log(eps) * (1+vector(length=length(v)))
index <- (v>eps)
u[index] <- log(v[index])
u
}
# here we define the number of iterations for computing the maximum likeliood of each model (to avoid local minima)
niter<-4
```
## Candidate models for the effects on detection
testing effects of species, patrolloing effort, road, and rivers on the detection probability. We display the best model of this section, the one with the lowest AIC
```{r}
effectlist1<-c("cst detection","no prey effects on detection of poachers", "no poacher effects on detection of preys","species interaction effects on detection","spatial effect of patroling effort on detection", "time effect of patroling effort on detection", "spatio-temporal effect of patroling effort on detection", "distance to road effect on detection", "stream length effect on detection", "distance to station effect on detection")
npar<-vector(mode="logical", length=length(effectlist1))
AICc<-vector(mode="logical", length=length(effectlist1))
devModel1<-vector(mode="logical", length=length(effectlist1))
e <- 0
for(P_effects in effectlist1)
{
e<-e+1
R = nrow(patchocc) # number of sites
n.states <- 4 # nb states
n.obs <- 4 # nb events
n.primary <- length(primary) # nb primary occasions
n.secondary <- length(secondary) # nb secondary occasions
J <- n.secondary
K <- n.primary
N <- n.primary * n.secondary
#now reshape array in matrix with secondary occ within primary occ:
obs = matrix(NA,nrow=R,ncol=n.primary*n.secondary)
count = 1
for (i in 1:n.primary){
for (j in 1:n.secondary){
obs[,count] <- patchocc[,i,j]
count = count+1
}
}
eff = rep(1,R) # nb sites with this particular history
#coveff<- patreffort
garb = obs[,1] # initial states
data = t(obs) # transpose
# primary and secondary occasions
primaryseq = seq(J,J*K,by=J)
secondaryseq = 1:(J*K)
bparam<-c(0.41, 0.07, 0.07, 0.04, 0.18, 0.18, 0.14, 0.40, 0.18, 0.14, 0.18, 0.05, 0.14, 0.86, 0.05, 0.16, 0.10, 0.05, 0.1, 0.1, 0.05, rep(0.5, 20))
binit<- log(bparam/(1-bparam))
res = optim(binit,dev_2spocc_dyn,NULL, data,eff, tempcov, roadcov, stationcov, streamcov, garb,R,primaryseq,secondaryseq,n.states, P_effects, method="BFGS",control=list(trace=0, REPORT=1), hessian = FALSE)
dev<-res$value
b = res$par
# Here we subtract the number of parameters that were not optimized (i.e equal to the inital values) and substract them from the number of parameters of the model
checkpar<-b-binit
npar[e]<-length(checkpar[-c(which(checkpar==0))])
devModel1[e]<-dev
AICc[e]<- 2*npar[e] + 2*dev + (2*npar[e]^2 + 2*npar[e])/(R-npar[e]-1)
#hessianfinal<-optimHess(res$par,dev_2spocc_dyn,NULL, data,eff,tempcov, garb,R,primaryseq,secondaryseq,n.states, control=list(trace=0, REPORT=1))
}
AICdet<-AICc
npardet<- npar
Best_detection_model<-effectlist1[AICc==min(AICc)]
Best_detection_model
```
## Candidate models for the effects on occupancy
Here we tested effects on the occupancy parameters given the best effects already selected on the detection
Here we tested effects on the occupancy parameters given the best effects already selected on the detection
```{r}
# this is the list of effects tested on the occupancy probabilities
effectlist2<-c("no prey effect on occupancy of poachers", "species interaction effects on occupancy", "spatial effect of patroling effort on occupancy", "spatial effect of patroling effort on poacher occupancy only", "spatial effect of patroling effort on poacher occupancy given presence/absence of prey", "distance to road on occupancy", "stream length effect on occupancy", "distance to station effect on occupancy")
# as the number of parameter vary with the type of hypothesis that we test we defin a vector with the number of parameters per model
npar<-vector(mode="logical", length=length(effectlist2))
# we define a vector to store the AICc of each model
AICc<-vector(mode="logical", length=length(effectlist2))
# we define a vector to store the deviance of each model
devModel2<-vector(mode="logical", length=length(effectlist2))
e <- 0
# we loop over the candidate models with the effects tested on the occupancy
for(P_effects in effectlist2)
{
e<-e+1
R = nrow(patchocc) # number of sites
n.states <- 4 # nb states
n.obs <- 4 # nb events
n.primary <- length(primary) # nb primary occasions
n.secondary <- length(secondary) # nb secondary occasions
J <- n.secondary
N <- n.primary * n.secondary
K <- n.primary
#binit = b[1:npar[e]]
#now reshape array in matrix with secondary occ within primary occ:
obs = matrix(NA,nrow=R,ncol=n.primary*n.secondary)
count = 1
for (i in 1:n.primary){
for (j in 1:n.secondary){
obs[,count] <- patchocc[,i,j]
count = count+1
}
}
eff = rep(1,R) # nb sites with this particular history
#coveff<- patreffort
garb = obs[,1] # initial states
data = t(obs) # transpose
# primary and secondary occasions
primaryseq = seq(J,J*K,by=J)
secondaryseq = 1:(J*K)
# to avoid local minima we run can either run 10 time the optimize function and extract the minimum deviance
#for(iteration in 1:niter)
#{
# binit = runif(32) # we reset the intial value at each loop (notice that we drawn the number of coefficients from the most parameterized model (time and space effects of the patrolling effort covariate) )
# or we can fix the initial values again to avoid local minima without having to run several times the same model
bparam<-c(0.41, 0.07, 0.07, 0.04, 0.18, 0.18, 0.14, 0.40, 0.18, 0.14, 0.18, 0.05, 0.14, 0.86, 0.05, 0.16, 0.10, 0.05, 0.1, 0.1, 0.05, rep(0.5, 20))
binit<- log(bparam/(1-bparam))
res = optim(binit,dev_2spocc_dyn2,NULL, data,eff, tempcov, roadcov, stationcov, streamcov, garb,R,primaryseq,secondaryseq,n.states, P_effects, method="BFGS",control=list(trace=0, REPORT=1), hessian = FALSE)
# if( res$value < dev) # if the current deviance is smaller than the previous one we set the minimum deviance dev to this new value
{
dev<-res$value
b = res$par
}
#}
# we store the final min deviance to the vector of models' deviance
devModel2[e]<-dev
#hessianfinal<-optimHess(res$par,dev_2spocc_dyn2,NULL, data,eff,tempcov, garb,R,primaryseq,secondaryseq,n.states, P_effects, control=list(trace=0, REPORT=1))
# we store the estimated mathematical parameters associated to the maximum likelihood
# Here we subtract the number of parameters that were not optimized (i.e equal to the inital values) and substract them from the number of parameters of the model
checkpar<-b-binit
npar[e]<-length(checkpar[-c(which(checkpar==0))])
AICc[e]<- 2*npar[e] + 2*dev + (2*npar[e]^2 + 2*npar[e])/(R-npar[e]-1)
}
AICocc<-AICc
nparocc<- npar
Best_occ_model<-effectlist2[AICc==min(AICc)]
```
## Candidate models for effects on transition
Here we tested effects on the transition parameters given the best effects already selected on the occupancy and detection
We estimate the parameter only from the best fitted model.
```{r}
# we keep the list just for the sake of simplicity as all parameters are stored in list (each element corresponding to a candidate model). However, notice that we only estimate parameters for the best model ("no prey effect")
effectlist<-c("poachers performance", "no prey effect", "prey counteracting behaviour", "spatial effects of ranger on poachers", "temporal effects of ranger on poachers", "space", "time cov", "both", "both delay")
npar<-vector(mode="logical", length=length(effectlist))
AICc<-vector(mode="logical", length=length(effectlist))
devModel3<-vector(mode="logical", length=length(effectlist))
mle_epsilonB<-list()
mle_epsilonA<-list()
mle_gammaAB<-list()
mle_gammaB<-list()
mle_gammaA<-list()
mle_epsilonAB<-list()
mle_trans42<- list()
mle_nuA<- list()
mle_omegaAB<-list()
mle_trans12<- list()
mle_etaA<- list()
mle_gammaAB<-list()
mle_trans43<- list()
mle_nuB<- list()
mle_omegaBA<- list()
mle_trans13<- list()
mle_etaB<- list()
e<-0
for(P_effects in effectlist)
{
e<-e+1
set.seed(7)
R = nrow(patchocc) # number of sites
n.states <- 4 # nb states
n.obs <- 4 # nb events
n.primary <- length(primary) # nb primary occasions
n.secondary <- length(secondary) # nb secondary occasions
J <- n.secondary
N <- n.primary * n.secondary
K <- n.primary
# binit = b[1:npar[e]]
#now reshape array in matrix with secondary occ within primary occ:
obs = matrix(NA,nrow=R,ncol=n.primary*n.secondary)
count = 1
for (i in 1:n.primary){
for (j in 1:n.secondary){
obs[,count] <- patchocc[,i,j]
count = count+1
}
}
# primary and secondary occasions
primaryseq = seq(J,J*K,by=J)
secondaryseq = 1:(J*K)
eff = rep(1,R) # nb sites with this particular history
#coveff<- patreffort
garb = obs[,1] # initial states
data = t(obs) # transpose
binit<-runif(32)
res = optim(binit,dev_2spocc_dyn3,NULL, data,eff, tempcov, garb,R,primaryseq,secondaryseq,n.states, P_effects, method="BFGS",control=list(trace=0, REPORT=1), hessian = FALSE)
dev<-res$value
b = res$par
checkpar<-b-binit
devModel3[e]<-dev
if(P_effects=="no prey effect")
hessianfinal<-optimHess(b,dev_2spocc_dyn3,NULL, data,eff,tempcov, garb,R,primaryseq,secondaryseq,n.states, P_effects, control=list(trace=0, REPORT=1))
npar[e]<-length(checkpar[-c(which(checkpar==0))])
AICc[e]<- 2*npar[e] + 2*dev + (2*npar[e]^2 + 2*npar[e])/(R-npar[e]-1)
if(P_effects=="no prey effect")
{
bbest <- res$par
mle_psiB <- 1/(1+exp(-(b[1])))
mle_psiAb<- 1/(1+exp(-(b[2])))
mle_psiAB <- 1/(1+exp(-(b[2])))
ResultEffect <- EffectsTransition(P_effects,b)
mle_epsilonAB[[e]]<- ResultEffect[[1]]
mle_trans42[[e]]<- ResultEffect[[2]]
mle_nuA[[e]]<- ResultEffect[[3]]
mle_omegaAB[[e]]<- ResultEffect[[4]]
mle_trans12[[e]]<- ResultEffect[[5]]
mle_etaA[[e]]<- ResultEffect[[6]]
mle_gammaAB[[e]]<- ResultEffect[[7]]
mle_trans43[[e]]<- ResultEffect[[8]]
mle_nuB[[e]]<- ResultEffect[[9]]
mle_omegaBA[[e]]<- ResultEffect[[10]]
mle_trans13[[e]]<- ResultEffect[[11]]
mle_etaB[[e]]<- ResultEffect[[12]]
mle_epsilonB[[e]] = mle_epsilonAB[[e]] + mle_trans42[[e]]
mle_epsilonA[[e]] = mle_epsilonAB[[e]] + mle_trans43[[e]]
mle_gammaA[[e]] = mle_gammaAB[[e]] + mle_trans12[[e]]
mle_gammaB[[e]] = mle_gammaAB[[e]] + mle_trans13[[e]]
mle_pB <-matrix(0, nrow=R, ncol=N)
mle_pAb <-matrix(0, nrow=R, ncol=N)
mle_pAB <-matrix(0, nrow=R, ncol=N)