library("raster")
library(rgdal)
library(sp)
library(mapdata)
library(adehabitatHR)
library(rgeos)
library(tidyverse)
library(ggplot2)
library(ggspatial)
library(sf)
library(rnaturalearth)
library(rnaturalearthdata)

#############
#Select Domain
#############
#read in appropriate shapefiles
setwd("~/Enviornmental_Data/USmap")
noestuaries<-readOGR(".","no_estuaries_wholeeastcoast")#whole east coast with no estuaries
noestuaries<-spTransform(noestuaries,"+init=epsg:4326")
useezsimple<-readOGR(".","US_State_Fed_waters_simple_dissolve")#us eez but also includes areas inland of state waters line
useezsimple<-spTransform(useezsimple,"+init=epsg:4326")
eastcoastmask<-readOGR(".","east_coast_shp_to_mask_eez")
eastcoastmask<-spTransform(eastcoastmask,"+init=epsg:4326")
useez<-readOGR(".","US_Fed_Waters")
useez<-spTransform(useez,"+init=epsg:4326")
useez<-crop(useez,eastcoastmask)#for later

#remove useez too far west (gulf of mexico)
useezsimple<-crop(useezsimple,eastcoastmask)

setwd("~/Enviornmental_Data/Mid_Atlantic_closure")
midclose<-readOGR(".","MIDClosure")
midclose<-spTransform(midclose,"+proj=longlat +datum=WGS84 +no_defs")


#Domain defined by 95% KUD of fishing area (All sets occur inside eez so no need to use eez as a domain)
setwd("~/BLLOP_Data")
ds_data<-read.csv("ds_bll_catch_full.csv")
ds_data$BINOMIAL<-ifelse(ds_data$Catch>0,1,0)
#remove data west of florida
ds_data<-ds_data[which(ds_data$BEGIN_SET_LONGITUDE> -80.5 | (ds_data$BEGIN_SET_LATITUDE>26.7 & ds_data$BEGIN_SET_LONGITUDE> -81.5)),]#need to do this because unlike POP data, some BLL sets occur west of -80.5 but are still in atlantic (e.g. off of jacksonville)
ds_data$BEGIN_SET_DATE_TIME<-as.POSIXct(ds_data$BEGIN_SET_DATE_TIME,format="%Y-%m-%d %H:%M:%S",tz="America/New_York")
ds_data$MONTH<-as.factor(strftime(ds_data$BEGIN_SET_DATE_TIME_UTC,format="%m",tz="America/New_York"))
ds_data$YEAR<-as.factor(strftime(ds_data$BEGIN_SET_DATE_TIME_UTC,format="%Y",tz="America/New_York"))
setlocs<-data.frame(lon=ds_data$BEGIN_SET_LONGITUDE,lat=ds_data$BEGIN_SET_LATITUDE)
coordinates(setlocs)<- ~lon + lat 
#The smoothing factor (h) is the distance over which a data point influences the utlization distribution. A larger h results in more smoothing and increases home range size estimates.
fisherykud<-kernelUD(setlocs,h=1.5) #after talking with tobey and steve like k=1.5 and 95% best for our purposes, it makes the area continuous and removes some outliers
fisherykud95<-getverticeshr(fisherykud, percent = 95)
proj4string(setlocs)<-CRS("+init=epsg:4326")#sets it to lat-long
proj4string(fisherykud95)<-CRS("+init=epsg:4326")#sets it to lat-long

#need to remove fisherykud95 that doesn't occur inside eez
fisherykud95<-crop(fisherykud95,useezsimple)
#removes fisherykud95 that occurs inside estuaries (e.g. pamlico sound)
fisherykud95<-fisherykud95-noestuaries
#removes fisherykud95 that occurs in deeper than 500m
setwd("~/Enviornmental_Data/Prediction_Rasters/BLLOP_rasters/raster2016_2018")
depth<-raster("depthraster16_18_hycom.tif")
depth[which(values(depth)> -500)]<-NA
useezsimplebuf<-raster::buffer(useezsimple,width=0.5) #need to do this so when I mask further down it completely covers entire fishery domain and beyond (just in case), was leaving small areas where fishery domain extended a little further east than depth polygon
depthfishery<-mask(depth,useezsimplebuf)
depthfisherypoly<-rasterToPolygons(depthfishery,na.rm=T,dissolve=T)

fisherykud95<-fisherykud95-depthfisherypoly

#there ends up being a tiny section of mid closure that gets cut off in fishery domain when limit it to 500m
#want to include that section still so add midclose to domain and then dissolve them together
fisherykud95<-fisherykud95+midclose
fisherykud95<-aggregate(fisherykud95,dissolve=T) #saved as fisherykud95_bllop.shp

plot(fisherykud95)
plot(setlocs,pch=".",add=T)


#############
#Check distribution of fishery
#############
#plot the fishery each year
#already ran this, no need to run again
setwd("~/BLLOP_Data")
plot.window(ylim=c(23,39),xlim=c(-81.5, -67))
pdf(paste("Yearly_bll_hauls_locs","pdf",sep="."),width=10,height=10,onefile=TRUE)
for(i in 2005:2019){
  maps::map('world', ylim=c(23,39),xlim=c(-81.5, -67), fill=TRUE, col="tan")
  plot(setlocs[ds_data$YEAR==i],add=T,pch=".",cex=2,col="blue")
  text(-78,30,paste(i))
}
dev.off()

#looks like fishery is pretty consistent in it's locations throughout the whole time period (2005-2019)
#plot all sets
plot.window(ylim=c(23,39),xlim=c(-81.5, -67))
maps::map('world', ylim=c(23,39),xlim=c(-81.5, -67), fill=TRUE, col="tan")
plot(setlocs,add=T,pch=".",cex=2,col="blue")



#################
#Prel calculation
#################
setwd("~/BLLOP_Data/Results/ds/R_raster_outputs")
exampraster<-raster("dsJanPPP.tif")

#masks areas outside of fishery domain and used if overlap among species is desired
PrelFunc<-function(species=NA,probs=NA,mask=NULL,wd=NA){
  #read in species rasters
  #wd<-paste("~/POP_Data/Results",species,"R_raster_outputs",sep="/")
  setwd(wd)
  speciesJan<-raster(paste(species,"JanPPP.tif",sep=""))
  speciesFeb<-raster(paste(species,"FebPPP.tif",sep=""))
  speciesMar<-raster(paste(species,"MarPPP.tif",sep=""))
  speciesApr<-raster(paste(species,"AprPPP.tif",sep=""))
  speciesMay<-raster(paste(species,"MayPPP.tif",sep=""))
  speciesJun<-raster(paste(species,"JunPPP.tif",sep=""))
  speciesJul<-raster(paste(species,"JulPPP.tif",sep=""))
  speciesAug<-raster(paste(species,"AugPPP.tif",sep=""))
  speciesSep<-raster(paste(species,"SepPPP.tif",sep=""))
  speciesOct<-raster(paste(species,"OctPPP.tif",sep=""))
  speciesNov<-raster(paste(species,"NovPPP.tif",sep=""))
  speciesDec<-raster(paste(species,"DecPPP.tif",sep=""))
  
  #select fishery domain as mask
  speciesJan<-mask(speciesJan,mask=mask)
  speciesFeb<-mask(speciesFeb,mask=mask)
  speciesMar<-mask(speciesMar,mask=mask)
  speciesApr<-mask(speciesApr,mask=mask)
  speciesMay<-mask(speciesMay,mask=mask)
  speciesJun<-mask(speciesJun,mask=mask)
  speciesJul<-mask(speciesJul,mask=mask)
  speciesAug<-mask(speciesAug,mask=mask)
  speciesSep<-mask(speciesSep,mask=mask)
  speciesOct<-mask(speciesOct,mask=mask)
  speciesNov<-mask(speciesNov,mask=mask)
  speciesDec<-mask(speciesDec,mask=mask)
  
  #find upper quantile for all outputs values for all months combined
  #think this makes more sense we are assessing the best time periods and the best locations for closed areas, thus when we assess months they need to be compared apples to apples
  #ex. probs=.75 is the value where all larger values are in the top 25% quantile, finds that quantile value
  quant<-quantile(c(values(speciesJan),values(speciesFeb),values(speciesMar),values(speciesApr),
                    values(speciesMay),values(speciesJun),values(speciesJul),values(speciesAug),
                    values(speciesSep),values(speciesOct),values(speciesNov),values(speciesDec)),probs=probs,na.rm=T)
  
  #finds upper quantile value for each month
  #ex. probs=.75 is the value where all larger values are in the top 25% quantile, finds that quantile value
  #Janquant<-quantile(values(speciesJan),probs=probs,na.rm=T)
  #Febquant<-quantile(values(speciesFeb),probs=probs,na.rm=T)
  #Marquant<-quantile(values(speciesMar),probs=probs,na.rm=T)
  #Aprquant<-quantile(values(speciesApr),probs=probs,na.rm=T)
  #Mayquant<-quantile(values(speciesMay),probs=probs,na.rm=T)
  #Junquant<-quantile(values(speciesJun),probs=probs,na.rm=T)
  #Julquant<-quantile(values(speciesJul),probs=probs,na.rm=T)
  #Augquant<-quantile(values(speciesAug),probs=probs,na.rm=T)
  #Sepquant<-quantile(values(speciesSep),probs=probs,na.rm=T)
  #Octquant<-quantile(values(speciesOct),probs=probs,na.rm=T)
  #Novquant<-quantile(values(speciesNov),probs=probs,na.rm=T)
  #Decquant<-quantile(values(speciesDec),probs=probs,na.rm=T)
  
  #any probaility values under top x% replaces value with NA
  #ex. if probs =.75 than any values lower than the top 25% would turn to NA
  speciesJan[speciesJan<quant]<-NA
  speciesFeb[speciesFeb<quant]<-NA
  speciesMar[speciesMar<quant]<-NA
  speciesApr[speciesApr<quant]<-NA
  speciesMay[speciesMay<quant]<-NA
  speciesJun[speciesJun<quant]<-NA
  speciesJul[speciesJul<quant]<-NA
  speciesAug[speciesAug<quant]<-NA
  speciesSep[speciesSep<quant]<-NA
  speciesOct[speciesOct<quant]<-NA
  speciesNov[speciesNov<quant]<-NA
  speciesDec[speciesDec<quant]<-NA
  
  #combine trimmed raster values (probabilities) into 1 dataset with each column a different month
  speciesvals<-data.frame(Jan=values(speciesJan),Feb=values(speciesFeb),Mar=values(speciesMar),Apr=values(speciesApr),
                          May=values(speciesMay),Jun=values(speciesJun),Jul=values(speciesJul),Aug=values(speciesAug),
                          Sep=values(speciesSep),Oct=values(speciesOct),Nov=values(speciesNov),Dec=values(speciesDec))
  
  #sum across months at each cell (part of denominator)
  speciesvals$MonthSum<-rowSums(speciesvals,na.rm=T)
  #sum over all sum months (final denominator)
  species_den<-sum(speciesvals$MonthSum,na.rm = T)
  
  #creates Prel for each given species
  Prelspecies<-matrix(NA,nrow = nrow(speciesvals),ncol=12)
  for(j in 1:12){
    Prelspecies[,j]<-speciesvals[,j]/species_den
  }
  Prelspecies<-data.frame(Prelspecies)
  names(Prelspecies)<-names(speciesvals)[1:12]
  
  speciesprobstack<-stack(speciesJan,speciesFeb,speciesMar,speciesApr,speciesMay,speciesJun,
                          speciesJul,speciesAug,speciesSep,speciesOct,speciesNov,speciesDec)
  
  return(list(Prelspecies=Prelspecies,speciesprobstack=speciesprobstack))
}


#kud 95% of fishing area
Preldskud95<-PrelFunc(species="ds",probs=0.75,mask=fisherykud95,wd="~/BLLOP_Data/Results/ds/R_raster_outputs")
Prelshhkud95<-PrelFunc(species="shh",probs=0.75,mask=fisherykud95,wd="~/BLLOP_Data/Results/shh/R_raster_outputs")
Prelsbkud95<-PrelFunc(species="sb",probs=0.75,mask=fisherykud95,wd="~/BLLOP_Data/Results/sb/R_raster_outputs")

#rasters of initial model output core area is same as rasters of results of equation 1 in White et al. 2019, just scale is different, but map is identical

######################
#Prel Overlap function
######################
#remainder of overlap function, adapted from White et al. 2019
PrelOverlapFunc<-function(Prel1=NA,Prel2=NA,Prel3=NA,Prel4=NA){
  #multiple species 1 by species 2 to get numerator of equation 3
  overlapnum<-matrix(NA,nrow = nrow(Prel1),ncol=12)
  if(class(Prel3)=="numeric" & class(Prel4)=="numeric"){
    for(j in 1:12){
      overlapnum[,j]<-Prel1[,j]*Prel2[,j]
    }
  }else if(class(Prel3)!="numeric" & class(Prel4)=="numeric"){
    for(j in 1:12){
      overlapnum[,j]<-Prel1[,j]*Prel2[,j]*Prel3[,j]
    }
  }else{
    for(j in 1:12){
      overlapnum[,j]<-Prel1[,j]*Prel2[,j]*Prel3[,j]*Prel4[,j]
    }
  }
  overlapnum<-data.frame(overlapnum)
  names(overlapnum)<-names(Prel1)
  
  #sum across months at each cell (part of denominator)
  overlapnum$MonthSum<-rowSums(overlapnum,na.rm=T)
  #sum over all sum months (final denominator)
  overlapden<-sum(overlapnum$MonthSum,na.rm = T)
  
  #creates Prel for overlap
  Preloverlap<-matrix(NA,nrow = nrow(Prel1),ncol=12)
  for(j in 1:12){
    Preloverlap[,j]<-log(overlapnum[,j]/overlapden)
  }
  Preloverlap<-data.frame(Preloverlap)
  names(Preloverlap)<-names(Prel1)
  
  return(Preloverlap=Preloverlap)
  
}

#provides a dataframe of overlap of species each month

#kud 95% of fishing area + eez
ds_shh_overlapkud95<-PrelOverlapFunc(Prel1=Preldskud95$Prelspecies,Prel2=Prelshhkud95$Prelspecies,Prel3=1,Prel4=1)
sb_shh_overlapkud95<-PrelOverlapFunc(Prel1=Prelsbkud95$Prelspecies,Prel2=Prelshhkud95$Prelspecies,Prel3=1,Prel4=1)
ds_sb_overlapkud95<-PrelOverlapFunc(Prel1=Preldskud95$Prelspecies,Prel2=Prelsbkud95$Prelspecies,Prel3=1,Prel4=1)
ds_sb_shh_overlapkud95<-PrelOverlapFunc(Prel1=Preldskud95$Prelspecies,Prel2=Prelsbkud95$Prelspecies,Prel3=Prelshhkud95$Prelspecies,Prel4=1)#when we use 3 species using this method it actually does determined overlap of 3 species



##########################
#Make raster and shapefile
##########################
#first makes monthly rasters from dataframe, then makes rasterstack and then converts rasters to monthly shapefiles of species overlap
RastersToShapfiles<-function(Preloverlap=NA){
  #Turn back into raster
  overlapJanr<-setValues(exampraster,NA)
  overlapJanr[1:553938]<-Preloverlap$Jan
  names(overlapJanr)<-"Jan"
  overlapFebr<-setValues(exampraster,NA)
  overlapFebr[1:553938]<-Preloverlap$Feb
  names(overlapFebr)<-"Feb"
  overlapMarr<-setValues(exampraster,NA)
  overlapMarr[1:553938]<-Preloverlap$Mar
  names(overlapMarr)<-"Mar"
  overlapAprr<-setValues(exampraster,NA)
  overlapAprr[1:553938]<-Preloverlap$Apr
  names(overlapAprr)<-"Apr"
  overlapMayr<-setValues(exampraster,NA)
  overlapMayr[1:553938]<-Preloverlap$May
  names(overlapMayr)<-"May"
  overlapJunr<-setValues(exampraster,NA)
  overlapJunr[1:553938]<-Preloverlap$Jun
  names(overlapJunr)<-"Jun"
  overlapJulr<-setValues(exampraster,NA)
  overlapJulr[1:553938]<-Preloverlap$Jul
  names(overlapJulr)<-"Jul"
  overlapAugr<-setValues(exampraster,NA)
  overlapAugr[1:553938]<-Preloverlap$Aug
  names(overlapAugr)<-"Aug"
  overlapSepr<-setValues(exampraster,NA)
  overlapSepr[1:553938]<-Preloverlap$Sep
  names(overlapSepr)<-"Sep"
  overlapOctr<-setValues(exampraster,NA)
  overlapOctr[1:553938]<-Preloverlap$Oct
  names(overlapOctr)<-"Oct"
  overlapNovr<-setValues(exampraster,NA)
  overlapNovr[1:553938]<-Preloverlap$Nov
  names(overlapNovr)<-"Nov"
  overlapDecr<-setValues(exampraster,NA)
  overlapDecr[1:553938]<-Preloverlap$Dec
  names(overlapDecr)<-"Dec"
  
  overlapstack<-stack(overlapJanr,overlapFebr,overlapMarr,overlapAprr,overlapMayr,overlapJunr,
                      overlapJulr,overlapAugr,overlapSepr,overlapOctr,overlapNovr,overlapDecr)
  
  #create raster to eventually turn values to -1
  overlapJan1r<-overlapJanr
  overlapFeb1r<-overlapFebr
  overlapMar1r<-overlapMarr
  overlapApr1r<-overlapAprr
  overlapMay1r<-overlapMayr
  overlapJun1r<-overlapJunr
  overlapJul1r<-overlapJulr
  overlapAug1r<-overlapAugr
  overlapSep1r<-overlapSepr
  overlapOct1r<-overlapOctr
  overlapNov1r<-overlapNovr
  overlapDec1r<-overlapDecr
  
  #turn all value rasters to -1
  overlapJan1r[!is.na(overlapJan1r)]<- -1
  overlapFeb1r[!is.na(overlapFeb1r)]<- -1
  overlapMar1r[!is.na(overlapMar1r)]<- -1
  overlapApr1r[!is.na(overlapApr1r)]<- -1
  overlapMay1r[!is.na(overlapMay1r)]<- -1
  overlapJun1r[!is.na(overlapJun1r)]<- -1
  overlapJul1r[!is.na(overlapJul1r)]<- -1
  overlapAug1r[!is.na(overlapAug1r)]<- -1
  overlapSep1r[!is.na(overlapSep1r)]<- -1
  overlapOct1r[!is.na(overlapOct1r)]<- -1
  overlapNov1r[!is.na(overlapNov1r)]<- -1
  overlapDec1r[!is.na(overlapDec1r)]<- -1
  
  #convert all cells with values to shapefile
  overlapJanshp<-rasterToPolygons(overlapJan1r)
  overlapFebshp<-rasterToPolygons(overlapFeb1r)
  overlapMarshp<-rasterToPolygons(overlapMar1r)
  overlapAprshp<-rasterToPolygons(overlapApr1r)
  overlapMayshp<-rasterToPolygons(overlapMay1r)
  overlapJunshp<-rasterToPolygons(overlapJun1r)
  overlapJulshp<-rasterToPolygons(overlapJul1r)
  overlapAugshp<-rasterToPolygons(overlapAug1r)
  overlapSepshp<-rasterToPolygons(overlapSep1r)
  overlapOctshp<-rasterToPolygons(overlapOct1r)
  overlapNovshp<-rasterToPolygons(overlapNov1r)
  overlapDecshp<-rasterToPolygons(overlapDec1r)
  
  #make list of overlap shapefiles
  overlapshplist<-list(overlapJanshp,overlapFebshp,overlapMarshp,overlapAprshp,overlapMayshp,overlapJunshp,
                       overlapJulshp,overlapAugshp,overlapSepshp,overlapOctshp,overlapNovshp,overlapDecshp)
  
  return(list(overlapshplist=overlapshplist,overlapstack=overlapstack))  
}
#Ignore warnings, just means there is no overlap for a specific month
#provides shapefiles of species overlap each month and raster stack of species overlap


#kud 95% of fishing area
#ds shh overlap shapefiles
ds_shh_overlapspatialkud95<-RastersToShapfiles(Preloverlap=ds_shh_overlapkud95)
ds_shh_overlaprasterstackkud95<-ds_shh_overlapspatialkud95$overlapstack
ds_shh_overlapshplistkud95<-ds_shh_overlapspatialkud95$overlapshplist
rm(ds_shh_overlapspatialkud95)

#sb shh overlap shapefiles
sb_shh_overlapspatialkud95<-RastersToShapfiles(Preloverlap=sb_shh_overlapkud95)
sb_shh_overlaprasterstackkud95<-sb_shh_overlapspatialkud95$overlapstack
sb_shh_overlapshplistkud95<-sb_shh_overlapspatialkud95$overlapshplist
rm(sb_shh_overlapspatialkud95)

#ds shh overlap shapefiles
ds_sb_overlapspatialkud95<-RastersToShapfiles(Preloverlap=ds_sb_overlapkud95)
ds_sb_overlaprasterstackkud95<-ds_sb_overlapspatialkud95$overlapstack
ds_sb_overlapshplistkud95<-ds_sb_overlapspatialkud95$overlapshplist
rm(ds_sb_overlapspatialkud95)

#ds shh sb overlap shapefiles
ds_sb_shh_overlapspatialkud95<-RastersToShapfiles(Preloverlap=ds_sb_shh_overlapkud95)
ds_sb_shh_overlaprasterstackkud95<-ds_sb_shh_overlapspatialkud95$overlapstack
ds_sb_shh_overlapshplistkud95<-ds_sb_shh_overlapspatialkud95$overlapshplist
rm(ds_sb_shh_overlapspatialkud95)


#################
#Write shapefiles
#################

#for individual species
#kud 95% of fishing area
#make ds shapefile list
dsshplistkud95 = lapply(as.list(Preldskud95$speciesprobstack), rasterToPolygons)
#make shh shapefile list
shhshplistkud95 = lapply(as.list(Prelshhkud95$speciesprobstack), rasterToPolygons)
#make sb shapefile list
sbshplistkud95 = lapply(as.list(Prelsbkud95$speciesprobstack), rasterToPolygons)


#write list of polygons
writeShpList<-function(speciesnameslength=NA,species=NA,shplist=NA,path=NA,domain=NA){
  for (j in 1:speciesnameslength){
    writeOGR(unlist(shplist)[[j]], 
             dsn = path,
             layer = paste(species,names(unlist(shplist)[[j]]),domain,sep=""),
             driver = 'ESRI Shapefile',
             overwrite_layer = T) }
}
###for individual species
#kud 95% of fishing area
writeShpList(speciesnameslength=12,shplist = dsshplistkud95,path="~/BLLOP_Data/Results/overlap/species_shp",species=NULL,domain="kud95")
writeShpList(speciesnameslength=12,shplist = shhshplistkud95,path="~/BLLOP_Data/Results/overlap/species_shp",species=NULL,domain="kud95")
writeShpList(speciesnameslength=12,shplist = sbshplistkud95,path="~/BLLOP_Data/Results/overlap/species_shp",species=NULL,domain="kud95")#strange warnings about length of name, ignore

###for multi species overlap
#kud 95% of fishing area
writeShpList(speciesnameslength=12,shplist = ds_shh_overlapshplistkud95,path="~/BLLOP_Data/Results/overlap/ds_shh",species="ds_shh",domain="kud95")
writeShpList(speciesnameslength=12,shplist = ds_sb_overlapshplistkud95,path="~/BLLOP_Data/Results/overlap/ds_sb",species="ds_sb",domain="kud95")
writeShpList(speciesnameslength=12,shplist = sb_shh_overlapshplistkud95,path="~/BLLOP_Data/Results/overlap/sb_shh",species="sb_shh",domain="kud95")
writeShpList(speciesnameslength=12,shplist = ds_sb_shh_overlapshplistkud95,path="~/BLLOP_Data/Results/overlap/ds_sb_shh",species="ds_sb_shh",domain="kud95")



######
#plot maps of overlaps
######
#KUD (map of each species, no overlap)
setwd("~/BLLOP_Data/Results/overlap/overlap_maps")
monthnames<-c("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")
theme_set(theme_bw())
#https://www.r-spatial.org/r/2018/10/25/ggplot2-sf.html
midclosedata<- st_as_sf(midclose)
midclosedata$Id1<-as.factor("mc")
useezdata<-st_as_sf(useez)
fisherykuddata<-st_as_sf(fisherykud95)
fisherykuddata$ID<-"map"
for(i in 1:12){
  dsdata<-st_as_sf(aggregate(dsshplistkud95[[i]],dissolve=T)) %>% dplyr::mutate(DS = as.factor("DS"))
  shhdata<-st_as_sf(aggregate(shhshplistkud95[[i]],dissolve=T)) %>% dplyr::mutate(SHH = as.factor("SHH"))
  sbdata<-st_as_sf(aggregate(sbshplistkud95[[i]],dissolve=T)) %>% dplyr::mutate(SB = as.factor("SB"))
  
  world<-ne_countries(scale="medium",returnclass = "sf")
  ###SB
  mpsb<-ggplot(data=world) + 
    geom_sf(color="black",fill="tan") +
    coord_sf(xlim=c(-81.5, -67),ylim=c(23,39),expand=FALSE) +
    geom_sf(data = sbdata, aes(color = "SB", fill = "SB")) +
    geom_sf(data = midclosedata, aes(colour = "Id", fill = "Id"),size=1) +
    geom_sf(data = fisherykuddata, aes(colour = "ID", fill = "ID"),size=1) +
    geom_sf(data = useezdata, aes(color = "Jurisdicti", fill = "Jurisdicti")) +
    geom_sf(data = midclosedata, aes(color = "Id1", fill = "Id1")) + #had to do this to create a break between species and cbump and eez in legend
    scale_fill_manual(name = "",
                      values = c("Jurisdicti"="transparent","ID"="transparent","Id"="transparent","DS"="grey33","SHH"="purple","SB"="darkgoldenrod3","Id1"="transparent"),
                      guide = "legend",
                      breaks = c("SB", "SHH", "DS", "Id1", "Id","ID","Jurisdicti"),
                      labels = c("Jurisdicti"="U.S. EEZ","ID"="Fishery Domain","Id"="Mid Atlantic","DS"="DS","SHH"="SHH","SB"="SB","Id1"="")) +
    scale_color_manual(name = "",
                       values = c("Jurisdicti"="black","ID"="cyan3","Id"="green","DS"="grey33","SHH"="purple","SB"="darkgoldenrod3","Id1"="transparent"),
                       guide = "legend",
                       breaks = c("SB", "SHH", "DS", "Id1", "Id","ID","Jurisdicti"),
                       labels = c("Jurisdicti"="U.S. EEZ","ID"="Fishery Domain","Id"="Mid Atlantic","DS"="DS","SHH"="SHH","SB"="SB","Id1"="")) +
    theme(axis.title.x = element_blank(), panel.grid = element_blank())+
    theme(axis.title.y = element_blank())+
    theme(legend.key=element_rect(color=NA,fill=NA),legend.key.size = unit(0.5, "cm")) +
    coord_sf(xlim=c(-81.5, -67),ylim=c(23,39),expand=FALSE) +
    #annotate("text",x=-80,y=38.4,label="e",size=6) + #if I want to add letter in map
    theme(text = element_text(size = 13)) + #if I want to change size of text in map
    annotation_scale(location="br" ,width_hint=0.25,style="bar",unit_category="metric",text_cex=0.85) +
    annotation_north_arrow(location = "tl", which_north = "true", height=unit(0.75,"cm"),width=unit(0.6,"cm"),style = north_arrow_orienteering)
  
  ggsave(filename = paste(monthnames[i],"sbcore_kud95",".pdf",sep=""),plot=mpsb,width=8,height=6,units="in",dpi=300)
  ggsave(filename = paste("png",monthnames[i],"sbcore_kud95",".png",sep=""),plot=mpsb,width=8,height=6,units="in",dpi=300)
  
  ###DS
  mpds<-ggplot(data=world) + 
    geom_sf(color="black",fill="tan") +
    coord_sf(xlim=c(-81.5, -67),ylim=c(23,39),expand=FALSE) +
    geom_sf(data = dsdata, aes(color = "DS", fill = "DS")) +
    geom_sf(data = midclosedata, aes(colour = "Id", fill = "Id"),size=1) +
    geom_sf(data = fisherykuddata, aes(colour = "ID", fill = "ID"),size=1) +
    geom_sf(data = useezdata, aes(color = "Jurisdicti", fill = "Jurisdicti")) +
    geom_sf(data = midclosedata, aes(color = "Id1", fill = "Id1")) + #had to do this to create a break between species and cbump and eez in legend
    scale_fill_manual(name = "",
                      values = c("Jurisdicti"="transparent","ID"="transparent","Id"="transparent","DS"="grey33","SHH"="purple","SB"="darkgoldenrod3","Id1"="transparent"),
                      guide = "legend",
                      breaks = c("SB", "SHH", "DS", "Id1", "Id","ID","Jurisdicti"),
                      labels = c("Jurisdicti"="U.S. EEZ","ID"="Fishery Domain","Id"="Mid Atlantic","DS"="DS","SHH"="SHH","SB"="SB","Id1"="")) +
    scale_color_manual(name = "",
                       values = c("Jurisdicti"="black","ID"="cyan3","Id"="green","DS"="grey33","SHH"="purple","SB"="darkgoldenrod3","Id1"="transparent"),
                       guide = "legend",
                       breaks = c("SB", "SHH", "DS", "Id1", "Id","ID","Jurisdicti"),
                       labels = c("Jurisdicti"="U.S. EEZ","ID"="Fishery Domain","Id"="Mid Atlantic","DS"="DS","SHH"="SHH","SB"="SB","Id1"="")) +
    theme(axis.title.x = element_blank(), panel.grid = element_blank())+
    theme(axis.title.y = element_blank())+
    theme(legend.key=element_rect(color=NA,fill=NA),legend.key.size = unit(0.5, "cm")) +
    coord_sf(xlim=c(-81.5, -67),ylim=c(23,39),expand=FALSE) +
    #annotate("text",x=-80,y=38.4,label="d",size=6) + #if I want to add letter in map
    theme(text = element_text(size = 13)) + #if I want to change size of text in map
    annotation_scale(location="br" ,width_hint=0.25,style="bar",unit_category="metric",text_cex=0.85) +
    annotation_north_arrow(location = "tl", which_north = "true", height=unit(0.75,"cm"),width=unit(0.6,"cm"),style = north_arrow_orienteering)
  
  ggsave(filename = paste(monthnames[i],"dscore_kud95",".pdf",sep=""),plot=mpds,width=8,height=6,units="in",dpi=300)
  ggsave(filename = paste("png",monthnames[i],"dscore_kud95",".png",sep=""),plot=mpds,width=8,height=6,units="in",dpi=300)
  
  ###SHH
  mpshh<-ggplot(data=world) + 
    geom_sf(color="black",fill="tan") +
    coord_sf(xlim=c(-81.5, -67),ylim=c(23,39),expand=FALSE) +
    geom_sf(data = shhdata, aes(color = "SHH", fill = "SHH")) +
    geom_sf(data = midclosedata, aes(colour = "Id", fill = "Id"),size=1) +
    geom_sf(data = fisherykuddata, aes(colour = "ID", fill = "ID"),size=1) +
    geom_sf(data = useezdata, aes(color = "Jurisdicti", fill = "Jurisdicti")) +
    geom_sf(data = midclosedata, aes(color = "Id1", fill = "Id1")) + #had to do this to create a break between species and cbump and eez in legend
    scale_fill_manual(name = "",
                      values = c("Jurisdicti"="transparent","ID"="transparent","Id"="transparent","DS"="grey33","SHH"="purple","SB"="darkgoldenrod3","Id1"="transparent"),
                      guide = "legend",
                      breaks = c("SB", "SHH", "DS", "Id1", "Id","ID","Jurisdicti"),
                      labels = c("Jurisdicti"="U.S. EEZ","ID"="Fishery Domain","Id"="Mid Atlantic","DS"="DS","SHH"="SHH","SB"="SB","Id1"="")) +
    scale_color_manual(name = "",
                       values = c("Jurisdicti"="black","ID"="cyan3","Id"="green","DS"="grey33","SHH"="purple","SB"="darkgoldenrod3","Id1"="transparent"),
                       guide = "legend",
                       breaks = c("SB", "SHH", "DS", "Id1", "Id","ID","Jurisdicti"),
                       labels = c("Jurisdicti"="U.S. EEZ","ID"="Fishery Domain","Id"="Mid Atlantic","DS"="DS","SHH"="SHH","SB"="SB","Id1"="")) +
    theme(axis.title.x = element_blank(), panel.grid = element_blank())+
    theme(axis.title.y = element_blank())+
    theme(legend.key=element_rect(color=NA,fill=NA),legend.key.size = unit(0.5, "cm")) +
    coord_sf(xlim=c(-81.5, -67),ylim=c(23,39),expand=FALSE) +
    #annotate("text",x=-80,y=38.4,label="f",size=6) + #if I want to add letter in map
    theme(text = element_text(size = 13)) + #if I want to change size of text in map
    annotation_scale(location="br" ,width_hint=0.25,style="bar",unit_category="metric",text_cex=0.85) +
    annotation_north_arrow(location = "tl", which_north = "true", height=unit(0.75,"cm"),width=unit(0.6,"cm"),style = north_arrow_orienteering)
  
  ggsave(filename = paste(monthnames[i],"shhcore_kud95",".pdf",sep=""),plot=mpshh,width=8,height=6,units="in",dpi=300)
  ggsave(filename = paste("png",monthnames[i],"shhcore_kud95",".png",sep=""),plot=mpshh,width=8,height=6,units="in",dpi=300)
  
}



#KUD (overlap of all species)
setwd("~/BLLOP_Data/Results/overlap")
monthnames<-c("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")
theme_set(theme_bw())
#https://www.r-spatial.org/r/2018/10/25/ggplot2-sf.html
midclosedata<- st_as_sf(midclose)
midclosedata$Id1<-as.factor("mc")
useezdata<-st_as_sf(useez)
fisherykuddata<-st_as_sf(fisherykud95)
fisherykuddata$ID<-"map"
for(i in 1:12){
  dsdata<-st_as_sf(aggregate(dsshplistkud95[[i]],dissolve=T)) %>% dplyr::mutate(DS = as.factor("DS"))
  shhdata<-st_as_sf(aggregate(shhshplistkud95[[i]],dissolve=T)) %>% dplyr::mutate(SHH = as.factor("SHH"))
  sbdata<-st_as_sf(aggregate(sbshplistkud95[[i]],dissolve=T)) %>% dplyr::mutate(SB = as.factor("SB"))
  ds_shhdata<-st_as_sf(aggregate(ds_shh_overlapshplistkud95[[i]],dissolve=T)) %>% dplyr::mutate(DS_SHH = as.factor("DS_SHH"))
  sb_shhdata<-st_as_sf(aggregate(sb_shh_overlapshplistkud95[[i]],dissolve=T)) %>% dplyr::mutate(SB_SHH = as.factor("SB_SHH"))
  ds_sbdata<-st_as_sf(aggregate(ds_sb_overlapshplistkud95[[i]],dissolve=T)) %>% dplyr::mutate(DS_SB = as.factor("DS_SB"))
  ds_sb_shhdata<-st_as_sf(aggregate(ds_sb_shh_overlapshplistkud95[[i]],dissolve=T)) %>% dplyr::mutate(DS_SB_SHH = as.factor("DS_SB_SHH"))
  
  world<-ne_countries(scale="medium",returnclass = "sf")
  mp<-ggplot(data=world) + 
    geom_sf(color="black",fill="tan") +
    coord_sf(xlim=c(-81.5, -67),ylim=c(23,39),expand=FALSE) +
    geom_sf(data = dsdata, aes(color = "DS", fill = "DS")) +
    geom_sf(data = shhdata, aes(color = "SHH", fill = "SHH")) +
    geom_sf(data = sbdata, aes(color = "SB", fill = "SB")) +
    geom_sf(data = ds_shhdata, aes(color = "DS_SHH", fill = "DS_SHH")) +
    geom_sf(data = sb_shhdata, aes(color = "SB_SHH", fill = "SB_SHH")) +
    geom_sf(data = ds_sbdata, aes(color = "DS_SB", fill = "DS_SB")) +
    geom_sf(data = ds_sb_shhdata, aes(color = "DS_SB_SHH", fill = "DS_SB_SHH")) +
    geom_sf(data = midclosedata, aes(colour = "Id", fill = "Id")) +
    geom_sf(data = fisherykuddata, aes(colour = "ID", fill = "ID")) +
    geom_sf(data = useezdata, aes(color = "Jurisdicti", fill = "Jurisdicti")) +
    geom_sf(data = midclosedata, aes(color = "Id1", fill = "Id1")) + #had to do this to create a break between species and cbump and eez in legend
    scale_fill_manual(name = "",
                      values = c("Jurisdicti"="transparent","ID"="transparent","Id"="transparent","DS"="grey","SHH"="red","SB"="darkgreen","DS_SHH"="blue","DS_SB"="purple","SB_SHH"="orange","DS_SB_SHH"="black","Id1"="transparent"),
                      guide = "legend",
                      breaks = c("SB", "SHH", "DS", "DS_SB", "DS_SHH","SB_SHH","DS_SB_SHH","Id1", "Id","ID","Jurisdicti"),
                      labels = c("Jurisdicti"="U.S. EEZ","ID"="Fishery Domain","Id"="Mid Atlantic","DS"="DS","SHH"="SHH","SB"="SB","DS_SHH"="DS_SHH","DS_SB"="DS_SB","SB_SHH"="SB_SHH","DS_SB_SHH"="DS_SB_SHH","Id1"="")) +
    scale_color_manual(name = "",
                       values = c("Jurisdicti"="black","ID"="cyan3","Id"="green","DS"="grey","SHH"="red","SB"="darkgreen","DS_SHH"="blue","DS_SB"="purple","SB_SHH"="orange","DS_SB_SHH"="black","Id1"="transparent"),
                       guide = "legend",
                       breaks = c("SB", "SHH", "DS", "DS_SB", "DS_SHH","SB_SHH","DS_SB_SHH","Id1", "Id","ID","Jurisdicti"),
                       labels = c("Jurisdicti"="U.S. EEZ","ID"="Fishery Domain","Id"="Mid Atlantic","DS"="DS","SHH"="SHH","SB"="SB","DS_SHH"="DS_SHH","DS_SB"="DS_SB","SB_SHH"="SB_SHH","DS_SB_SHH"="DS_SB_SHH","Id1"="")) +
    theme(axis.title.x = element_blank())+
    theme(axis.title.y = element_blank())+
    theme(legend.key=element_rect(color=NA,fill=NA),legend.key.size = unit(0.5, "cm")) +
    coord_sf(xlim=c(-81.5, -67),ylim=c(23,39),expand=FALSE) +
    #annotate("text",x=-80,y=38.4,label="b",size=6) + #if I want to add letter in map
    theme(text = element_text(size = 13)) + #if I want to change size of text in map
    annotation_scale(location="br" ,width_hint=0.25,style="bar",unit_category="metric",text_cex=0.85) +
    annotation_north_arrow(location = "tl", which_north = "true", height=unit(0.75,"cm"),width=unit(0.6,"cm"),style = north_arrow_orienteering)
  
  ggsave(filename = paste(monthnames[i],"core_overlapkud95",".pdf",sep=""),plot=mp,width=8,height=6,units="in",dpi=300)
  ggsave(filename = paste("png",monthnames[i],"core_overlapkud95",".png",sep=""),plot=mp,width=8,height=6,units="in",dpi=300)
  
}

#save data

############
#Closed Area Metrics functions
############
setwd("~/Enviornmental_Data/Mid_Atlantic_closure")
midclose<-readOGR(".","MIDClosure")
midclose<-spTransform(midclose,"+proj=longlat +datum=WGS84 +no_defs")
setwd("~/Enviornmental_Data/USmap")
useez<-readOGR(".","US_Fed_Waters")
eastcoastmask<-readOGR(".","east_coast_shp_to_mask_eez")
useez<-spTransform(useez,"+init=epsg:4326")
eastcoastmask<-spTransform(eastcoastmask,"+init=epsg:4326")
useez<-crop(useez,eastcoastmask)

#4 Metrics
#Calculate the percent of core habitat  (from individual species or species overlaps) that is in Mid-Atlantic Closure for each month
#Calculate the percent of Mid-Atlantic Closure that has core habitat (from individual species or species overlaps) for each month
#Calculate median output value of core habitat inside Mid-Atlantic Closure and outside Mid-Atlantic Closure (for individual species or species overlaps) for each month
#Calculate mean output value inside Mid-Atlantic Closure and the occurrence rate of species in fishery (which is outside Mid-Atlantic Closure) for months Mid-Atlantic Closure is closed

CoreUseinRegion<-function(speciesrasters=NA){
  areaofregion<-raster::area(midclose)/1000000 #convert from m2 to km2 (to be compared to raster km2 output)
  regionpercentRec<-NULL
  percentofregionRec<-NULL
  medianInsideRec<-NULL
  medianOutsideRec<-NULL
  sumcoreclosedareaRec<-NULL
  for(i in 1:12){
    #calculate median inside and outside of midclose
    speciesrasterInside<-mask(speciesrasters[[i]],mask=midclose) #remember speciesrasters are rasters of core habitat for each month
    speciesrasterOutside<-mask(speciesrasters[[i]],mask=midclose,inverse=TRUE)
    medianInside<-median(values(speciesrasterInside),na.rm=T)
    medianOutside<-median(values(speciesrasterOutside),na.rm=T)
    medianInsideRec<-c(medianInsideRec,medianInside)
    medianOutsideRec<-c(medianOutsideRec,medianOutside)
    
    #Calculates percent core use in Mid Atlantic closure (ind species and overlaps)
    speciesrasters[[i]][!is.na(speciesrasters[[i]])]<- 1
    arearaster<-raster::area(speciesrasters[[i]],na.rm=T)#area is in km2
    arearasteriso<-arearaster[!is.na(arearaster)]#only isolates (gives vector of) cell area values without NAs
    rastervals<-values(speciesrasters[[i]])#values of all cells
    rastervalsiso<-rastervals[!is.na(rastervals)]#only isolates (gives vector of) cell values (should be 1) without NAs
    totalval<-arearasteriso*rastervalsiso#gives area value x cell value
    sumval<-sum(totalval) #sum of 'core area'
    
    region_raster<-mask(speciesrasters[[i]],mask=midclose)
    regionarearaster<-raster::area(region_raster,na.rm=T)#area is in km2
    regionarearasteriso<-regionarearaster[!is.na(regionarearaster)]#only isolates (gives vector of) cell area values without NAs
    regionrastervals<-values(region_raster)#values of all cells
    regionrastervalsiso<-regionrastervals[!is.na(regionrastervals)]#only isolates (gives vector of) cell values (should be 1) without NAs
    regiontotalval<-regionarearasteriso*regionrastervalsiso#gives area value x cell value
    regionsumval<-sum(regiontotalval) #sum of 'core area' inside closed area
    
    regionpercent<-regionsumval/sumval #percent of 'core area' inside closed area
    regionpercentRec<-c(regionpercentRec,regionpercent)
    
    #Calculates percent of region (closed area) occupied by species core habitat
    percentofregion<-sum(regionarearasteriso)/areaofregion #sum(regionarearasteriso) is same as regionsumval
    percentofregionRec<-c(percentofregionRec,percentofregion)
    
    #sum of area of core habitat inside closed area
    sumcoreclosedarea<-sum(regionarearasteriso)
    sumcoreclosedareaRec<-c(sumcoreclosedareaRec,sumcoreclosedarea)
  }
  return(list(medianInsideRec=medianInsideRec,medianOutsideRec=medianOutsideRec,
              regionpercentRec=regionpercentRec,percentofregionRec=percentofregionRec,
              sumcoreclosedareaRec=sumcoreclosedareaRec))
}

ProbPresInOut<-function(species=NA,wd=NA){
  setwd(wd)
  speciesJan<-raster(paste(species,"JanPPP.tif",sep=""))
  speciesFeb<-raster(paste(species,"FebPPP.tif",sep=""))
  speciesMar<-raster(paste(species,"MarPPP.tif",sep=""))
  speciesApr<-raster(paste(species,"AprPPP.tif",sep=""))
  speciesMay<-raster(paste(species,"MayPPP.tif",sep=""))
  speciesJun<-raster(paste(species,"JunPPP.tif",sep=""))
  speciesJul<-raster(paste(species,"JulPPP.tif",sep=""))
  
  #limit to fishery domain
  speciesJan<-mask(speciesJan,mask=fisherykud95)
  speciesFeb<-mask(speciesFeb,mask=fisherykud95)
  speciesMar<-mask(speciesMar,mask=fisherykud95)
  speciesApr<-mask(speciesApr,mask=fisherykud95)
  speciesMay<-mask(speciesMay,mask=fisherykud95)
  speciesJun<-mask(speciesJun,mask=fisherykud95)
  speciesJul<-mask(speciesJul,mask=fisherykud95)
  
  #isolate outputs just for midclose
  speciesJan<-mask(speciesJan,mask=midclose)
  speciesFeb<-mask(speciesFeb,mask=midclose)
  speciesMar<-mask(speciesMar,mask=midclose)
  speciesApr<-mask(speciesApr,mask=midclose)
  speciesMay<-mask(speciesMay,mask=midclose)
  speciesJun<-mask(speciesJun,mask=midclose)
  speciesJul<-mask(speciesJul,mask=midclose)
  
  #calculate midclose mean output
  midcloseoutputJan<-mean(values(speciesJan),na.rm=T)
  midcloseoutputFeb<-mean(values(speciesFeb),na.rm=T)
  midcloseoutputMar<-mean(values(speciesMar),na.rm=T)
  midcloseoutputApr<-mean(values(speciesApr),na.rm=T)
  midcloseoutputMay<-mean(values(speciesMay),na.rm=T)
  midcloseoutputJun<-mean(values(speciesJun),na.rm=T)
  midcloseoutputJul<-mean(values(speciesJul),na.rm=T)
  
  #species catch data
  setwd("~/BLLOP_Data")
  catch_data<-read.csv(paste(species,"bll_catch_full.csv",sep="_"))
  catch_data<-subset(catch_data,select=-c(X.2,X.1,X))
  catch_data$BINOMIAL<-ifelse(catch_data$Catch>0,1,0)
  catch_data$BEGIN_SET_DATE_TIME<-as.POSIXct(catch_data$BEGIN_SET_DATE_TIME,format="%Y-%m-%d %H:%M:%S",tz="America/New_York")
  catch_data<-catch_data[with(catch_data,order(BEGIN_SET_DATE_TIME)),]
  #remove data west of florida
  catch_data<-catch_data[which(catch_data$BEGIN_SET_LONGITUDE> -80.5 | (catch_data$BEGIN_SET_LATITUDE>26.7 & catch_data$BEGIN_SET_LONGITUDE> -81.5)),]#need to do this because unlike POP data, some BLL sets occur west of -80.5 but are still in atlantic (e.g. off of jacksonville)
  catch_data$MONTH<-as.factor(strftime(catch_data$BEGIN_SET_DATE_TIME_UTC,format="%m",tz="America/New_York"))
  catch_data$YEAR<-as.factor(strftime(catch_data$BEGIN_SET_DATE_TIME_UTC,format="%Y",tz="America/New_York"))
  #remove 9 sets where soak time is 0
  catch_data<-catch_data[-which(catch_data$SOAK_DURATION==0),]
  catch_data$logEFFORT<-log(catch_data$NUM_HOOKS_SET*catch_data$SOAK_DURATION)
  catch_data$SPECIES<-"Catch"
  catch_data$Date<-as.Date(catch_data$BEGIN_SET_DATE_TIME,format="%Y-%m-%d",origin="1970-01-01",tz="America/New_York")
  catch_data$Day<-as.numeric(strftime(catch_data$BEGIN_SET_DATE_TIME,format="%j"))
  catch_data$Set_Begin_Hour<-as.numeric(strftime(round(as.POSIXct(catch_data$BEGIN_SET_DATE_TIME,format="%m/%d/%Y %H:%M",origin="1970-01-01",tz="America/New_York"), units="hours"),format="%H"))
  catch_data$BEGIN_SET_TEMPERATURE_C<-(catch_data$BEGIN_SET_TEMPERATURE-32)*5/9 #surface temp taken from bottom of machine
  catch_data$MEAN_DEPTH<-(catch_data$BOTTOM_DEPTH_MAXIMUM_METER+catch_data$BOTTOM_DEPTH_MINIMUM_METER)/2
  #SRF_TRIP is whether set is in shark research fishery or not
  #Region fished, 22 is south atlantic, 23 is north atlantic, 21 is gulf of mexico
  catch_datanona<-subset(catch_data, select=c(Catch,BINOMIAL,SRF_TRIP,REGION_FISHED,BEGIN_SET_DATE_TIME,Date,Day,MONTH,YEAR,Set_Begin_Hour,BAITTYPE,HOOK_CONFIG,MEAN_DEPTH,BOTTOM_DEPTH_MAXIMUM_METER,BOTTOM_DEPTH_MINIMUM_METER,BEGIN_SET_TEMPERATURE_C,logEFFORT,
                                              BEGIN_SET_LATITUDE,BEGIN_SET_LONGITUDE,BATHYMETRY,RUGOSITY,BT,BS,SST,SSS,SSH,BTSD,SSTSD,TURB,TURB_ER,CHLA))
  #some sets with missing env data (only 14 sets)
  catch_datanona<-catch_datanona[complete.cases(catch_datanona[c(10:12,17:31)]),]
  #make sure mean depth (from set) and Bathymetry are similar, remove sets that are not the similar
  #first convert depths from fathoms to meters (conversion factor is 1.83 m to 1 fathom), also need depth to be negative value
  catch_datanona$MEAN_DEPTH<-catch_datanona$MEAN_DEPTH*-1 #average between depth at beginning and end of set
  catch_datanona$BOTTOM_DEPTH_MAXIMUM_METER<-catch_datanona$BOTTOM_DEPTH_MAXIMUM_METER*-1
  catch_datanona$BOTTOM_DEPTH_MINIMUM_METER<-catch_datanona$BOTTOM_DEPTH_MINIMUM_METER*-1
  #decided to go with mean depth because bathymetry data could have been collected on edge or deeper which means it could be off from min or max, mean should be better
  catch_datanona<-catch_datanona[-which(abs(catch_datanona$BATHYMETRY-catch_datanona$MEAN_DEPTH)>100),]#this removes 4 sets that off by 100m and 2 sets that have NAs for Mean Depth
  
  #limit it to fishery domain
  catch_datanonasp<-catch_datanona
  coordinates(catch_datanonasp)<- ~BEGIN_SET_LONGITUDE + BEGIN_SET_LATITUDE
  crs(catch_datanonasp)<-"+proj=longlat +datum=WGS84 +no_defs"
  catch_datanona$In_Domain<-over(catch_datanonasp,fisherykud95)
  catch_datanona<-catch_datanona[which(catch_datanona$In_Domain==1),]
  
  #remove sets inside midclose (Jan-Jul) before calculation (72 sets)
  midclose.spatial.polygons<-SpatialPolygons(midclose@polygons)
  crs(midclose.spatial.polygons)<-"+proj=longlat +datum=WGS84 +no_defs"
  catch_datanonasp<-catch_datanona
  coordinates(catch_datanonasp)<- ~BEGIN_SET_LONGITUDE + BEGIN_SET_LATITUDE #have to rerun because catch_datanona has reduced rows now
  crs(catch_datanonasp)<-"+proj=longlat +datum=WGS84 +no_defs"
  catch_datanona$midclose<-over(catch_datanonasp,midclose.spatial.polygons)
  catch_datanona<-catch_datanona[-which(catch_datanona$midclose==1 & (catch_datanona$MONTH=="01" | catch_datanona$MONTH=="02" | catch_datanona$MONTH=="03" |
                                                                        catch_datanona$MONTH=="04" | catch_datanona$MONTH=="05" | catch_datanona$MONTH=="06" | catch_datanona$MONTH=="07")),]
  
  #calcuate prob occurrence of catching each species
  catch_datanonaJan<-catch_datanona[which(catch_datanona$MONTH=="01"),]
  catch_datanonaFeb<-catch_datanona[which(catch_datanona$MONTH=="02"),]
  catch_datanonaMar<-catch_datanona[which(catch_datanona$MONTH=="03"),]
  catch_datanonaApr<-catch_datanona[which(catch_datanona$MONTH=="04"),]
  catch_datanonaMay<-catch_datanona[which(catch_datanona$MONTH=="05"),]
  catch_datanonaJun<-catch_datanona[which(catch_datanona$MONTH=="06"),]
  catch_datanonaJul<-catch_datanona[which(catch_datanona$MONTH=="07"),]
  
  ProboccurJan<-sum(catch_datanonaJan$BINOMIAL)/nrow(catch_datanonaJan)
  ProboccurFeb<-sum(catch_datanonaFeb$BINOMIAL)/nrow(catch_datanonaFeb)
  ProboccurMar<-sum(catch_datanonaMar$BINOMIAL)/nrow(catch_datanonaMar)
  ProboccurApr<-sum(catch_datanonaApr$BINOMIAL)/nrow(catch_datanonaApr)
  ProboccurMay<-sum(catch_datanonaMay$BINOMIAL)/nrow(catch_datanonaMay)
  ProboccurJun<-sum(catch_datanonaJun$BINOMIAL)/nrow(catch_datanonaJun)
  ProboccurJul<-sum(catch_datanonaJul$BINOMIAL)/nrow(catch_datanonaJul)
  
  
  return(list(closed_area_output=c(midcloseoutputJan,midcloseoutputFeb,midcloseoutputMar,midcloseoutputApr,midcloseoutputMay,midcloseoutputJun,midcloseoutputJul),
              proboccur=c(ProboccurJan,ProboccurFeb,ProboccurMar,ProboccurApr,ProboccurMay,ProboccurJun,ProboccurJul)))
}


#########
#Compare prob outputs In and prob occurr Out
#########
#Compare prob outputs inside mid atlantic closure to prob occurrence outside mid atlantic closure
#just using whole model outputs (i.e. no fishing cutoffs or core areas)
probpresInOutds<-ProbPresInOut(species="ds",wd="~/BLLOP_Data/Results/ds/R_raster_outputs")
probpresInOutshh<-ProbPresInOut(species="shh",wd="~/BLLOP_Data/Results/shh/R_raster_outputs")
probpresInOutsb<-ProbPresInOut(species="sb",wd="~/BLLOP_Data/Results/sb/R_raster_outputs")

setwd("~/BLLOP_Data/Results/overlap")
tiff("BLLOP_SpeciesProbPresIn_OccurOut_highres.tif",width=10,height=4,units="in",res=300)
par(mfrow=c(1,3),mar=c(5,4.5,2,1))
plot(100*probpresInOutds$closed_area_output,type="b",ylim=c(0,60),xaxt="n",xlab="Month",ylab="Occurrence Probability or Occurrence Rate (%)",main="Dusky Shark",cex.axis=1.25,cex.lab=1.5,col="red")
axis(side=1,at=c(1:7),c("Jan","Feb","Mar","Apr","May","Jun","Jul"),cex.axis=1.3)
text(x=6.9,y=60,"d",cex=1.5)
#legend("bottomleft",legend=c("Inside Closed Area","Outside Closed Area"),fill=c("red","black"),cex=1.5)
lines(100*probpresInOutds$proboccur, type="b",col="black")
plot(100*probpresInOutsb$closed_area_output,type="b",ylim=c(0,100),xaxt="n",xlab="Month",ylab="Occurrence Probability or Occurrence Rate (%)",main="Sandbar Shark",cex.axis=1.25,cex.lab=1.5,col="red")
axis(side=1,at=c(1:7),c("Jan","Feb","Mar","Apr","May","Jun","Jul"),cex.axis=1.3)
text(x=6.9,y=99.9,"e",cex=1.5)
lines(100*probpresInOutsb$proboccur, type="b",col="black")
plot(100*probpresInOutshh$closed_area_output,type="b",ylim=c(0,85),xaxt="n",xlab="Month",ylab="Occurrence Probability or Occurrence Rate (%)",main="Scalloped Hammerhead",cex.axis=1.25,cex.lab=1.5,col="red")
axis(side=1,at=c(1:7),c("Jan","Feb","Mar","Apr","May","Jun","Jul"),cex.axis=1.3)
text(x=6.9,y=85,"f",cex=1.5)
lines(100*probpresInOutshh$proboccur, type="b",col="black")
dev.off()


###########
#% of core habitat in Mid Atlantic closure
#% Mid Atlantic closure with Core habitat
###########
#kud 95% of fishing area + eez
setwd("~/BLLOP_Data/Results")
load("bllop_overlap_data_kud95.RData")

#MAC (mid atlantic closure)
#not concerned with overlap anymore
dsPerUseofmackud95<-CoreUseinRegion(speciesrasters=Preldskud95$speciesprobstack)
shhPerUseofmackud95<-CoreUseinRegion(speciesrasters=Prelshhkud95$speciesprobstack)
sbPerUseofmackud95<-CoreUseinRegion(speciesrasters=Prelsbkud95$speciesprobstack)
#species overlap
ds_shhPerUseofmackud95<-CoreUseinRegion(speciesrasters=ds_shh_overlaprasterstackkud95)
sb_shhPerUseofmackud95<-CoreUseinRegion(speciesrasters=sb_shh_overlaprasterstackkud95)
ds_sbPerUseofmackud95<-CoreUseinRegion(speciesrasters=ds_sb_overlaprasterstackkud95)
ds_sb_shhPerUseofmackud95<-CoreUseinRegion(speciesrasters=ds_sb_shh_overlaprasterstackkud95)


months<-c("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")

setwd("~/BLLOP_Data/Results/overlap")
#plot % of core habitat in MAC (mid atlantic closure)
tiff("Per_Core_Area_in_MAC_kud95_highres.tif",width=8,height=6,units="in",res=300)
par(mfrow=c(1,1))
plot(dsPerUseofmackud95$regionpercentRec*100,xlab="Month",ylab="% High Risk Area in Closed Area",type="b",xaxt="n",col="grey33",lwd=2,ylim=c(0,60))
axis(1,at=1:12,months)
text(x=1.5,y=60,"b",cex=1.5)
polygon(y=c(-10,110,110,-10),x=c(1,1,7,7),col=rgb(0,0,0,0.1))
lines(shhPerUseofmackud95$regionpercentRec*100,type="b",col="purple",lwd=2)
lines(sbPerUseofmackud95$regionpercentRec*100,type="b",col="darkgoldenrod3",lwd=2)
legend("topright",legend=c("DS","SB","SHH"),
       fill=c("grey33","darkgoldenrod3","purple"),cex=0.75)
dev.off()



#plot % mac with Core habitat
tiff("Per_MAC_with_Core_Area_kud95_kud95_highres.tif",width=8,height=6,units="in",res=300)
par(mfrow=c(1,1))
plot(dsPerUseofmackud95$percentofregionRec*100,xlab="Month",ylab="% Closed Area with High Risk Area",type="b",xaxt="n",col="grey33",lwd=2,ylim=c(0,100))
axis(1,at=1:12,months)
text(x=1.5,y=100,"b",cex=1.5)
polygon(y=c(-10,110,110,-10),x=c(1,1,7,7),col=rgb(0,0,0,0.1))
lines(shhPerUseofmackud95$percentofregionRec*100,type="b",col="purple",lwd=2)
lines(sbPerUseofmackud95$percentofregionRec*100,type="b",col="darkgoldenrod3",lwd=2)
legend("topright",legend=c("DS","SB","SHH"),
       fill=c("grey33","darkgoldenrod3","purple"),cex=0.75)
dev.off()




###########
#Compare median core habitat In and Out
###########

#ratio In:Out
setwd("~/BLLOP_Data/Results/overlap")
tiff("BLLOP_Median_outputs_ratios_highres.tif",width=4,height=7,units="in",res=300)
par(mfrow=c(3,1),oma=c(1,1,0,0)+0.1,mar=c(3,3,0.5,1)+0.1)
plot(dsPerUseofmackud95$medianInsideRec/dsPerUseofmackud95$medianOutsideRec,type="b",xaxt="n",xlab="Month",ylab="",main="",ylim=c(0.8,1.1),cex.axis=1.5)
polygon(y=c(-1,2.2,2.2,-1),x=c(1,1,7,7),col=rgb(0,0,0,0.1))
text(x=12,y=1.09,"a",cex=1.5)
text(x=3.5,y=1.09,"Dusky Shark",cex=1.5)
axis(1,at=1:12,months,cex.axis=1.25)
abline(h=1,lty=2)
plot(sbPerUseofmackud95$medianInsideRec/sbPerUseofmackud95$medianOutsideRec,type="b",xaxt="n",xlab="Month",ylab="",main="",ylim=c(0.8,1.1),cex.axis=1.5)
polygon(y=c(-1,2.2,2.2,-1),x=c(1,1,7,7),col=rgb(0,0,0,0.1))
text(x=12,y=1.09,"b",cex=1.5)
text(x=3.5,y=1.09,"Sandbar Shark",cex=1.5)
axis(1,at=1:12,months,cex.axis=1.25)
abline(h=1,lty=2)
mtext(side=2,"Ratios of Median Values (In:Out)",line=3,cex=1)
plot(shhPerUseofmackud95$medianInsideRec/shhPerUseofmackud95$medianOutsideRec,type="b",xaxt="n",xlab="Month",ylab="",main="",ylim=c(0.8,1.1),cex.axis=1.5)
polygon(y=c(-1,2.2,2.2,-1),x=c(1,1,7,7),col=rgb(0,0,0,0.1))
text(x=12,y=1.09,"c",cex=1.5)
text(x=4.3,y=1.09,"Scalloped",cex=1.5)
text(x=4.3,y=1.06,"Hammerhead",cex=1.5)
axis(1,at=1:12,months,cex.axis=1.25)
abline(h=1,lty=2)
dev.off()


