###########################################################################################################################

## Graydon McKee
## Updated info with 2018 and 2019 Walleye for Manuscript
## Apr 2020

###########################################################################################################################

rm(list = ls())

## Read in acoustic delemetry data from May 2016 to November 2019 

Detect<-Full16_19_BBWAT_detections

## Number of fish detected north of Bent Island at any point

North<-subset(Detect, Detect$glatos_array=="BSR" | Detect$glatos_array=="WOR" | Detect$glatos_array=="HUC" | 
                Detect$glatos_array=="GIS" | Detect$glatos_array=="GRI" | Detect$glatos_array=="HUR" | 
                Detect$glatos_array=="NOR"| Detect$glatos_array=="SCI" | Detect$glatos_array=="SPG" | 
                Detect$glatos_array=="SSA")
North<-North[!(North$station=="SSA-72" | North$station=="SSA-73" | North$station=="SSA-74" | North$station=="SSA-75" | 
               North$station=="SSA-76" | North$station=="SSA-69" | North$station=="SSA-70" | North$station=="SSA-71"),]

length(unique(North$animal_id))

## Number of fish at or beyond EDI

Far<-subset(Detect, Detect$glatos_array=="EDI" | Detect$glatos_array=="SIP" | Detect$glatos_array=="BLP" | 
              Detect$glatos_array=="BAE" | Detect$glatos_array=="CAP" | Detect$glatos_array=="SAW" | 
              Detect$glatos_array=="SQB")

length(unique(Far$animal_id))

## Peninsular Gates

Pen<-subset(Detect, Detect$glatos_array=="SIP" | Detect$glatos_array=="BLP")
length(unique(Pen$animal_id))

SIP<-subset(Pen, Pen$glatos_array=="SIP")
length(unique(SIP$animal_id))
BLP<-subset(Pen, Pen$glatos_array=="BLP")
length(unique(BLP$animal_id))

################################################

## Fish detected in 2016

D2016<-subset(Detect,Detect$detection_timestamp_utc>as.numeric(as.POSIXct('2016-01-01',tz='GMT',format='%Y-%m-%d')) & 
                Detect$detection_timestamp_utc<as.numeric(as.POSIXct('2017-01-01',tz='GMT',format='%Y-%m-%d')))

## Fish detected in 2017

D2017<-subset(Detect,Detect$detection_timestamp_utc>as.numeric(as.POSIXct('2017-01-01',tz='GMT',format='%Y-%m-%d')) & 
                Detect$detection_timestamp_utc<as.numeric(as.POSIXct('2018-01-01',tz='GMT',format='%Y-%m-%d')))

## Fish detected in 2018

D2018<-subset(Detect,Detect$detection_timestamp_utc>as.numeric(as.POSIXct('2018-01-01',tz='GMT',format='%Y-%m-%d')) & 
                Detect$detection_timestamp_utc<as.numeric(as.POSIXct('2019-01-01',tz='GMT',format='%Y-%m-%d')))

## Fish detected in 2019

D2019<-subset(Detect,Detect$detection_timestamp_utc>as.numeric(as.POSIXct('2019-01-01',tz='GMT',format='%Y-%m-%d')) & 
                Detect$detection_timestamp_utc<as.numeric(as.POSIXct('2020-01-01',tz='GMT',format='%Y-%m-%d')))

## Number of fish detected each year

length(unique(D2016$animal_id))
length(unique(D2017$animal_id))
length(unique(D2018$animal_id))
length(unique(D2019$animal_id))

## Number of fish detected at various gates in each year

## 2016

D16.BEI<-subset(D2016,D2016$glatos_array=="BEI")
D16.GEP<-subset(D2016,D2016$glatos_array=="GEP")
D16.EDI<-subset(D2016,D2016$glatos_array=="EDI")
D16.SIP<-subset(D2016,D2016$glatos_array=="SIP")
D16.BLP<-subset(D2016,D2016$glatos_array=="BLP")
D16.PEN<-subset(D2016,D2016$glatos_array=="SIP" | D2016$glatos_array=="BLP")

length(unique(D16.BEI$animal_id))
length(unique(D16.GEP$animal_id))
length(unique(D16.EDI$animal_id))
length(unique(D16.SIP$animal_id))
length(unique(D16.BLP$animal_id))
length(unique(D16.PEN$animal_id))

## 2017

D17.BEI<-subset(D2017,D2017$glatos_array=="BEI")
D17.GEP<-subset(D2017,D2017$glatos_array=="GEP")
D17.EDI<-subset(D2017,D2017$glatos_array=="EDI")
D17.SIP<-subset(D2017,D2017$glatos_array=="SIP")
D17.BLP<-subset(D2017,D2017$glatos_array=="BLP")
D17.PEN<-subset(D2017,D2017$glatos_array=="SIP" | D2017$glatos_array=="BLP")

length(unique(D17.BEI$animal_id))
length(unique(D17.GEP$animal_id))
length(unique(D17.EDI$animal_id))
length(unique(D17.SIP$animal_id))
length(unique(D17.BLP$animal_id))
length(unique(D17.PEN$animal_id))

## 2018

D18.BEI<-subset(D2018,D2018$glatos_array=="BEI")
D18.GEP<-subset(D2018,D2018$glatos_array=="GEP")
D18.EDI<-subset(D2018,D2018$glatos_array=="EDI")
D18.SIP<-subset(D2018,D2018$glatos_array=="SIP")
D18.BLP<-subset(D2018,D2018$glatos_array=="BLP")
D18.PEN<-subset(D2018,D2018$glatos_array=="SIP" | D2018$glatos_array=="BLP")

length(unique(D18.BEI$animal_id))
length(unique(D18.GEP$animal_id))
length(unique(D18.EDI$animal_id))
length(unique(D18.SIP$animal_id))
length(unique(D18.BLP$animal_id))
length(unique(D18.PEN$animal_id))

## 2019

D19.BEI<-subset(D2019,D2019$glatos_array=="BEI")
D19.GEP<-subset(D2019,D2019$glatos_array=="GEP")
D19.EDI<-subset(D2019,D2019$glatos_array=="EDI")
D19.SIP<-subset(D2019,D2019$glatos_array=="SIP")
D19.BLP<-subset(D2019,D2019$glatos_array=="BLP")
D19.PEN<-subset(D2019,D2019$glatos_array=="SIP" | D2019$glatos_array=="BLP")

length(unique(D19.BEI$animal_id))
length(unique(D19.GEP$animal_id))
length(unique(D19.EDI$animal_id))
length(unique(D19.SIP$animal_id))
length(unique(D19.BLP$animal_id))
length(unique(D19.PEN$animal_id))

## All years

Detect.BEI<-subset(Detect,Detect$glatos_array=="BEI")
Detect.GEP<-subset(Detect,Detect$glatos_array=="GEP")
Detect.EDI<-subset(Detect,Detect$glatos_array=="EDI")
Detect.SIP<-subset(Detect,Detect$glatos_array=="SIP")
Detect.BLP<-subset(Detect,Detect$glatos_array=="BLP")
Detect.PEN<-subset(Detect,Detect$glatos_array=="SIP" | Detect$glatos_array=="BLP")

length(unique(Detect.BEI$animal_id))
length(unique(Detect.GEP$animal_id))
length(unique(Detect.EDI$animal_id))
length(unique(Detect.SIP$animal_id))
length(unique(Detect.BLP$animal_id))
length(unique(Detect.PEN$animal_id))

length(unique(Detect$animal_id))

## Migratory and resident fish in each year

## Indicate if a fish was at a migratory or resident receiver

Detect$Mig<-ifelse((Detect$glatos_array=="EDI" | Detect$glatos_array=="SIP" | Detect$glatos_array=="BLP" | 
                     Detect$glatos_array=="BAE" | Detect$glatos_array=="CAP" | Detect$glatos_array=="SAW" | 
                     Detect$glatos_array=="SQB"),1,0)
unique(Detect$Mig)

## Fish detected in 2016

D2016<-subset(Detect,Detect$detection_timestamp_utc>as.numeric(as.POSIXct('2016-01-01',tz='GMT',format='%Y-%m-%d')) & 
                Detect$detection_timestamp_utc<as.numeric(as.POSIXct('2017-01-01',tz='GMT',format='%Y-%m-%d')))

## Fish detected in 2017

D2017<-subset(Detect,Detect$detection_timestamp_utc>as.numeric(as.POSIXct('2017-01-01',tz='GMT',format='%Y-%m-%d')) & 
                Detect$detection_timestamp_utc<as.numeric(as.POSIXct('2018-01-01',tz='GMT',format='%Y-%m-%d')))

## Fish detected in 2018

D2018<-subset(Detect,Detect$detection_timestamp_utc>as.numeric(as.POSIXct('2018-01-01',tz='GMT',format='%Y-%m-%d')) & 
                Detect$detection_timestamp_utc<as.numeric(as.POSIXct('2019-01-01',tz='GMT',format='%Y-%m-%d')))

## Fish detected in 2019

D2019<-subset(Detect,Detect$detection_timestamp_utc>as.numeric(as.POSIXct('2019-01-01',tz='GMT',format='%Y-%m-%d')) & 
                Detect$detection_timestamp_utc<as.numeric(as.POSIXct('2020-01-01',tz='GMT',format='%Y-%m-%d')))

## 2016 Migratory or Resident

M16<-tapply(D2016$Mig,D2016$animal_id,max)
M16

M16.d<-data.frame(Fish=names(M16),M16=M16)

## 2017 Migratory or Resident

M17<-tapply(D2017$Mig,D2017$animal_id,max)
M17

M17.d<-data.frame(Fish=names(M17),M17=M17)

## 2018 Migratory or Resident

M18<-tapply(D2018$Mig,D2018$animal_id,max)
M18

M18.d<-data.frame(Fish=names(M18),M18=M18)

## Merge all years to see what fish were migratory and resident in each

Migration<-merge(M16.d,M17.d,by="Fish", all=TRUE)
Migration<-merge(Migration,M18.d,by="Fish", all=TRUE)

## Add fish length to this table

## Get unique fish with lengths

Bio<-Detect[!duplicated(Detect$animal_id),]
Bio<-Bio[,c(1,17)]

## Change column name to match migration

colnames(Bio) <- c("Fish", "length_m")

## Add the lengths

Migration2<-merge(Migration,Bio, by="Fish", all.x = TRUE)

## Write to .csv so you can find this later

write.csv(Migration2,file = "Migration_Repeat_Length.csv")



############################################################################################


## Secchi Disk Plot

## Import Secchi Data (SecchiR)

## Number Months for Ordering

SecchiR$Mn<-rep(1:5, each=4)

S.A<-subset(SecchiR,SecchiR$Location=="A")
S.B<-subset(SecchiR,SecchiR$Location=="B")
S.C<-subset(SecchiR,SecchiR$Location=="C")
S.D<-subset(SecchiR,SecchiR$Location=="D")

plot(S.A$`Secchi depth (m)`~S.A$Mn,
     ylim=c(0,9),
     pch=18, cex=2,
     bty="l", cex.lab=1.5, cex.axis=1.5,
     xaxt='n', xlab="Monthly Occasion", ylab="Secchi Depth (m)", las=1)
axis(1, at=c(1:5), labels=c("MJ","JJ","JA","AS","SO"), cex.axis=1.5)

points(S.B$`Secchi depth (m)`~S.B$Mn, pch=15, col=2, cex=2)
#points(S.C$`Secchi depth (m)`~S.C$Mn, pch=16, col=3, cex=2) #TOHA data for state C does not exist
points(S.D$`Secchi depth (m)`~S.D$Mn, pch=17, col=4, cex=2)

lines(S.A$Mn,S.A$`Secchi depth (m)`,lty=1,lwd=3, col=1)
lines(S.B$Mn,S.B$`Secchi depth (m)`,lty=2,lwd=3, col=2)
#lines(S.C$Mn,S.C$`Secchi depth (m)`,lty=3,lwd=3, col=3)
lines(S.D$Mn,S.D$`Secchi depth (m)`,lty=4,lwd=3, col=4)

legend(1,9,legend=c("A","B","D"), pch=c(18,15,17), lty=c(1,2,4), col=c(1,2,4), cex=1.4, title="State")

#########################################################################

## Look at the number of fish detected in each state during each monthly occasion from 2016-2019

## Remake the Mark table with all data from 2016-2019 (note: the gate deployment has changed so was not used in MARK models)

## Read in 2016-2019 acoustic telemetry data

BBWAT<-Full16_19_BBWAT_detections

##Capture location table

capture <- unique(BBWAT[,c('animal_id', 'utc_release_date_time', 'release_latitude', 'release_longitude', 'release_location')])

head(capture)

##Detections table

detect <- BBWAT[,c('animal_id', 'detection_timestamp_utc', 'deploy_long', 'deploy_lat','glatos_array')]

head(detect)

##Match capture column names to detection column names

names(capture)[2:5] <- c('detection_timestamp_utc', 'deploy_lat', 'deploy_long', 'glatos_array')

head(capture)

##Combine captue and detection tables (Capture-Mark-Recapture)

CMR<-rbind(detect,capture)

##Retain only detections from receivers used in both years (remove others here)

CMR<-CMR[ ! CMR$glatos_array %in% c('Black Sturgeon River - Above Camp 43','SQB','SAW','Hurkett Cove',
                                    'Pearl Harbour','COP','NOR','HUC','Delany Island','PER','Squaw Bay','CAP','BAE',
                                    'HUR','WRC','HAM','GIS','LPL','SPG','SSA','IRA','PEA','Hurkett'), ]


## Determine the range of dates in this data

rng <- trunc(range(CMR$detection_timestamp_utc), units='days')

# Create sequence of times at monthly/bi-weekly intervals.
tSeq <- seq(rng[1], rng[2], 2592000)

# Bin data by time interval and add new column to 'CMR'.
bin <- findInterval(CMR$detection_timestamp_utc, tSeq)
CMR$bin <- tSeq[bin]

## Bin by day

rng <- trunc(range(CMR$detection_timestamp_utc), units='days')

# Create sequence of times at daily intervals.
tSeq.day <- seq(rng[1], rng[2], 86400)

# Bin data by time interval and add new column to 'CMR'.
bin.day <- findInterval(CMR$detection_timestamp_utc, tSeq.day)
CMR$bin.day <- tSeq.day[bin.day]

# Check 'CMR'.
head(CMR)

fish <- unique(CMR$animal_id)

# Create a data frame with all combinations of animal and time bins.
allBins <- expand.grid(animal_id=fish, bin=tSeq)

CMR <- merge(CMR, allBins, by.x=c('animal_id', 'bin'), all=TRUE)

head(CMR)

##Remove detection timestamp, lat, snd long columns

CMR$detection_timestamp_utc<-NULL
CMR$deploy_long<-NULL
CMR$deploy_lat<-NULL

head(CMR)

##Remove repeated rows

CMR<-unique(CMR)

head(CMR)

######################################

States<-CMR

##Concatenate animal_id, bin, glatos_array

States$Concat<-paste(States$animal_id,States$bin,States$glatos_array,sep="|")

##Number of detections of each fish at each receiver per time bin

X<-table(States$Concat)
head(X)

##Make table of counts a data frame

Y<-data.frame(X)
head(Y)

##Remove duplicate Concats from States

States = States[!duplicated(States$Concat),]
head(States)

##Combine States and Y into binned capture frequency

names(Y)<-c("Concat","Freq")

CapFreq<-merge(States,Y,by="Concat")


##Assign numbers to gates

unique(CapFreq$glatos_array)

index<-c(NA,'BSR','WOR','BEI','GEP','EDI','SIP','BLP')

values<-c(NA,0,0,1,2,3,4,4)

CapFreq$Gate<-values[match(CapFreq$glatos_array,index)]

##Weighted gate value based on gate number and frequency

CapFreq$WGate<-(CapFreq$Freq*CapFreq$Gate)

##Change CapFreq to new object in case of error

Cap1<-CapFreq

##Concatenate animal_id and bin

Cap1$AnBin<-paste(Cap1$animal_id,Cap1$bin,sep="|")

##Add WeightAvg column with NA

Cap1["WeightAvg"]<-NA

##Sum gates and frequency for each fish in each bin

WGate.split <- split(Cap1$WGate, Cap1$AnBin)
head(WGate.split)

SumGate <- sapply(WGate.split, sum)
head(SumGate)

Freq.split<-split(Cap1$Freq,Cap1$AnBin)
head(Freq.split)

SumFreq<-sapply(Freq.split,sum)
head(SumFreq)

##Create new table with sum gates and sum frequency

Cap2<-data.frame(SumFreq,SumGate)
head(Cap2)

##Calculate weighted average

Cap2$W.Avg<-Cap2$SumGate/Cap2$SumFreq

Cap3<-Cap2

##Add animal_id and bin concat
Cap3$FishBin<-unique(Cap1$AnBin)

##Split animal_id and bin 

FishBin.Split<-strsplit(Cap3$FishBin, "|", fixed = TRUE)
head(FishBin.Split)

str(FishBin.Split)

##subset lists 

Fish<-sapply(FishBin.Split, function(x){x[[1]]})
Bin<-sapply(FishBin.Split, function(x){x[[2]]})

##Add to Cap3

Cap3$Fish.No<-Fish
Cap3$Bin<-Bin

##Turn weighted averages for states in lettered states (0 for NA)

W.Avg<-Cap3$W.Avg

head(W.Avg)

T<-ifelse(W.Avg<=1,"A",
          ifelse(W.Avg>1 & W.Avg<=2,"B",
                 ifelse(W.Avg>2 & W.Avg<=3,"C",
                        ifelse(W.Avg>3 & W.Avg<=4,"D",
                               ifelse(is.na(W.Avg),"0","9")))))
head(T)

T[is.na(T)] <- 0

##Add lettered states to table

Cap3$States<-T

MARK1<-Cap3

##############

Encounters<-tapply(MARK1$Fish.No,list(MARK1_2020$Bin,MARK1_2020$States), length)

Encounter <- data.frame(t(Encounters))

Encounter.m<-data.matrix(Encounter)

Encounter.m<-Encounter.m[,-c(31:42)]

# Get the stacked barplot
par(mar = c(5.1, 4.1, 4.1, 7.5))

barplot(Encounter.m, 
        col=c("black","#0232D4","darkgreen","#FF0B0B","grey10") , 
        angle=c(45,0,45,0,135,0), density=c(1000,25,50,50,50),lwd=0.000001,
        border="white", 
        space=0.04, 
        font.axis=2, 
        xlab="Month", ylab="Number of Walleye", cex.lab = 1.5,
        ylim=c(0,200),
        xaxt='n', las=1)

abline(h=0)

axis(1, at=c(2.6,5.7,8.85,11.95,15.1,18.2,21.3,24.5,27.6,30.65), labels=F)

text(x=c(2.6,5.7,8.85,11.95,15.1,18.2,21.3,24.5,27.6,30.65), y=-15, labels=c("JA 2016", "ON 2016","JF 2017","AM 2017","JA 2017",
                                                                 "ON 2017","JF 2018","AM 2018","JA 2018","ON 2018"), srt=30, xpd=NA)

legend(31.5, 130, legend=c("Not Detected","A","B","C","D"), fill=c("black","#0232D4","darkgreen","#FF0B0B","grey10"),
       angle=c(45,0,45,0,135,0), density=c(1000,25,50,50,50), title="State", xpd=NA,
       cex=1.1)

rect(6.3,0,11.38,170,col="light grey")

rect(18.8,0,23.9,170,col="light grey")








