## =============================================================================
##
## Script name: R code for LEK: Females dive towards dispersed leks during
##                              spawning season in Atlantic cod (Gadus morhua)
##
## Author: Arjen A.W. van der Kamp & Jon Egil Skjæraasen
## Email: aaw.vanderkamp@gmail.com
##
## Date: 16 November 2026
##
## -----------------------------------------------------------------------------
##
## Notes:
##
## -----------------------------------------------------------------------------

library(tidyverse)   
library(conflicted)
library(nlme)
library(lmerTest)    
library(mgcv)
library(MuMIn)
library(emmeans)
library(forcats)
library(car)
library(effects)
library(ggeffects)
library(sjPlot)
library(patchwork)
library(scales)
library(zoo)
library(sf)
library(ggspatial)
library(sp)
library(adehabitatHR)
library(move)
conflicts_prefer(lmerTest::lmer, dplyr::filter, dplyr::select, data.table::month, 
                 dplyr::lag, data.table::year)
theme_JE<-theme_bw()+theme(plot.background = element_blank(),
                           panel.grid.major = element_blank(),panel.grid.minor = element_blank())+
  theme(axis.line = element_line(color = 'black'))
setwd("") # <- fill in own trajectory
memory.limit(size=100000)

####################################
##  BAKKASUND MAP with RECEIVERS  ##
####################################

# Load stations
stations_df <- read.csv("Austevoll_stations_nodub_grid.txt", header = TRUE)
colnames(stations_df) <- c("Station", "Latitude", "Longitude")
stations_df$Latitude  <- as.numeric(stations_df$Latitude)
stations_df$Longitude <- as.numeric(stations_df$Longitude)
stations_sf <- st_as_sf(stations_df,
                        coords = c("Longitude", "Latitude"),
                        crs = 4326)
stations_utm <- st_transform(stations_sf, 32631)

shp_land = read_sf("land_polygons.shp")
shp_land_utm <- st_transform(shp_land, 32631)
st_crs(shp_land)

bbox <- st_bbox(c(xmin = 5.03, xmax = 5.122,
                  ymin = 60.11, ymax = 60.145),
                crs = 4326) |>
  st_transform(32631)
# land_crop takes a long time, so the file can be downloaded in the folder attached to the manuscript
# land_crop <- shp_land |>
#   st_crop(bbox) |>
#   st_transform(32631)
# save(land_crop,file="land_crop.Rdata")
load("land_crop.Rdata")

###############################
### Estimation of the area #### 
### Convert points to sf   ####
###############################

Filt_BK <- read_csv("Bakkasund_filt_19_24_land_removed.csv")
Filt_BK <- Filt_BK |> 
  dplyr::mutate(DataYear=data.table::year(DATETIME),
                Month=data.table::month(DATETIME),
                Period=ifelse(Month%in%c(2:3),0,1))

##Fix dates and Time_Corr
Filt_BK<-Filt_BK |>
  dplyr::mutate(Time_Fix=ifelse(is.na(DATETIMEsecs)==TRUE,
                                as.POSIXct(paste(Date, "00:00:01"),
                                           format = "%Y-%m-%d %H:%M:%S",tz="UTC"),NA))
Filt_BK<-Filt_BK |>
  dplyr::mutate(DATETIMEsecs=ifelse(is.na(DATETIMEsecs)!=TRUE,DATETIMEsecs,Time_Fix-1))
Filt_BK<-Filt_BK |>
  dplyr::mutate(Day_Night=ifelse(DATETIMEsecs>=sunupsecs&DATETIMEsecs<sundownsecs,0,1)) 
coords<-Filt_BK |> dplyr::select(LON,LAT)
coords_sf <- st_as_sf(coords, coords = c("LON", "LAT"), crs = 4326)

# Transform to 31 zone
coords_utm <- st_transform(coords_sf, crs = 32631)
coords_utm_filt <- coords_utm[(1:100),]
utm_coordinates <- st_coordinates(coords_utm)

# data.frame with X and Y
utm_df <- data.frame(X2 = utm_coordinates[, 1],  
                     Y2 = utm_coordinates[, 2])  
Filt_BK<-cbind(Filt_BK,utm_df)
Spawn_mat_spawn <- Filt_BK |> 
  dplyr::filter(Period==0&MatStageComb=="Mat") |> 
  dplyr::mutate(Ser_Year_Per=paste(Serial2,Year,Period,sep="_"),
                Ser_Year_Per_Diel=paste(Serial2,Year,Period,Day_Night,sep="_"))

points_sf <- st_as_sf(Spawn_mat_spawn, coords = c("LON", "LAT"), crs = 4326) |>
  st_transform(32631)
concave_val <- 2

# Concave hull
concave_hull <- concaveman::concaveman(points_sf, concavity = concave_val)
concave_area_km2 <- st_area(concave_hull) |> units::set_units(km^2)
round(concave_area_km2, 2) 

# Subtract land from concave hull
land_union <- st_union(land_crop) |>
  st_transform(32631)
concave_water <- st_difference(concave_hull, land_union)

water_area_km2 <- st_area(concave_water) |> units::set_units(km^2)
round(water_area_km2, 2) #1.89km2

# Depth deeper than 25
points_sf_25 <- points_sf |> dplyr::filter(Depth2 >= 25)

# Concave hull
concave_hull_25 <- concaveman::concaveman(points_sf_25, concavity = concave_val)  
concave_area_km2 <- st_area(concave_hull_25) |> units::set_units(km^2)
round(concave_area_km2, 2) #1.58

# Subtract land from concave hull 
land_union <- st_union(land_crop) |> st_transform(32631)
concave_water_25 <- st_difference(concave_hull_25, land_union)

water_area_km2 <- st_area(concave_water_25) |> units::set_units(km^2)
round(water_area_km2, 2) #1.53

Frame_Fig2 <- st_as_sfc(st_bbox(c(xmin = 5.049628, xmax = 5.12000,
                                  ymin = 60.113030, ymax = 60.133073),
                                crs = st_crs(4326))) |> st_transform(32631)

# Fig. 1
ggplot() +
  geom_sf(data = land_crop,
          fill      = "white",
          color     = "black",
          linewidth = 0.2) +
  geom_sf(data = concave_water,
          fill      = "orange",
          color     = "orange4",
          alpha     = 0.7,
          linewidth = 0.6) +
  geom_sf(data      = concave_water_25,
          fill      = NA,
          colour    = "red",
          alpha     = 0.9,
          linewidth = 0.6)+
  geom_sf(data = stations_utm,
          color = "black",
          size  = 3,
          alpha = 0.8) +
  geom_sf_text(data = stations_utm,
               aes(label = Station),
               nudge_y = 50,
               size    = 3) +
  annotate("text",
           x        = 5.079,
           y        = 60.128,
           label    = "Stora Karlsøy",
           hjust    = 0.5,
           vjust    = 0.5,
           size     = 5,
           fontface = "italic") +
  coord_sf(xlim        = c(5.03, 5.12),
           ylim        = c(60.11, 60.145),
           expand      = FALSE,
           crs         = st_crs(32631),
           default_crs = st_crs(4326)) +
  annotation_scale(location      = "bl",
                   width_hint    = 0.25,
                   unit_category = "metric") +
  theme_minimal() +
  theme(panel.background = element_rect(fill = "lightblue", color = NA),
        panel.border     = element_rect(color = "black", fill = NA, linewidth = 0.8),
        panel.grid       = element_blank(),
        axis.text        = element_blank(),
        axis.ticks       = element_blank(),
        axis.title       = element_blank())

###############################
### Data handling and prep #### 
###############################

# Load data
Filt_BK<-read_csv("Bakkasund_filt_19_24_land_removed.csv")
Filt_BK<- Filt_BK|>
  mutate(DataYear=year(DATETIME),
         Month=month(DATETIME),
         Period=ifelse(Month%in%c(2:3),0,1))

##Fix dates and Time_Corr
Filt_BK<-Filt_BK |> 
  mutate(Time_Fix=ifelse(is.na(DATETIMEsecs)==TRUE,
                         as.POSIXct(paste(Date, "00:00:01"),
                                    format = "%Y-%m-%d %H:%M:%S",tz="UTC"),NA))
Filt_BK<-Filt_BK |> 
  mutate(DATETIMEsecs=ifelse(is.na(DATETIMEsecs)!=TRUE,DATETIMEsecs,Time_Fix-1))
Filt_BK<-Filt_BK |>
  mutate(Day_Night=ifelse(DATETIMEsecs>=sunupsecs&DATETIMEsecs<sundownsecs,0,1)) 
Filt_BK<-Filt_BK |>
  mutate(DataYear2=ifelse(Month==1,DataYear-1,DataYear))
Filt_BK<-Filt_BK|>dplyr::filter(Month!=1&Month!=4)
Filt_BK<-Filt_BK |>
  mutate(Date_Corr=as.Date(ifelse(as.numeric(DATETIMEsecs)<as.numeric(sunupsecs),ymd(Date)-1,ymd(Date))))
Filt_BK<-Filt_BK |> mutate(Ser_Per_Year_Date_Diel=paste(Serial2,Period,DataYear2,Date_Corr,Day_Night,sep = "_"))
Filt_BK<-Filt_BK |> arrange(Ser_Per_Year_Date_Diel,DATETIMEsecs)
Ser_Year_Per_df <- as.data.frame(unique(Filt_BK$Ser_Per_Year_Date_Diel))
Ser_Year_Per_df <- Ser_Year_Per_df |>
  mutate(Burst1=1:25383)
colnames(Ser_Year_Per_df) <- c("Ser_Per_Year_Date_Diel","Burst_1")
Filt_BK<-Filt_BK |> left_join(Ser_Year_Per_df)
Filt_BK<-Filt_BK |> filter(is.na(DATETIMEsecs)==FALSE)
Filt_BK<-Filt_BK |> arrange(Ser_Per_Year_Date_Diel,DATETIMEsecs)
Filt_BK<-Filt_BK |> mutate(DTsecs_diff=DATETIMEsecs-lag(DATETIMEsecs))
Filt_BK<-Filt_BK |> mutate(Burst3=ifelse(Ser_Per_Year_Date_Diel!=lag(Ser_Per_Year_Date_Diel),0,
                                         ifelse(is.na(DTsecs_diff)==TRUE,0,
                                                ifelse(Ser_Per_Year_Date_Diel==lag(Ser_Per_Year_Date_Diel) & DTsecs_diff<=43200,0,1))))
Filt_BK<-Filt_BK |> mutate(Burst3=ifelse(is.na(Burst3)==TRUE,0,Burst3))
Filt_BK<-Filt_BK |> mutate(Burst_b=cumsum(Burst3)+Burst_1)

Burst_dur_12h<-Filt_BK|>group_by(Burst_b)|>
  summarise(Hour_Dur=(max(DATETIMEsecs)-min(DATETIMEsecs))/(60*60),PosBurst=n())
Filt_BK <- Filt_BK |> left_join(Burst_dur_12h,by="Burst_b")

Ser_Burstb <- Filt_BK |>
  group_by(DataYear,Sex,MatStageComb,Period,Serial2,Day_Night,Burst_b,Length,Year) |>
  summarise(PosN=n())
Ser_Burstb_Mat_Spawwn_10 <- Ser_Burstb |>
  filter(Period==0&MatStageComb=="Mat" & PosN>9)
Ser_Burstb_Mat_Spawwn_10_TY <- Ser_Burstb |>
  filter(Period==0 & MatStageComb=="Mat" & PosN>9 & DataYear==Year)

Overlap_Fish<-Ser_Burstb_Mat_Spawwn_10 |> 
  group_by(DataYear,Sex,MatStageComb,Period,Serial2,Day_Night) |>
  summarise(Nburst=n()) |> filter(Nburst>1)

# Depths difference test model, Tidal corrected
# Load data from https://www.kartverket.no/en/at-sea/se-havniva/result
# Sp_files in the attached folder
Tide_2019 <- read_csv("Sp_2019.csv", skip = 13) |> dplyr::select(1:3)
Tide_2020 <- read_csv("Sp_2020.csv", skip = 13) |> dplyr::select(1:3)
Tide_2021 <- read_csv("Sp_2021.csv", skip = 13) |> dplyr::select(1:3)
Tide_2022 <- read_csv("Sp_2022.csv", skip = 13) |> dplyr::select(1:3)
Tide_2023 <- read_csv("Sp_2023.csv", skip = 13) |> dplyr::select(1:3)
Tide_2024 <- read_csv("Sp_2024.csv", skip = 13) |> dplyr::select(1:3)

Tidal_corr <- rbind(Tide_2019, Tide_2020, Tide_2021, Tide_2022, Tide_2023, Tide_2024)
colnames(Tidal_corr) <- c("DT", "Pred", "Observed")
Tidal_corr$secs <- as.numeric(Tidal_corr$DT)

Tidal_corr <- Tidal_corr |> 
  dplyr::distinct(DT, Pred, Observed, secs) |>
  dplyr::arrange(secs) |>
  dplyr::filter(!is.na(secs))

SpawnSeis_data <- read_csv("Bakkasund_filt_19_24_land_removed.csv")
SpawnSeis_data <- SpawnSeis_data |> 
  mutate(Month  = data.table::month(DATETIME),
         Year   = data.table::year(DATETIME),
         DTsecs = as.numeric(DATETIME),
         Period = ifelse(Month %in% c(2:3), 0, 1)) |> arrange(DTsecs)

# Interpolate tide at detection
interpolate <- approx(x = Tidal_corr$secs, y = Tidal_corr$Pred, xout = SpawnSeis_data$DTsecs)
SpawnSeis_data$Tide_corr <- interpolate$y

# check for any timestamps outside the tidal data's rang
sum(is.na(SpawnSeis_data$Tide_corr))

SpawnSeis_data <- SpawnSeis_data |>
  mutate(Period = ifelse(Month %in% c(2:3), 0, 1),
         Depth_Corr = ifelse(!is.na(Depth2)&Depth2>=0, Depth2 - Tide_corr/100, NA))
Filt_BK <- SpawnSeis_data

# Fix dates and Time_Corr
Filt_BK<-Filt_BK|>mutate(Time_Fix=ifelse(is.na(DATETIMEsecs)==TRUE,
                                         as.POSIXct(paste(Date, "00:00:01"),
                                                    format = "%Y-%m-%d %H:%M:%S",tz="UTC"),NA))
Filt_BK<-Filt_BK|>mutate(DATETIMEsecs=ifelse(is.na(DATETIMEsecs)!=TRUE,DATETIMEsecs,Time_Fix-1))
Filt_BK<-Filt_BK|>mutate(Day_Night=ifelse(DATETIMEsecs>=sunupsecs&DATETIMEsecs<sundownsecs,0,1)) 
Filt_BK<-Filt_BK|>mutate(Year2=ifelse(Month==1,Year-1,Year))
Filt_BK<-Filt_BK|>filter(Month!=1&Month!=4)
Filt_BK<-Filt_BK|>mutate(Date_Corr=as.Date(ifelse(as.numeric(DATETIMEsecs)<as.numeric(sunupsecs),ymd(Date)-1,ymd(Date))))
Filt_BK<- Filt_BK|>mutate(Ser_Per_Year_Date_Diel=paste(Serial2,Period,Year2,Date_Corr,Day_Night,sep = "_"))
Filt_BK<-Filt_BK|>arrange(Ser_Per_Year_Date_Diel,DATETIMEsecs)
Ser_Year_Per_df<-as.data.frame(unique(Filt_BK$Ser_Per_Year_Date_Diel))
Ser_Year_Per_df<-Ser_Year_Per_df|>mutate(Burst1=1:25383)
colnames(Ser_Year_Per_df)<-c("Ser_Per_Year_Date_Diel","Burst_1")
Filt_BK<-Filt_BK|>left_join(Ser_Year_Per_df)
Filt_BK<-Filt_BK|>filter(is.na(DATETIMEsecs)==FALSE)
Filt_BK<-Filt_BK|>arrange(Ser_Per_Year_Date_Diel,DATETIMEsecs)
Filt_BK<-Filt_BK|>mutate(DTsecs_diff=DATETIMEsecs-lag(DATETIMEsecs))
Filt_BK<-Filt_BK|>mutate(Burst3=ifelse(Ser_Per_Year_Date_Diel!=lag(Ser_Per_Year_Date_Diel),0,
                                       ifelse(is.na(DTsecs_diff)==TRUE,0,      
                                              ifelse(Ser_Per_Year_Date_Diel==lag(Ser_Per_Year_Date_Diel)&DTsecs_diff<=43200,0,1))))
Filt_BK<-Filt_BK|>mutate(Burst3=ifelse(is.na(Burst3)==TRUE,0,Burst3))
Filt_BK<-Filt_BK|>mutate(Burst_b=cumsum(Burst3)+Burst_1)

##Depth test
Filt_BK_Depth_G <- Filt_BK |>
  dplyr::filter(Period==0&MatStageComb=="Mat" & is.na(Acc)==TRUE & is.na(Temp)==TRUE & is.na(Depth_Corr)==FALSE & is.na(Sex)==FALSE) |>
  dplyr::group_by(Serial2,Sex,Day_Night,Year)|>
  dplyr::summarise(MeanDepth=mean(Depth_Corr),Numb=n())

Depth_Mod<-lmerTest::lmer(MeanDepth~Sex*factor(Day_Night)+(1|Serial2)+(1|Year),
                          data = Filt_BK_Depth_G,
                          weights = sqrt(Numb),
                          na.action = "na.fail")
summary(Depth_Mod)
M2<-dredge(Depth_Mod)
M2
plot(Depth_Mod)
check_model(Depth_Mod, check = c("qq", "homogeneity", "vif"))

###################################
## All the maps for the Appendix ##
###################################

Filt_BK <- read_csv("Bakkasund_filt_19_24_land_removed.csv")
Filt_BK <- Filt_BK |> 
  mutate(DataYear=data.table::year(DATETIME),Month=data.table::month(DATETIME),Period=ifelse(Month%in%c(2:3),0,1))

Filt_BK<-Filt_BK|>
  mutate(Time_Fix=ifelse(is.na(DATETIMEsecs)==TRUE,
                         as.POSIXct(paste(Date, "00:00:01"),
                                    format = "%Y-%m-%d %H:%M:%S",tz="UTC"),NA))
Filt_BK<-Filt_BK|>
  mutate(DATETIMEsecs=ifelse(is.na(DATETIMEsecs)!=TRUE,DATETIMEsecs,Time_Fix-1))
Filt_BK<-Filt_BK|>
  mutate(Day_Night=ifelse(DATETIMEsecs>=sunupsecs&DATETIMEsecs<sundownsecs,0,1)) 
Filt_BK<-Filt_BK|>
  mutate(DataYear2=ifelse(Month==1,DataYear-1,DataYear))
Filt_BK<-Filt_BK|>
  filter(Month!=1&Month!=4)
Filt_BK<-Filt_BK|>
  mutate(Date_Corr=as.Date(ifelse(as.numeric(DATETIMEsecs)<as.numeric(sunupsecs),ymd(Date)-1,ymd(Date))))
Filt_BK<- Filt_BK|>
  mutate(Ser_Per_Year_Date_Diel=paste(Serial2,Period,DataYear2,Date_Corr,Day_Night,sep = "_"))
Filt_BK<-Filt_BK|>
  arrange(Ser_Per_Year_Date_Diel,DATETIMEsecs)
Ser_Year_Per_Date_Diel_df<-as.data.frame(unique(Filt_BK$Ser_Per_Year_Date_Diel))
Ser_Year_Per_Date_Diel_df<-Ser_Year_Per_Date_Diel_df|>mutate(Burst1=1:25383)
colnames(Ser_Year_Per_Date_Diel_df)<-c("Ser_Per_Year_Date_Diel","Burst_1")
Filt_BK<-Filt_BK|>
  left_join(Ser_Year_Per_Date_Diel_df)
Filt_BK<-Filt_BK|>
  filter(is.na(DATETIMEsecs)==FALSE)
Filt_BK<-Filt_BK|>
  arrange(Ser_Per_Year_Date_Diel,DATETIMEsecs)
Filt_BK<-Filt_BK|>
  mutate(DTsecs_diff=DATETIMEsecs-lag(DATETIMEsecs))
Filt_BK<-Filt_BK|>
  mutate(Burst3=ifelse(Ser_Per_Year_Date_Diel!=lag(Ser_Per_Year_Date_Diel),0,
                       ifelse(is.na(DTsecs_diff)==TRUE,0,      
                              ifelse(Ser_Per_Year_Date_Diel==lag(Ser_Per_Year_Date_Diel)&DTsecs_diff<=43200,0,1))))
Filt_BK<-Filt_BK|>
  mutate(Burst3=ifelse(is.na(Burst3)==TRUE,0,Burst3))
Filt_BK<-Filt_BK|>
  mutate(Burst_b=cumsum(Burst3)+Burst_1)

Burst_dur_12h<-Filt_BK|>
  dplyr::group_by(Burst_b)|>dplyr::summarise(Hour_Dur=(max(DATETIMEsecs)-min(DATETIMEsecs))/(60*60),PosBurst=n())
Filt_BK<-Filt_BK|>
  inner_join(Burst_dur_12h)

Ser_Burst<-Filt_BK|>
  dplyr::group_by(DataYear,Sex,MatStageComb,Ser_Per_Year_Date_Diel,Burst_b,Length,Year)|>dplyr::summarise(PosN=n())
Ser_Burst_TY<-Ser_Burst|>
  filter(DataYear==Year)
Ser_Burst_Month<-Filt_BK|>
  dplyr::group_by(DataYear,Month,Sex,MatStageComb,Ser_Per_Year_Date_Diel,Burst_b)|>dplyr::summarise(PosN=n())
Ser_Burst_check<-Ser_Burst|>
  dplyr::group_by(Ser_Per_Year_Date_Diel,Burst_b)|>dplyr::summarise(PosN=n())

Ser_Burst_Merge<-Ser_Burst|>
  filter(MatStageComb=="Mat"&PosN>9)|>
  dplyr::select(-Year)
Ser_Burst_Merge_TY<-Ser_Burst_TY|>
  filter(MatStageComb=="Mat"&PosN>9)|>dplyr::select(-Year)

Filt_BK_Fin<-Filt_BK|>
  dplyr::select(LAT,LON,X,Y,Length,DATETIME,Ser_Per_Year_Date_Diel,Sex,Serial,Serial2,Day_Night,DataYear,Period,Burst_b,PosBurst,MatStageComb,Month,Date_Corr)
Filt_BK_Fin<-Filt_BK_Fin[complete.cases(Filt_BK_Fin),]
Filt_BK_Fin<-as.data.frame(Filt_BK_Fin)
Filt_BK_Fin<-Filt_BK_Fin|>
  mutate(weekN=data.table::week(Date_Corr))

# All data
xmin<-min(Filt_BK_Fin$X)-2000 ## Lowest value - 100m
xmax<-max(Filt_BK_Fin$X)+2000 ## Higest value + 100m
ymin<-min(Filt_BK_Fin$Y)-3000 ## Lowest value - 100m
ymax<-max(Filt_BK_Fin$Y)+3000 ## Higest value + 100m

# Use this grid for all years
x <- seq(xmin,xmax,by=10) # where resolution is the pixel size you desire 
y <- seq(ymin,ymax,by=10)
xy <- expand.grid(x=x,y=y)
coordinates(xy) <- ~x+y
gridded(xy) <- TRUE
class(xy)

Filt_BK_Fin_spawn<-Filt_BK_Fin|>
  filter(Period==0&PosBurst>1&MatStageComb=="Mat")
Filt_BK_Fin_spawn<-as.data.frame(Filt_BK_Fin_spawn)

Filt_BK_Fin_spawn<-Filt_BK_Fin_spawn|>
  mutate(Burst_b=as.numeric(Burst_b))
Filt_BK_Fin_spawn<-Filt_BK_Fin_spawn|>
  inner_join(Ser_Burst_Merge)

###################################
## Calculating home ranges males ##
###################################

Filt_BK_spawn_19M_12h_Night_M <-Filt_BK_Fin_spawn|>filter(DataYear==2019&Sex=="M"&Day_Night==1)
Filt_BK_spawn_19M_12h_Day_M   <-Filt_BK_Fin_spawn|>filter(DataYear==2019&Sex=="M"&Day_Night==0)
Filt_BK_spawn_20M_12h_Night_M <-Filt_BK_Fin_spawn|>filter(DataYear==2020&Sex=="M"&Day_Night==1)
Filt_BK_spawn_20M_12h_Day_M   <-Filt_BK_Fin_spawn|>filter(DataYear==2020&Sex=="M"&Day_Night==0)
Filt_BK_spawn_21M_12h_Night_M <-Filt_BK_Fin_spawn|>filter(DataYear==2021&Sex=="M"&Day_Night==1)
Filt_BK_spawn_21M_12h_Day_M   <-Filt_BK_Fin_spawn|>filter(DataYear==2021&Sex=="M"&Day_Night==0)
Filt_BK_spawn_22M_12h_Night_M <-Filt_BK_Fin_spawn|>filter(DataYear==2022&Sex=="M"&Day_Night==1)
Filt_BK_spawn_22M_12h_Day_M   <-Filt_BK_Fin_spawn|>filter(DataYear==2022&Sex=="M"&Day_Night==0)
Filt_BK_spawn_23M_12h_Night_M <-Filt_BK_Fin_spawn|>filter(DataYear==2023&Sex=="M"&Day_Night==1)
Filt_BK_spawn_23M_12h_Day_M   <-Filt_BK_Fin_spawn|>filter(DataYear==2023&Sex=="M"&Day_Night==0)
Filt_BK_spawn_24M_12h_Night_M <-Filt_BK_Fin_spawn|>filter(DataYear==2024&Sex=="M"&Day_Night==1)
Filt_BK_spawn_24M_12h_Day_M   <-Filt_BK_Fin_spawn|>filter(DataYear==2024&Sex=="M"&Day_Night==0)

Filt_BK_spawn_19M_12h <- bind_rows(Filt_BK_spawn_19M_12h_Night_M,Filt_BK_spawn_19M_12h_Day_M)
Filt_BK_spawn_20M_12h <- bind_rows(Filt_BK_spawn_20M_12h_Night_M,Filt_BK_spawn_20M_12h_Day_M)
Filt_BK_spawn_21M_12h <- bind_rows(Filt_BK_spawn_21M_12h_Night_M,Filt_BK_spawn_21M_12h_Day_M)
Filt_BK_spawn_22M_12h <- bind_rows(Filt_BK_spawn_22M_12h_Night_M,Filt_BK_spawn_22M_12h_Day_M)
Filt_BK_spawn_23M_12h <- bind_rows(Filt_BK_spawn_23M_12h_Night_M,Filt_BK_spawn_23M_12h_Day_M)
Filt_BK_spawn_24M_12h <- bind_rows(Filt_BK_spawn_24M_12h_Night_M,Filt_BK_spawn_24M_12h_Day_M)

##Calculating home ranges females
Filt_BK_spawn_19F_12h_Night_F <-Filt_BK_Fin_spawn|>filter(DataYear==2019&Sex=="F"&Day_Night==1)
Filt_BK_spawn_19F_12h_Day_F   <-Filt_BK_Fin_spawn|>filter(DataYear==2019&Sex=="F"&Day_Night==0)
Filt_BK_spawn_20F_12h_Night_F <-Filt_BK_Fin_spawn|>filter(DataYear==2020&Sex=="F"&Day_Night==1)
Filt_BK_spawn_20F_12h_Day_F   <-Filt_BK_Fin_spawn|>filter(DataYear==2020&Sex=="F"&Day_Night==0)
Filt_BK_spawn_21F_12h_Night_F <-Filt_BK_Fin_spawn|>filter(DataYear==2021&Sex=="F"&Day_Night==1)
Filt_BK_spawn_21F_12h_Day_F   <-Filt_BK_Fin_spawn|>filter(DataYear==2021&Sex=="F"&Day_Night==0)
Filt_BK_spawn_22F_12h_Night_F <-Filt_BK_Fin_spawn|>filter(DataYear==2022&Sex=="F"&Day_Night==1)
Filt_BK_spawn_22F_12h_Day_F   <-Filt_BK_Fin_spawn|>filter(DataYear==2022&Sex=="F"&Day_Night==0)
Filt_BK_spawn_23F_12h_Night_F <-Filt_BK_Fin_spawn|>filter(DataYear==2023&Sex=="F"&Day_Night==1)
Filt_BK_spawn_23F_12h_Day_F   <-Filt_BK_Fin_spawn|>filter(DataYear==2023&Sex=="F"&Day_Night==0)
Filt_BK_spawn_24F_12h_Night_F <-Filt_BK_Fin_spawn|>filter(DataYear==2024&Sex=="F"&Day_Night==1)
Filt_BK_spawn_24F_12h_Day_F   <-Filt_BK_Fin_spawn|>filter(DataYear==2024&Sex=="F"&Day_Night==0)

Filt_BK_spawn_19F_12h <- bind_rows(Filt_BK_spawn_19F_12h_Night_F,Filt_BK_spawn_19F_12h_Day_F)
Filt_BK_spawn_20F_12h <- bind_rows(Filt_BK_spawn_20F_12h_Night_F,Filt_BK_spawn_20F_12h_Day_F)
Filt_BK_spawn_21F_12h <- bind_rows(Filt_BK_spawn_21F_12h_Night_F,Filt_BK_spawn_21F_12h_Day_F)
Filt_BK_spawn_22F_12h <- bind_rows(Filt_BK_spawn_22F_12h_Night_F,Filt_BK_spawn_22F_12h_Day_F)
Filt_BK_spawn_23F_12h <- bind_rows(Filt_BK_spawn_23F_12h_Night_F,Filt_BK_spawn_23F_12h_Day_F)
Filt_BK_spawn_24F_12h <- bind_rows(Filt_BK_spawn_24F_12h_Night_F,Filt_BK_spawn_24F_12h_Day_F)

# Brownian Bridge movement models
# 2019 Male Night
BBKer_spawn_19M_12h_Night_M   <- as.ltraj(xy=Filt_BK_spawn_19M_12h_Night_M[,c("X","Y")],
                                          date = Filt_BK_spawn_19M_12h_Night_M$DATETIME,
                                          id=factor(Filt_BK_spawn_19M_12h_Night_M$Ser_Per_Year_Date_Diel),
                                          burst=Filt_BK_spawn_19M_12h_Night_M$Burst_b)
tnm_spawn_19M_12h_dd_Night_M  <- kernelbb(BBKer_spawn_19M_12h_Night_M,sig1 =0.8408408,sig2=4,byburst = TRUE, grid=xy)##Done
tnm_spawn_19M_12h_dd_Night_9  <- tnm_spawn_19M_12h_dd_Night_M
save(tnm_spawn_19M_12h_dd_Night_9, file = "tnm_spawn_19M_12h_dd_Night_9.Rdata")
load("tnm_spawn_19M_12h_dd_Night_9.Rdata")

# 2019 Male Day
BBKer_spawn_19M_12h_Day_M     <- as.ltraj(xy=Filt_BK_spawn_19M_12h_Day_M[,c("X","Y")],
                                          date = Filt_BK_spawn_19M_12h_Day_M$DATETIME,
                                          id=factor(Filt_BK_spawn_19M_12h_Day_M$Ser_Per_Year_Date_Diel),
                                          burst=Filt_BK_spawn_19M_12h_Day_M$Burst_b)
tnm_spawn_19M_12h_dd_Day_M   <- kernelbb(BBKer_spawn_19M_12h_Day_M,sig1 =0.8408408,sig2=4,byburst = TRUE, grid=xy)##Done
tnm_spawn_19M_12h_dd_Day_9   <- tnm_spawn_19M_12h_dd_Day_M
save(tnm_spawn_19M_12h_dd_Day_9, file = "tnm_spawn_19M_12h_dd_Day_9.Rdata")
load("tnm_spawn_19M_12h_dd_Day_9.Rdata")

# 2021 Male Night
BBKer_spawn_21M_12h_Night_M   <-as.ltraj(xy=Filt_BK_spawn_21M_12h_Night_M[,c("X","Y")],
                                         date = Filt_BK_spawn_21M_12h_Night_M$DATETIME,
                                         id=factor(Filt_BK_spawn_21M_12h_Night_M$Ser_Per_Year_Date_Diel),
                                         burst=Filt_BK_spawn_21M_12h_Night_M$Burst_b)
tnm_spawn_21M_12h_dd_Night_M  <-kernelbb(BBKer_spawn_21M_12h_Night_M,sig1 =0.8408408,sig2=4,byburst = TRUE, grid=xy)##Done
tnm_spawn_21M_12h_dd_Night_9 <- tnm_spawn_21M_12h_dd_Night_M
save(tnm_spawn_21M_12h_dd_Night_9, file = "tnm_spawn_21M_12h_dd_Night_9.Rdata")
load("tnm_spawn_21M_12h_dd_Night_9.Rdata")

# 2021 Male Day
BBKer_spawn_21M_12h_Day_M     <-as.ltraj(xy=Filt_BK_spawn_21M_12h_Day_M[,c("X","Y")],
                                         date = Filt_BK_spawn_21M_12h_Day_M$DATETIME,
                                         id=factor(Filt_BK_spawn_21M_12h_Day_M$Ser_Per_Year_Date_Diel),
                                         burst=Filt_BK_spawn_21M_12h_Day_M$Burst_b)
tnm_spawn_21M_12h_dd_Day_M  <-kernelbb(BBKer_spawn_21M_12h_Day_M,sig1 =0.8408408,sig2=4,byburst = TRUE, grid=xy)##Done
tnm_spawn_21M_12h_dd_Day_9<-tnm_spawn_21M_12h_dd_Day_M
save(tnm_spawn_21M_12h_dd_Day_9, file="tnm_spawn_21M_12h_dd_Day_9.Rdata")
load("tnm_spawn_21M_12h_dd_Day_9.Rdata")

# 2022 Male Night
BBKer_spawn_22M_12h_Night_M   <-as.ltraj(xy=Filt_BK_spawn_22M_12h_Night_M[,c("X","Y")],
                                         date = Filt_BK_spawn_22M_12h_Night_M$DATETIME,
                                         id=factor(Filt_BK_spawn_22M_12h_Night_M$Ser_Per_Year_Date_Diel),
                                         burst=Filt_BK_spawn_22M_12h_Night_M$Burst_b)
tnm_spawn_22M_12h_dd_Night_M  <-kernelbb(BBKer_spawn_22M_12h_Night_M,sig1 =0.8408408,sig2=4,byburst = TRUE, grid=xy)##Done
tnm_spawn_22M_12h_dd_Night_9<-tnm_spawn_22M_12h_dd_Night_M
save(tnm_spawn_22M_12h_dd_Night_9,file="tnm_spawn_22M_12h_dd_Night_9.Rdata")
load("tnm_spawn_22M_12h_dd_Night_9.Rdata")

# 2022 Male Day
BBKer_spawn_22M_12h_Day_M     <-as.ltraj(xy=Filt_BK_spawn_22M_12h_Day_M[,c("X","Y")],
                                         date = Filt_BK_spawn_22M_12h_Day_M$DATETIME,
                                         id=factor(Filt_BK_spawn_22M_12h_Day_M$Ser_Per_Year_Date_Diel),
                                         burst=Filt_BK_spawn_22M_12h_Day_M$Burst_b)
tnm_spawn_22M_12h_dd_Day_M  <-kernelbb(BBKer_spawn_22M_12h_Day_M,sig1 =0.8408408,sig2=4,byburst = TRUE, grid=xy)##Done
tnm_spawn_22M_12h_dd_Day_9<-tnm_spawn_22M_12h_dd_Day_M
save(tnm_spawn_22M_12h_dd_Day_9,file="tnm_spawn_22M_12h_dd_Day_9.Rdata")
load("tnm_spawn_22M_12h_dd_Day_9.Rdata")

# 2023 Male Night
BBKer_spawn_23M_12h_Night_M   <-as.ltraj(xy=Filt_BK_spawn_23M_12h_Night_M[,c("X","Y")],
                                         date = Filt_BK_spawn_23M_12h_Night_M$DATETIME,
                                         id=factor(Filt_BK_spawn_23M_12h_Night_M$Ser_Per_Year_Date_Diel),
                                         burst=Filt_BK_spawn_23M_12h_Night_M$Burst_b)
tnm_spawn_23M_12h_dd_Night_M <- kernelbb(BBKer_spawn_23M_12h_Night_M,sig1 =0.8408408,sig2=4,byburst = TRUE, grid=xy)##Done
tnm_spawn_23M_12h_dd_Night_9 <- tnm_spawn_23M_12h_dd_Night_M
save(tnm_spawn_23M_12h_dd_Night_9,file="tnm_spawn_23M_12h_dd_Night_9.Rdata")
load("tnm_spawn_23M_12h_dd_Night_9.Rdata")

# 2023 Male Day
BBKer_spawn_23M_12h_Day_M     <-as.ltraj(xy=Filt_BK_spawn_23M_12h_Day_M[,c("X","Y")],
                                         date = Filt_BK_spawn_23M_12h_Day_M$DATETIME,
                                         id=factor(Filt_BK_spawn_23M_12h_Day_M$Ser_Per_Year_Date_Diel),
                                         burst=Filt_BK_spawn_23M_12h_Day_M$Burst_b)
tnm_spawn_23M_12h_dd_Day_M  <-kernelbb(BBKer_spawn_23M_12h_Day_M,sig1 =0.8408408,sig2=4,byburst = TRUE, grid=xy)##Done
tnm_spawn_23M_12h_dd_Day_9<-tnm_spawn_23M_12h_dd_Day_M
save(tnm_spawn_23M_12h_dd_Day_9, file="tnm_spawn_23M_12h_dd_Day_9.Rdata")
load("tnm_spawn_23M_12h_dd_Day_9.Rdata")

# 2024 Male Night
BBKer_spawn_24M_12h_Night_M   <-as.ltraj(xy=Filt_BK_spawn_24M_12h_Night_M[,c("X","Y")],
                                         date = Filt_BK_spawn_24M_12h_Night_M$DATETIME,
                                         id=factor(Filt_BK_spawn_24M_12h_Night_M$Ser_Per_Year_Date_Diel),
                                         burst=Filt_BK_spawn_24M_12h_Night_M$Burst_b)
tnm_spawn_24M_12h_dd_Night_M  <-kernelbb(BBKer_spawn_24M_12h_Night_M,sig1 =0.8408408,sig2=4,byburst = TRUE, grid=xy)##Done
tnm_spawn_24M_12h_dd_Night_9<-tnm_spawn_24M_12h_dd_Night_M
save(tnm_spawn_24M_12h_dd_Night_9,file="tnm_spawn_24M_12h_dd_Night_9.Rdata")
load("tnm_spawn_24M_12h_dd_Night_9.Rdata")

# 2024 Male Day
BBKer_spawn_24M_12h_Day_M     <-as.ltraj(xy=Filt_BK_spawn_24M_12h_Day_M[,c("X","Y")],
                                         date = Filt_BK_spawn_24M_12h_Day_M$DATETIME,
                                         id=factor(Filt_BK_spawn_24M_12h_Day_M$Ser_Per_Year_Date_Diel),
                                         burst=Filt_BK_spawn_24M_12h_Day_M$Burst_b)
tnm_spawn_24M_12h_dd_Day_M <- kernelbb(BBKer_spawn_24M_12h_Day_M,sig1 =0.8408408,sig2=4,byburst = TRUE, grid=xy)##Done
tnm_spawn_24M_12h_dd_Day_9 <- tnm_spawn_24M_12h_dd_Day_M
save(tnm_spawn_24M_12h_dd_Day_9,file="tnm_spawn_24M_12h_dd_Day_9.Rdata")
load("tnm_spawn_24M_12h_dd_Day_9.Rdata")

# 2020 has much data so we splited it into Month February (MF) and Month March (MM)
Filt_BK_spawn_20MF_12h_Night_M<-Filt_BK_Fin_spawn|>filter(DataYear==2020&Period==0&Sex=="M"&Month==2&Day_Night==1)
Filt_BK_spawn_20MM_12h_Night_M<-Filt_BK_Fin_spawn|>filter(DataYear==2020&Period==0&Sex=="M"&Month==3&Day_Night==1)

Filt_BK_spawn_20MF_12h_Day_M<-Filt_BK_Fin_spawn|>filter(DataYear==2020&Period==0&Sex=="M"&Month==2&Day_Night==0)
Filt_BK_spawn_20MM_12h_Day_M<-Filt_BK_Fin_spawn|>filter(DataYear==2020&Period==0&Sex=="M"&Month==3&Day_Night==0)

BBKer_spawn_20MF_12h_Night_M <- as.ltraj(xy=Filt_BK_spawn_20MF_12h_Night_M[,c("X","Y")],
                                         date = Filt_BK_spawn_20MF_12h_Night_M$DATETIME,
                                         id=factor(Filt_BK_spawn_20MF_12h_Night_M$Ser_Per_Year_Date_Diel),
                                         burst=Filt_BK_spawn_20MF_12h_Night_M$Burst_b)
tnm_spawn_20MF_12h_dd_Night_M<-kernelbb(BBKer_spawn_20MF_12h_Night_M,sig1 =0.8408408,sig2=4,byburst = TRUE, grid=xy)##Done
save(tnm_spawn_20MF_12h_dd_Night_M,file = "tnm_spawn_20MF_12h_dd_Night_M_noland.Rdata")

BBKer_spawn_20MM_12h_Night_M <- as.ltraj(xy=Filt_BK_spawn_20MM_12h_Night_M[,c("X","Y")],
                                         date = Filt_BK_spawn_20MM_12h_Night_M$DATETIME,
                                         id=factor(Filt_BK_spawn_20MM_12h_Night_M$Ser_Per_Year_Date_Diel),
                                         burst=Filt_BK_spawn_20MM_12h_Night_M$Burst_b)
tnm_spawn_20MM_12h_dd_Night_M<-kernelbb(BBKer_spawn_20MM_12h_Night_M,sig1 =0.8408408,sig2=4,byburst = TRUE, grid=xy)##Done
save(tnm_spawn_20MM_12h_dd_Night_M,file = "tnm_spawn_20MM_12h_dd_Night_M_noland.Rdata")

tnm_spawn_20M_12h_dd_Night_9 <- c(tnm_spawn_20MF_12h_dd_Night_M,tnm_spawn_20MM_12h_dd_Night_M)
save(tnm_spawn_20M_12h_dd_Night_9,file="tnm_spawn_20M_12h_dd_Night_9.Rdata")
load("tnm_spawn_20M_12h_dd_Night_9.Rdata")

BBKer_spawn_20MF_12h_Day_M <- as.ltraj(xy=Filt_BK_spawn_20MF_12h_Day_M[,c("X","Y")],
                                       date = Filt_BK_spawn_20MF_12h_Day_M$DATETIME,
                                       id=factor(Filt_BK_spawn_20MF_12h_Day_M$Ser_Per_Year_Date_Diel),
                                       burst=Filt_BK_spawn_20MF_12h_Day_M$Burst_b)
tnm_spawn_20MF_12h_dd_Day_M<-kernelbb(BBKer_spawn_20MF_12h_Day_M,sig1 =0.8408408,sig2=4,byburst = TRUE, grid=xy)##Done
save(tnm_spawn_20MF_12h_dd_Day_M,file = "tnm_spawn_20MF_12h_dd_Day_M_noland.Rdata")

BBKer_spawn_20MM_12h_Day_M <- as.ltraj(xy=Filt_BK_spawn_20MM_12h_Day_M[,c("X","Y")],
                                       date = Filt_BK_spawn_20MM_12h_Day_M$DATETIME,
                                       id=factor(Filt_BK_spawn_20MM_12h_Day_M$Ser_Per_Year_Date_Diel),
                                       burst=Filt_BK_spawn_20MM_12h_Day_M$Burst_b)
tnm_spawn_20MM_12h_dd_Day_M<-kernelbb(BBKer_spawn_20MM_12h_Day_M,sig1 =0.8408408,sig2=4,byburst = TRUE, grid=xy)##Done
save(tnm_spawn_20MM_12h_dd_Day_M,file = "tnm_spawn_20MM_12h_dd_Day_M_noland.Rdata")

tnm_spawn_20M_12h_dd_Day_9 <- c(tnm_spawn_20MF_12h_dd_Day_M,tnm_spawn_20MM_12h_dd_Day_M)
save(tnm_spawn_20M_12h_dd_Day_9,file="tnm_spawn_20M_12h_dd_Day_9.Rdata")
load("tnm_spawn_20M_12h_dd_Day_9.Rdata")


############################################################################
## This part of the script can be skipped as running it takes a long time
## lines 616 - 781
## We provide the HRBB_serial_date_all.zip file with the output files
############################################################################

# BBMM with day and night
# 2019 Male
BBKer_spawn_19M_12h <- asltraj(xy=Filt_BK_spawn_19M_12h[,c("X","Y")],
                               date=Filt_BK_spawn_19M_12h$DATETIME,
                               id=factor(Filt_BK_spawn_19M_12h$Ser_Per_Year_Date_Diel),
                               burst=Filt_BK_spawn_19M_12h$Burst_b)
tnm_spawn_19M_12h_dd_noland <- kernelbb(BBKer_spawn_19M_12h,sig1 =0.8408408,sig2=4,byburst = TRUE, grid=xy)
save(tnm_spawn_19M_12h_dd_noland,file="tnm_spawn_19M_12h_dd_noland.Rdata")
# 2020 Male Feb
BBKer_spawn_20MF_12h<-as.ltraj(xy=Filt_BK_spawn_20MF_12h[,c("X","Y")],
                               date = Filt_BK_spawn_20MF_12h$DATETIME,
                               id=factor(Filt_BK_spawn_20MF_12h$Ser_Per_Year_Date_Diel),
                               burst=Filt_BK_spawn_20MF_12h$Burst_b)
tnm_spawn_20MF_12h_dd<-kernelbb(BBKer_spawn_20MF_12h,sig1 =0.8408408,sig2=4,byburst = TRUE, grid=xy)
save(tnm_spawn_20MF_12h_dd,file = "tnm_spawn_20MF_12h_dd_noland.Rdata")
# 2020 Male March
BBKer_spawn_20MM_12h<-as.ltraj(xy=Filt_BK_spawn_20MM_12h[,c("X","Y")],
                               date = Filt_BK_spawn_20MM_12h$DATETIME,
                               id=factor(Filt_BK_spawn_20MM_12h$Ser_Per_Year_Date_Diel),
                               burst=Filt_BK_spawn_20MM_12h$Burst_b)
tnm_spawn_20MM_12h_dd<-kernelbb(BBKer_spawn_20MM_12h,sig1 =0.8408408,sig2=4,byburst = TRUE, grid=xy)
save(tnm_spawn_20MM_12h_dd,file = "tnm_spawn_20MM_12h_dd_noland.Rdata")
# 2021 Male
BBKer_spawn_21M_12h <- asltraj(xy=Filt_BK_spawn_21M_12h[,c("X","Y")],
                               date=Filt_BK_spawn_21M_12h$DATETIME,
                               id=factor(Filt_BK_spawn_21M_12h$Ser_Per_Year_Date_Diel),
                               burst=Filt_BK_spawn_21M_12h$Burst_b)
tnm_spawn_21M_12h_dd_noland <- kernelbb(BBKer_spawn_21M_12h,sig1 =0.8408408,sig2=4,byburst = TRUE, grid=xy)
save(tnm_spawn_21M_12h_dd_noland,file="tnm_spawn_21M_12h_dd_noland.Rdata")
# 2022 Male
BBKer_spawn_22M_12h <- asltraj(xy=Filt_BK_spawn_22M_12h[,c("X","Y")],
                               date=Filt_BK_spawn_22M_12h$DATETIME,
                               id=factor(Filt_BK_spawn_22M_12h$Ser_Per_Year_Date_Diel),
                               burst=Filt_BK_spawn_22M_12h$Burst_b)
tnm_spawn_22M_12h_dd_noland <- kernelbb(BBKer_spawn_22M_12h,sig1 =0.8408408,sig2=4,byburst = TRUE, grid=xy)
save(tnm_spawn_22M_12h_dd_noland,file="tnm_spawn_22M_12h_dd_noland.Rdata")
# 2023 Male
BBKer_spawn_23M_12h <- asltraj(xy=Filt_BK_spawn_23M_12h[,c("X","Y")],
                               date=Filt_BK_spawn_23M_12h$DATETIME,
                               id=factor(Filt_BK_spawn_23M_12h$Ser_Per_Year_Date_Diel),
                               burst=Filt_BK_spawn_23M_12h$Burst_b)
tnm_spawn_23M_12h_dd_noland <- kernelbb(BBKer_spawn_23M_12h,sig1 =0.8408408,sig2=4,byburst = TRUE, grid=xy)
save(tnm_spawn_23M_12h_dd_noland,file="tnm_spawn_23M_12h_dd_noland.Rdata")
# 2024 Male
BBKer_spawn_24M_12h <- asltraj(xy=Filt_BK_spawn_24M_12h[,c("X","Y")],
                               date=Filt_BK_spawn_24M_12h$DATETIME,
                               id=factor(Filt_BK_spawn_24M_12h$Ser_Per_Year_Date_Diel),
                               burst=Filt_BK_spawn_24M_12h$Burst_b)
tnm_spawn_24M_12h_dd_noland <- kernelbb(BBKer_spawn_24M_12h,sig1 =0.8408408,sig2=4,byburst = TRUE, grid=xy)
save(tnm_spawn_24M_12h_dd_noland,file="tnm_spawn_24M_12h_dd_noland.Rdata")
# 2019 Female
BBKer_spawn_19F_12h <- asltraj(xy=Filt_BK_spawn_19F_12h[,c("X","Y")],
                               date=Filt_BK_spawn_19F_12h$DATETIME,
                               id=factor(Filt_BK_spawn_19F_12h$Ser_Per_Year_Date_Diel),
                               burst=Filt_BK_spawn_19F_12h$Burst_b)
tnm_spawn_19F_12h_dd_noland <- kernelbb(BBKer_spawn_19F_12h,sig1 =0.8408408,sig2=4,byburst = TRUE, grid=xy)
save(tnm_spawn_19F_12h_dd_noland,file="tnm_spawn_19F_12h_dd_noland.Rdata")
# 2020 Female February
BBKer_spawn_20FF_12h<-as.ltraj(xy=Filt_BK_spawn_20FF_12h[,c("X","Y")],
                               date = Filt_BK_spawn_20FF_12h$DATETIME,
                               id=factor(Filt_BK_spawn_20FF_12h$Ser_Per_Year_Date_Diel),
                               burst=Filt_BK_spawn_20FF_12h$Burst_b)
tnm_spawn_20FF_12h_dd<-kernelbb(BBKer_spawn_20FF_12h,sig1 =0.8408408,sig2=4,byburst = TRUE, grid=xy)
save(tnm_spawn_20FF_12h_dd,file = "tnm_spawn_20FF_12h_dd_noland.Rdata")
# 2020 Female March
BBKer_spawn_20FM_12h<-as.ltraj(xy=Filt_BK_spawn_20FM_12h[,c("X","Y")],
                               date = Filt_BK_spawn_20FM_12h$DATETIME,
                               id=factor(Filt_BK_spawn_20FM_12h$Ser_Per_Year_Date_Diel),
                               burst=Filt_BK_spawn_20FM_12h$Burst_b)
tnm_spawn_20FM_12h_dd<-kernelbb(BBKer_spawn_20FM_12h,sig1 =0.8408408,sig2=4,byburst = TRUE, grid=xy)
save(tnm_spawn_20FM_12h_dd,file = "tnm_spawn_20FM_12h_dd_noland.Rdata")
# 2021 Female
BBKer_spawn_21F_12h <- asltraj(xy=Filt_BK_spawn_21F_12h[,c("X","Y")],
                               date=Filt_BK_spawn_21F_12h$DATETIME,
                               id=factor(Filt_BK_spawn_21F_12h$Ser_Per_Year_Date_Diel),
                               burst=Filt_BK_spawn_21F_12h$Burst_b)
tnm_spawn_21F_12h_dd_noland <- kernelbb(BBKer_spawn_21F_12h,sig1 =0.8408408,sig2=4,byburst = TRUE, grid=xy)
save(tnm_spawn_21F_12h_dd_noland,file="tnm_spawn_21F_12h_dd_noland.Rdata")
# 2022 Female
BBKer_spawn_22F_12h <- asltraj(xy=Filt_BK_spawn_22F_12h[,c("X","Y")],
                               date=Filt_BK_spawn_22F_12h$DATETIME,
                               id=factor(Filt_BK_spawn_22F_12h$Ser_Per_Year_Date_Diel),
                               burst=Filt_BK_spawn_22F_12h$Burst_b)
tnm_spawn_22F_12h_dd_noland <- kernelbb(BBKer_spawn_22F_12h,sig1 =0.8408408,sig2=4,byburst = TRUE, grid=xy)
save(tnm_spawn_22F_12h_dd_noland,file="tnm_spawn_22F_12h_dd_noland.Rdata")
# 2023 Female
BBKer_spawn_23F_12h <- asltraj(xy=Filt_BK_spawn_23F_12h[,c("X","Y")],
                               date=Filt_BK_spawn_23F_12h$DATETIME,
                               id=factor(Filt_BK_spawn_23F_12h$Ser_Per_Year_Date_Diel),
                               burst=Filt_BK_spawn_23F_12h$Burst_b)
tnm_spawn_23F_12h_dd_noland <- kernelbb(BBKer_spawn_23F_12h,sig1 =0.8408408,sig2=4,byburst = TRUE, grid=xy)
save(tnm_spawn_23F_12h_dd_noland,file="tnm_spawn_23F_12h_dd_noland.Rdata")
# 2024 Female
BBKer_spawn_24F_12h <- asltraj(xy=Filt_BK_spawn_24F_12h[,c("X","Y")],
                               date=Filt_BK_spawn_24F_12h$DATETIME,
                               id=factor(Filt_BK_spawn_24F_12h$Ser_Per_Year_Date_Diel),
                               burst=Filt_BK_spawn_24F_12h$Burst_b)
tnm_spawn_24F_12h_dd_noland <- kernelbb(BBKer_spawn_24F_12h,sig1 =0.8408408,sig2=4,byburst = TRUE, grid=xy)
save(tnm_spawn_24F_12h_dd_noland,file="tnm_spawn_24F_12h_dd_noland.Rdata")

###############################
### creating overlap files  ###
###############################

# UD files per year and 2020 is split into February (F) and March (M)
ud_files <- list("2019" = c("tnm_spawn_19F_12h_dd_noland.Rdata", "tnm_spawn_19M_12h_dd_noland.Rdata"),
                 "2020" = c("tnm_spawn_20FF_12h_dd_noland.Rdata", "tnm_spawn_20MF_12h_dd_noland.Rdata",
                            "tnm_spawn_20FM_12h_dd_noland.Rdata", "tnm_spawn_20MM_12h_dd_noland.Rdata"),
                 "2021" = c("tnm_spawn_21F_12h_dd_noland.Rdata", "tnm_spawn_21M_12h_dd_noland.Rdata"),
                 "2022" = c("tnm_spawn_22F_12h_dd_noland.Rdata", "tnm_spawn_22M_12h_dd_noland.Rdata"),
                 "2023" = c("tnm_spawn_23F_12h_dd_noland.Rdata", "tnm_spawn_23M_12h_dd_noland.Rdata"),
                 "2024" = c("tnm_spawn_24F_12h_dd_noland.Rdata", "tnm_spawn_24M_12h_dd_noland.Rdata"))

# Load all UD files of one year and combine them into one estUDm object
load_year_ud <- function(files) {
  ud <- list()
  for (f in files) {
    env <- new.env()
    load(f, envir = env)
    for (obj in ls(env)) ud <- c(ud, unlist(get(obj, envir = env)))}
  class(ud) <- "estUDm"
  ud}

# Bursts per fish or day, only with more than 1 burst
bursts_by <- function(year, group_var) {
  Filt_BK_Fin_spawn |>
    dplyr::filter(DataYear == year) |>
    dplyr::select(all_of(c(group_var, "Burst_b"))) |>
    distinct() |>
    group_by(across(all_of(group_var))) |>
    dplyr::filter(n() > 1) |>
    ungroup()}

# UDOI overlap between all bursts within each group, one CSV per group.
# Files that already exist are skipped
run_overlaps <- function(ud, bursts, group_var, year, label) {
  yy <- substr(year, 3, 4)
  for (g in sort(unique(bursts[[group_var]]))) {
    out_file <- paste0("Tot_", yy, "_", label, g, ".csv")
    if (file.exists(out_file)) next
    ids_to_keep <- as.character(bursts$Burst_b[bursts[[group_var]] == g])
    ud_g <- ud[ids_to_keep, drop = FALSE]
    class(ud_g) <- "estUDm"
    overlap_g <- kerneloverlaphr(ud_g, method = "UDOI", percent = 95)
    write.csv(overlap_g, file = out_file)}}

# Run all years
for (year in names(ud_files)) {
  message("---- ", year, " ----")
  yy  <- substr(year, 3, 4)
  Tot <- load_year_ud(ud_files[[year]])
  ## Home ranges (50% and 95%), only when file doesn't exist yet
  hr_file <- paste0("HRBB_", yy, "_12_noland_all.csv")
  if (!file.exists(hr_file)) {
    write.csv(kernel.area(Tot, percent = c(50, 95)), file = hr_file)}
  ## UDOI: site affinity
  run_overlaps(Tot, bursts_by(year, "Serial2"), "Serial2", year, "serial")
  ## UDOI: aggregation intensity
  run_overlaps(Tot, bursts_by(year, "Date_Corr"), "Date_Corr", year, "date")
  rm(Tot); gc()}

#########################################
## HomeRanges in Bakkasund; 50 and 95% ##
#########################################

Filt_BK<-read_csv("Bakkasund_filt_19_24_land_removed.csv")
Filt_BK<- Filt_BK|>mutate(DataYear=year(DATETIME),Month=month(DATETIME),Period=ifelse(Month%in%c(2:3),0,1))
# Fix dates and Time_Corr
Filt_BK<-Filt_BK|>mutate(Time_Fix=ifelse(is.na(DATETIMEsecs)==TRUE,
                                         as.POSIXct(paste(Date, "00:00:01"),
                                                    format = "%Y-%m-%d %H:%M:%S",tz="UTC"),NA))
Filt_BK<-Filt_BK|>mutate(DATETIMEsecs=ifelse(is.na(DATETIMEsecs)!=TRUE,DATETIMEsecs,Time_Fix-1))
Filt_BK<-Filt_BK|>mutate(Day_Night=ifelse(DATETIMEsecs>=sunupsecs&DATETIMEsecs<sundownsecs,0,1)) 
Filt_BK<-Filt_BK|>mutate(DataYear2=ifelse(Month==1,DataYear-1,DataYear))
Filt_BK<-Filt_BK|>filter(Month!=1&Month!=4)
Filt_BK<-Filt_BK|>mutate(Date_Corr=as.Date(ifelse(as.numeric(DATETIMEsecs)<as.numeric(sunupsecs),ymd(Date)-1,ymd(Date))))
Filt_BK<- Filt_BK|>mutate(Ser_Per_Year_Date_Diel=paste(Serial2,Period,DataYear2,Date_Corr,Day_Night,sep = "_"))
Filt_BK<-Filt_BK|>arrange(Ser_Per_Year_Date_Diel,DATETIMEsecs)
Ser_Year_Per_df<-as.data.frame(unique(Filt_BK$Ser_Per_Year_Date_Diel))
Ser_Year_Per_df<-Ser_Year_Per_df|>mutate(Burst1=1:25383)
colnames(Ser_Year_Per_df)<-c("Ser_Per_Year_Date_Diel","Burst_1")
Filt_BK<-Filt_BK|>left_join(Ser_Year_Per_df)
Filt_BK<-Filt_BK|>filter(is.na(DATETIMEsecs)==FALSE)
Filt_BK<-Filt_BK|>arrange(Ser_Per_Year_Date_Diel,DATETIMEsecs)
Filt_BK<-Filt_BK|>mutate(DTsecs_diff=DATETIMEsecs-lag(DATETIMEsecs))
Filt_BK<-Filt_BK|>mutate(Burst3=ifelse(Ser_Per_Year_Date_Diel!=lag(Ser_Per_Year_Date_Diel),0,
                                       ifelse(is.na(DTsecs_diff)==TRUE,0,      
                                              ifelse(Ser_Per_Year_Date_Diel==lag(Ser_Per_Year_Date_Diel)&DTsecs_diff<=43200,0,1))))
Filt_BK<-Filt_BK|>mutate(Burst3=ifelse(is.na(Burst3)==TRUE,0,Burst3))
Filt_BK<-Filt_BK|>mutate(Burst_b=cumsum(Burst3)+Burst_1)
Burst_dur_12h<-Filt_BK|>group_by(Burst_b)|>summarise(Hour_Dur=(max(DATETIMEsecs)-min(DATETIMEsecs))/(60*60),PosBurst=n())
Filt_BK<-Filt_BK|>left_join(Burst_dur_12h,by="Burst_b")
Ser_Burstb<-Filt_BK|>group_by(DataYear,Sex,MatStageComb,Period,Serial2,Day_Night,Burst_b,Length,Year)|>summarise(PosN=n())
Ser_Burstb_Mat_Spawwn_10<-Ser_Burstb|>filter(Period==0&MatStageComb=="Mat"&PosN>9)
Ser_Burstb_Mat_Spawwn_10_TY<-Ser_Burstb|>filter(Period==0&MatStageComb=="Mat"&PosN>9&DataYear==Year)

Overlap_Fish<-Ser_Burstb_Mat_Spawwn_10|>group_by(DataYear,Sex,MatStageComb,Period,Serial2,Day_Night)|>
  summarise(Nburst=n())|>filter(Nburst>1)

# Make test with just spawning and aggregated data
# Depths difference test- model suggestion
Filt_BK_Spawn<-Filt_BK|>filter(Period==0&MatStageComb=="Mat"&is.na(Sex)==FALSE)|>
  group_by(Year,Serial2,Day_Night,Sex)|>
  summarise(DepthMean=mean(Depth2,na.rm=TRUE),Numb=n())

Filt_BK_Spawn<-Filt_BK_Spawn|>filter(is.na(DepthMean)==FALSE)
Mod_depth_aggregate<-lmer(DepthMean~Sex*Day_Night+(1|Serial2)+(1|Year),
                          data = Filt_BK_Spawn,weights = sqrt(Numb),na.action = "na.fail")

summary(Mod_depth_aggregate)
M2<-dredge(Mod_depth_aggregate)
M2

#Final model
Mod_depth_aggregate<-lmer(DepthMean~Sex*Day_Night+(1|Serial2)+(1|Year),
                          data = Filt_BK_Spawn,weights = sqrt(Numb),na.action = "na.fail")
plot(Mod_depth_aggregate)

Filt_BK_Spawn<-Filt_BK_Spawn|>mutate(Day_Night=ifelse(Day_Night==0,"Day","Night"))

# get files with stem HRBB (home range brownian bridge)
# HRBB files in HRBB_serial_date_all.zip file
file_stem <- "HRBB"  
filenames <- list.files(pattern = paste0(file_stem, ".*\\.csv$"))

data_list <- lapply(filenames, function(file) {
  df <- read_csv(file)
  df <- df |>
    gather(c(2:as.numeric(ncol(df))),key=Burst_b,value=HR_size) |>
    separate(Burst_b,sep=1,c("X","Burst_b")) |>
    mutate(source_file = file) |>
    dplyr::select(-X)
  colnames(df)<-c("Per_HR","Burst_b","HR_size","Source_file")
  return(df)})  # Returner den modifiserte dataframe

combined_hr <- bind_rows(data_list)
combined_hr <- combined_hr[ !duplicated(apply(combined_hr, 1, sort), MARGIN = 2), ]
# Uses at least 10
Home_Range_All_feed<-combined_hr |>
  filter(str_detect(Source_file,"fd"))

Ser_Burstb<-Filt_BK |> 
  group_by(DataYear,Sex,MatStageComb,Period,Serial2,Day_Night,Burst_b,Length,Year)|>
  summarise(PosN=n())
Ser_Burstb_Mat_Spawwn_10 <- Ser_Burstb|>filter(Period==0 & MatStageComb=="Mat" & PosN>9)
Ser_Burstb_Mat_Spawwn_10_TY <- Ser_Burstb |>
  filter(Period==0 & MatStageComb=="Mat" & PosN>9 & DataYear==Year)

# Spawning Period tagging year 50%
Home_Range_All <- combined_hr |>
  anti_join(Home_Range_All_feed)
Home_Range_All_50 <- Home_Range_All |>
  filter(Per_HR==50)
Home_Range_All_50 <- Home_Range_All_50 |>
  mutate(Burst_b=as.numeric(Burst_b))
Home_Range_All_50 <- Home_Range_All_50 |>
  inner_join(Ser_Burstb_Mat_Spawwn_10_TY)
Home_Range_All_50_sum <- Home_Range_All_50 |>
  group_by(Serial2,Sex,Day_Night,Year,Length) |>
  summarise(MHR_50=mean(HR_size),
            DaysN=n(),
            TotPos=sum(PosN),
            MedianPos=median(PosN))
Home_Range_All_50_sum <- Home_Range_All_50_sum |>
  mutate(Day_Night=ifelse(Day_Night==0,"Day","Night"))  

# Spawning Period tagging year 95%
Home_Range_All_95 <- Home_Range_All |> filter(Per_HR==95)
Home_Range_All_95 <- Home_Range_All_95 |> mutate(Burst_b=as.numeric(Burst_b))
Home_Range_All_95 <- Home_Range_All_95 |> inner_join(Ser_Burstb_Mat_Spawwn_10_TY)
Home_Range_All_95_sum <- Home_Range_All_95 |>
  group_by(Serial2,Sex,Day_Night,Year,Length) |>
  summarise(MHR_95=mean(HR_size),
            DaysN=n(),
            TotPos=sum(PosN),
            MedianPos=median(PosN))
Home_Range_All_95_sum <- Home_Range_All_95_sum |>
  mutate(Day_Night=ifelse(Day_Night==0,"Day","Night"))
HR_50_merge <- Home_Range_All_50_sum |>
  ungroup() |>
  dplyr::select(Serial2,Year,Day_Night,MHR_50)
Home_Range_All_Bakka <- Home_Range_All_95_sum |>
  left_join(HR_50_merge,
            by=c("Serial2"="Serial2","Year"="Year","Day_Night"="Day_Night"))

HR_95new<-Home_Range_All_95_sum|>filter(is.na(Length)==FALSE)
HR_50new<-Home_Range_All_50_sum|>filter(is.na(Length)==FALSE)

# Test 50 % homerange
Mod1 <- lmerTest::lmer(I(log(MHR_50))~Sex*Day_Night*Length+(1|Serial2)+(1|Year),
                       HR_50new,
                       na.action = "na.fail",
                       weights = DaysN)
summary(Mod1)
M2<-dredge(Mod1)
M2
plot(Mod1)

HR_fin_50 <- lmerTest::lmer(I(log(MHR_50))~Sex*Day_Night+(1|Serial2)+(1|Year),
                            HR_50new,
                            na.action = "na.fail",
                            weights = sqrt(DaysN))
summary(HR_fin_50)
plot(HR_fin_50)

# Test 95 homerange
Mod1 <- lmerTest::lmer(I(log(MHR_95))~Sex*Day_Night*Length+(1|Serial2)+(1|Year),
                       HR_95new,
                       na.action = "na.fail",
                       weights = sqrt(DaysN))
summary(Mod1)
M2<-dredge(Mod1)
M2
plot(Mod1)

HR_fin_95 <- lmerTest::lmer(I(log(MHR_95))~Sex*Day_Night+(1|Serial2)+(1|Year),
                            HR_95new,
                            na.action = "na.fail",
                            weights = sqrt(DaysN))
summary(HR_fin_95)
plot(HR_fin_95)

# As length doesn't matter, we included the one fish without a length to the analysis by overwriting HR_95new
HR_95new <- Home_Range_All_95_sum
HR_50new <- Home_Range_All_50_sum

# All years not only tagging year 50%
Home_Range_All_50 <- Home_Range_All |>
  filter(Per_HR==50)
Home_Range_All_50 <- Home_Range_All_50 |>
  mutate(Burst_b=as.numeric(Burst_b))
Home_Range_All_50 <- Home_Range_All_50 |>
  inner_join(Ser_Burstb_Mat_Spawwn_10)
Home_Range_All_50_sum <- Home_Range_All_50 |>
  group_by(Serial2,Sex,Day_Night,DataYear,Length) |>
  summarise(MHR_50=mean(HR_size),
            DaysN=n(),
            TotPos=sum(PosN),
            MedianPos=median(PosN))
Home_Range_All_50_sum <- Home_Range_All_50_sum |>
  mutate(Day_Night=ifelse(Day_Night==0,"Day","Night"))  
HR_50newb <- Home_Range_All_50_sum

Mod_50_all <- lmerTest::lmer(I(log(MHR_50))~Sex*Day_Night+(1|Serial2)+(1|DataYear),
                             HR_50newb,
                             na.action = "na.fail",
                             weights = DaysN)
summary(Mod_50_all)
M2<-dredge(Mod_50_all)
M2
plot(Mod_50_all)

# All years not only tagging year 95%
Home_Range_All_95 <- Home_Range_All |> filter(Per_HR==95)
Home_Range_All_95 <- Home_Range_All_95 |> mutate(Burst_b=as.numeric(Burst_b))
Home_Range_All_95 <- Home_Range_All_95 |> inner_join(Ser_Burstb_Mat_Spawwn_10)
Home_Range_All_95_sum <- Home_Range_All_95 |>
  group_by(Serial2,Sex,Day_Night,DataYear,Length) |>
  summarise(MHR_95=mean(HR_size),
            DaysN=n(),
            TotPos=sum(PosN),
            MedianPos=median(PosN))
Home_Range_All_95_sum <- Home_Range_All_95_sum |>
  mutate(Day_Night=ifelse(Day_Night==0,"Day","Night"))
HR_95newb <- Home_Range_All_95_sum

Mod_95_all <- lmerTest::lmer(I(log(MHR_95))~Sex*Day_Night+(1|Serial2)+(1|DataYear),
                             HR_95newb,
                             na.action = "na.fail",
                             weights = sqrt(DaysN))
summary(Mod_95_all)
M2<-dredge(Mod_95_all)
M2
plot(Mod_95_all)

HR_fin_95 <- lmerTest::lmer(I(log(MHR_95))~Sex*Day_Night+(1|Serial2)+(1|DataYear),
                            HR_95newb,
                            na.action = "na.fail",
                            weights = sqrt(DaysN))
summary(HR_fin_95)
plot(HR_fin_95)

tab_model(Mod_50_all,Mod_95_all,file="Home_Range_Tests_All.doc")

###################
## Site affinity ##
###################

# serial files in HRBB_serial_date_all.zip file
file_stem <- "serial"  
filenames <- list.files(pattern = paste0(file_stem, ".*\\.csv$"))
data_list <- lapply(filenames, function(file) {
  df <- read_csv(file)
  df <- df |>
    gather(c(2:as.numeric(ncol(df))),key=Ser2,value=UDOI_Overlap) |>
    mutate(Ser2=as.numeric(Ser2)) |>
    mutate(source_file = file)
  return(df)})

combined_df <- bind_rows(data_list)
combined_df <- combined_df[ !duplicated(apply(combined_df, 1, sort), MARGIN = 2), ]

# Here I take out Osen data files and the non-spawning period
Tot_comb_Osen <- combined_df |>
  filter(str_detect(source_file,"Osen"))
Tot_comb_all <- combined_df |>
  anti_join(Tot_comb_Osen)
Tot_comb_feed <- Tot_comb_all |>
  filter(str_detect(source_file,"feed")) #Bakkasund feeding period
Tot_comb <- Tot_comb_all |>
  anti_join(Tot_comb_feed) #Bakkasund spawning period

Ser_Burstc <- Filt_BK |>
  group_by(DataYear,Sex,MatStageComb,Period,Ser_Per_Year_Date_Diel,Day_Night,Burst_b,Length,Year) |>
  summarise(PosN=n())
Ser_Burstc_Mat_Spawwn_10 <- Ser_Burstc |>
  filter(Period==0 & MatStageComb=="Mat" & PosN>9)
Ser_Burstc_Mat_Spawwn_10_TY <- Ser_Burstc |> filter(Period==0&MatStageComb=="Mat" & PosN>9 & DataYear==Year)

# inner_join overlap data with Ser_burstc
Tot_comb<-Tot_comb|>
  inner_join(Ser_Burstc_Mat_Spawwn_10,by=c("...1"="Burst_b")) |>
  inner_join(Ser_Burstc_Mat_Spawwn_10,by=c("Ser2"="Burst_b"))

Tot_comb <- Tot_comb |>
  separate("Ser_Per_Year_Date_Diel.x",sep = "_",c("Serial","Period","Year","Date_Corr","Diel"))
Tot_comb <- Tot_comb |>
  separate("Ser_Per_Year_Date_Diel.y",sep = "_",c("Serial2","Period2","Year2","Date_Corr2","Diel2"))
Tot_comb_sum <- Tot_comb |>
  group_by(Serial,Date_Corr,Diel,...1) |>
  summarise(NumbFish=n()) |>
  group_by(Serial,Date_Corr,Diel) |>
  summarise(NBurst=n())

##Same fish next day, i.e. site affinity. Here we have not filtered out fish with few positions, should we?
Same_Fish_Next_Day <- Tot_comb |>
  filter(Serial==Serial2 & Diel==Diel2 & Date_Corr!=Date_Corr2)
Same_Fish_Next_Day <- Same_Fish_Next_Day |>
  mutate(Day_Diff=abs(as.numeric(as.Date(Date_Corr)-as.numeric(as.Date(Date_Corr2)))))
Same_Fish_Next_Day <- Same_Fish_Next_Day |>
  filter(Day_Diff==1)
Same_Fish_Next_Day <- Same_Fish_Next_Day[ !duplicated(apply(Same_Fish_Next_Day, 1, sort), MARGIN = 2), ]
Sum_SFND <- Same_Fish_Next_Day |>
  group_by(Serial,Diel,Sex.x,Year) |>
  summarise(Site_affinity=mean(UDOI_Overlap),DayO=n()+1)
Sum_SFND <- Sum_SFND |>
  mutate(Diel=as.numeric(Diel),
         Day_Night=ifelse(Diel==0,"Day","Night"))

Sum_SFND <- Sum_SFND |>
  mutate(Year=as.numeric(Year),Day_Night=ifelse(Diel==0,"Day","Night"))
HR_95newb <- HR_95newb |>
  mutate(Year=as.numeric(DataYear)) |>
  dplyr::select(Serial2,Day_Night,DataYear,Year,MHR_95,Sex)
Sum_SFND_95_HRBK <- Sum_SFND |>
  mutate(Serial=as.numeric(Serial)) |>
  left_join(HR_95newb,
            by=c("Serial"="Serial2","Day_Night"="Day_Night","Year"="Year"))
Sum_SFND_95_HRBK <- Sum_SFND_95_HRBK |>
  filter(is.na(Sex)==FALSE)
mean(Sum_SFND_95_HRBK$Site_affinity)

#Model testing
Mod1_site_affinity <- lmerTest::lmer(Site_affinity~Sex*factor(Diel)+I(log(MHR_95))+(1|Serial)+(1|Year),
                                     data = Sum_SFND_95_HRBK,
                                     weights = sqrt(DayO),
                                     na.action = "na.fail")
summary(Mod1_site_affinity)
M2<-dredge(Mod1_site_affinity)
M2
Mod1_overlap_fin <- lmerTest::lmer(Site_affinity~Sex+factor(Diel)+I(log(MHR_95))+(1|Serial)+(1|Year),
                                   data = Sum_SFND_95_HRBK,
                                   weights = sqrt(DayO),
                                   na.action = "na.fail")
summary(Mod1_overlap_fin)
plot(Mod1_overlap_fin)
tab_model(Mod1_overlap_fin,file="Site_affinity_fin_all_1026.doc")

##################################
########### Fig. 3   #############
##################################

Sum_SFND_95_HRBK <- Sum_SFND_95_HRBK |>
  mutate(log_MHR95=log(MHR_95))
Mod1_overlap_finb <- lmerTest::lmer(Site_affinity~Sex+factor(Diel)+log_MHR95+(1|Serial)+(1|Year),
                                    data = Sum_SFND_95_HRBK,
                                    na.action = "na.fail",
                                    weights = sqrt(DayO))
summary(Mod1_overlap_finb)

ggpb <- ggpredict(Mod1_overlap_finb,
                  terms = c("log_MHR95[all]", "Sex", "Diel"),
                  type = "fixed") 

ggpb <- as.data.frame(ggpb)
ggpb <- ggpb |>
  ungroup() |>
  mutate(Day_Night=ifelse(facet==0,"Day","Night"),
         Site_affinity=predicted,
         MHR_95=exp(x),
         Sex=group) |>
  filter(Day_Night=="Day"&MHR_95<13|Day_Night!="Day")

summary_site_affinity <- Sum_SFND_95_HRBK  |> 
  dplyr::group_by(Year,Sex, Diel) |> 
  dplyr::summarise(n = n(),
                   mean_site_affinity = round(mean(Site_affinity, na.rm = TRUE), 3),
                   sd_site_affinity = round(sd(Site_affinity, na.rm = TRUE), 3),
                   median_site_affinity = round(median(Site_affinity, na.rm = TRUE), 3),
                   min_site_affinity = round(min(Site_affinity, na.rm = TRUE), 3),
                   max_site_affinity = round(max(Site_affinity, na.rm = TRUE), 3),
                   .groups = "drop")  |> 
  arrange(Year,Sex, Diel)
summary_site_affinity

avg_affinity_summary <- Sum_SFND_95_HRBK |>
  dplyr::group_by(Sex.x, Day_Night) |>
  dplyr::summarise(avg = mean(Site_affinity, na.rm = TRUE))
avg_affinity_summary

Bakka_ov_10 <- ggplot(ggpb, aes(MHR_95, Site_affinity, color = Sex, fill = Sex)) +
  geom_ribbon(aes(ymin = conf.low, ymax = conf.high),
              alpha = 0.2, color = NA) +
  geom_line(size = 1, alpha = 0.5) +
  geom_hline(data = avg_affinity_summary, 
             aes(yintercept = avg, color = Sex.x),
             linetype = "dotted", linewidth = 0.8) +
  facet_wrap(~ Day_Night, scales = "free_x") +
  labs(x     = "Home range size (ha)",
       y     = "Site affinity",
       color = "Sex",
       fill  = "Sex",
       size  = "Days observed") +
  theme_JE +
  scale_color_manual(breaks = c("F", "M"),
                     values = c("red", "blue"),
                     labels = c("Female", "Male")) +
  scale_fill_manual(breaks = c("F", "M"),
                    values = c("red", "blue"),
                    labels = c("Female", "Male")) +
  scale_size_continuous(breaks = c(2, 20, 50),
                        range  = c(1, 6)) +
  coord_cartesian(ylim = c(0, 2.3)) +
  theme(legend.position   = c(0.9, 0.80),
        strip.text        = element_text(size = 12, face = "plain"),
        axis.text         = element_text(size = 12),
        axis.title        = element_text(size = 12)) +
  guides(size  = guide_legend(title    = "Days observed",
                              override.aes = list(alpha = 0.5, color = "blue")),
         color = guide_legend(override.aes = list(size = 3))) +
  geom_point(data = Sum_SFND_95_HRBK,
             aes(MHR_95, Site_affinity, size = DayO, col = Sex),
             alpha = 0.5)
Bakka_ov_10

#################################################
########### Aggregation Intensity   #############
#################################################

# date files in HRBB_serial_date_all.zip file
file_stem <- "date"  
filenames <- list.files(pattern = paste0(file_stem, ".*\\.csv$"))

data_list <- lapply(filenames, function(file) {
  df <- read_csv(file)
  df <- df |>
    gather(c(2:as.numeric(ncol(df))),key=Ser2,value=Overlap)|>
    mutate(Ser2=as.numeric(Ser2))|>
    mutate(source_file = file)
  return(df)})

combined_dfb <- bind_rows(data_list)
combined_dfb <- combined_dfb[ !duplicated(apply(combined_dfb, 1, sort), MARGIN = 2), ]
Tot_comb_of_Osen <- combined_dfb |>
  filter(str_detect(source_file,"Osen")) #Osen files
Tot_comb_of_all <- combined_dfb |>
  anti_join(Tot_comb_of_Osen) #Bakkasund
Tot_comb_of_feed <- Tot_comb_of_all |>
  filter(str_detect(source_file,"feed"))
Tot_comb_of <- Tot_comb_of_all |>
  anti_join(Tot_comb_of_feed) #Bakkasund

Tot_comb_of <- Tot_comb_of |>
  left_join(Ser_Burstc_Mat_Spawwn_10,by=c("...1"="Burst_b")) |>
  Tot_comb_of <- Tot_comb_of |> 
  separate("Ser_Per_Year_Date_Diel.x",
           sep = "_",
           c("Serial","Period","Year","Date_Corr","Diel"))
Tot_comb_of <- Tot_comb_of |> 
  separate("Ser_Per_Year_Date_Diel.y",
           sep = "_",
           c("Serial2","Period2","Year2","Date_Corr2","Diel2"))
Tot_comb_sum<-Tot_comb_of |> 
  group_by(Serial,Date_Corr,Diel,...1) |>
  summarise(NumbFish=n())|>
  group_by(Serial,Date_Corr,Diel) |>
  summarise(NBurst=n())

Diff_Fish_Same_Day <- Tot_comb_of |>
  filter(Serial!=Serial2 & Diel==Diel2 & Date_Corr==Date_Corr2)
Diff_Fish_Same_Day <- Diff_Fish_Same_Day[ !duplicated(apply(Diff_Fish_Same_Day, 1, sort), MARGIN = 2), ]
Diff_Fish_Same_Day <- Diff_Fish_Same_Day |>
  mutate(Sex_Comb=paste(Sex.x,Sex.y,sep=""))
DFSD1<-Diff_Fish_Same_Day |> 
  dplyr::select(Serial,Sex_Comb,Diel,Year,Overlap,Date_Corr)
DFSD2<-Diff_Fish_Same_Day |> 
  dplyr::select(Serial2,Sex_Comb,Diel,Year,Overlap,Date_Corr2)
colnames(DFSD2) <- c("Serial","Sex_Comb","Diel","Year","Overlap","Date_Corr")

DFSD<-rbind(DFSD1,DFSD2)
DFSD_Sex_Comb_date <- DFSD |>
  group_by(Sex_Comb,Diel,Date_Corr,Serial) |>
  summarise(Pos=n()) |>
  group_by(Sex_Comb,Diel,Date_Corr)|>
  summarise(FishNOverLap=n())

DFSD_sum_org<-DFSD |>
  group_by(Serial,Sex_Comb,Diel,Year) |>
  summarise(MeanO=mean(Overlap),Numb=n()) |>
  mutate(Sex_Comb=ifelse(Sex_Comb=="FM","MF",Sex_Comb),
         Day_Night=ifelse(as.numeric(Diel)==0,"Day","Night"))

DFSD_sum<-DFSD |>
  dplyr::mutate(Sex_Comb=ifelse(Sex_Comb=="FM","MF",Sex_Comb),
                Day_Night=ifelse(as.numeric(Diel)==0,"Day","Night"))|>
  dplyr::group_by(Serial,Sex_Comb,Day_Night,Year,Date_Corr)|>
  dplyr::summarise(MeanO=mean(Overlap),Numb=n(),.groups = "drop")|>
  dplyr::group_by(Serial,Sex_Comb,Day_Night,Year)|>
  dplyr::summarise(MeanO=mean(MeanO),FishN=sum(Numb),DaySO=n(),.groups="drop")

DFSD_sum |> 
  dplyr::filter(Sex_Comb=="MM") |> 
  ungroup() |> 
  dplyr::summarise(max_MeanO=max(MeanO), 
                   min_MeanO=min(MeanO),
                   mean_MeanO = mean(MeanO))

DFSD_high<-DFSD|>filter(Overlap>1) |>
  group_by(Sex_Comb) |>
  summarise(NPairs=n()/2)

summary_ODF <- ODF_BK_2$data |>
  dplyr::group_by(Year, Day_Night, Sex_Comb) |>
  dplyr::summarise(n = n(),
                   mean_MeanO = round(mean(MeanO, na.rm = TRUE), 4),
                   sd_MeanO = round(sd(MeanO, na.rm = TRUE), 4),
                   median_MeanO = round(median(MeanO, na.rm = TRUE), 4),
                   min_MeanO = round(min(MeanO, na.rm = TRUE), 4),
                   max_MeanO = round(max(MeanO, na.rm = TRUE), 4),
                   .groups = "drop")  |> 
  arrange(Year, Day_Night, Sex_Comb)

summary_ODF

OvDF_BK<-DFSD_sum|>group_by(Sex_Comb)|>
  summarise(MMO=100*mean(MeanO),St_Dev=100*sd(MeanO),Numb=n(),min_MeanO=min(MeanO),max_MeanO=max(MeanO))
write.csv(OvDF_BK,file="ODVF_BK.csv",row.names = FALSE)

DFSD_sum$Sex_Comb <- fct_relevel(DFSD_sum$Sex_Comb, "MM")
Mod1_log <- lmerTest::lmer(log(MeanO+0.000001) ~ Sex_Comb*Day_Night + (1 | Serial) + (1 | Year),
                           data    = DFSD_sum,
                           na.action = "na.fail",
                           weights = sqrt(DaySO))

plot(Mod1_log)
M2<-dredge(Mod1_log)
M2

Mod1_log_fin<-lmerTest::lmer(log(MeanO+0.000001) ~ Sex_Comb + (1 | Serial) + (1 | Year),
                             data    = DFSD_sum,
                             na.action = "na.fail",
                             weights = sqrt(DaySO))
summary(Mod1_log_fin)
tab_model(Mod1_log_fin,file="Aggregation_Intensity_log_new1026.doc")

##################################################
########### Dean Overlap Calculation #############
##################################################

###############################################################################
## This part of the script can be skipped as running it takes a long time
## lines 1305 - 1367
## We provide the Dean_overlap_serial_date_all.zip file with the output files
###############################################################################

dean_overlap_traj <- "" # fill in own trajectory

# UD files per year, 2020 is split into February (F) and March (M)
ud_files <- list("2019" = c("tnm_spawn_19F_12h_dd_noland.Rdata", "tnm_spawn_19M_12h_dd_noland.Rdata"),
                 "2020" = c("tnm_spawn_20FF_12h_dd_noland.Rdata", "tnm_spawn_20MF_12h_dd_noland.Rdata",
                            "tnm_spawn_20FM_12h_dd_noland.Rdata", "tnm_spawn_20MM_12h_dd_noland.Rdata"),
                 "2021" = c("tnm_spawn_21F_12h_dd_noland.Rdata", "tnm_spawn_21M_12h_dd_noland.Rdata"),
                 "2022" = c("tnm_spawn_22F_12h_dd_noland.Rdata", "tnm_spawn_22M_12h_dd_noland.Rdata"),
                 "2023" = c("tnm_spawn_23F_12h_dd_noland.Rdata", "tnm_spawn_23M_12h_dd_noland.Rdata"),
                 "2024" = c("tnm_spawn_24F_12h_dd_noland.Rdata", "tnm_spawn_24M_12h_dd_noland.Rdata"))

# Functions, load all UD files of one year and combine them into one estUDm object
load_year_ud <- function(files) {
  ud <- list()
  for (f in files) {
    env <- new.env()
    load(file.path(dean_overlap_traj, f), envir = env)
    for (obj in ls(env)) ud <- c(ud, unlist(get(obj, envir = env)))}
  class(ud) <- "estUDm"
  ud}

# Bursts per fish or per date, only groups with more than 1 burst
bursts_by <- function(year, group_var) {
  Filt_BK_Fin_spawn |>
    dplyr::filter(DataYear == year) |>
    dplyr::select(all_of(c(group_var, "Burst_b"))) |>
    distinct() |>
    group_by(across(all_of(group_var))) |>
    dplyr::filter(n() > 1) |>
    ungroup()}

# HR overlap between all bursts within each group, 1 csv per group, files that already exist skipped
run_hr_overlaps <- function(ud, bursts, group_var, year, label) {
  yy <- substr(year, 3, 4)
  for (g in sort(unique(bursts[[group_var]]))) {
    out_file <- file.path(dean_overlap_traj, paste0("Tot_", yy, "_", label, g, ".csv"))
    if (file.exists(out_file)) next
    ids_to_keep <- as.character(bursts$Burst_b[bursts[[group_var]] == g])
    ud_g <- ud[ids_to_keep, drop = FALSE]
    class(ud_g) <- "estUDm"
    overlap_g <- kerneloverlaphr(ud_g, method = "HR", percent = 95)
    write.csv(overlap_g, file = out_file)}}

# Run all years
for (year in names(ud_files)) {
  message("-- ", year, " --")
  yy  <- substr(year, 3, 4)
  Tot <- load_year_ud(ud_files[[year]])
  # Home ranges (50% and 95%)
  write.csv(kernel.area(Tot, percent = c(50, 95)),
            file = file.path(dean_overlap_traj, paste0("HRBB_", yy, "_12_noland_all.csv")))
  # Site affinity
  run_hr_overlaps(Tot, bursts_by(year, "Serial2"), "Serial2", year, "serialHR")
  # Aggregation intensity
  run_hr_overlaps(Tot, bursts_by(year, "Date_Corr"), "Date_Corr", year, "dateHR")
  rm(Tot); gc()}

# data
Filt_BK <- read_csv("Bakkasund_filt_19_24_land_removed.csv") |> 
  mutate(DataYear=year(DATETIME),Month=month(DATETIME),Period=ifelse(Month%in%c(2:3),0,1))
Filt_BK<-Filt_BK |>
  mutate(Time_Fix=ifelse(is.na(DATETIMEsecs)==TRUE,
                         as.POSIXct(paste(Date, "00:00:01"),
                                    format = "%Y-%m-%d %H:%M:%S",tz="UTC"),NA))
Filt_BK<-Filt_BK |>
  mutate(DATETIMEsecs=ifelse(is.na(DATETIMEsecs)!=TRUE,DATETIMEsecs,Time_Fix-1))
Filt_BK<-Filt_BK |>
  mutate(Day_Night=ifelse(DATETIMEsecs>=sunupsecs&DATETIMEsecs<sundownsecs,0,1)) 
unique(Filt_BK$Day_Night)
Filt_BK<-Filt_BK |>
  mutate(DataYear2=ifelse(Month==1,DataYear-1,DataYear))
Filt_BK<-Filt_BK |>
  filter(Month!=1&Month!=4)
Filt_BK <-Filt_BK|>
  mutate(Date_Corr=as.Date(ifelse(as.numeric(DATETIMEsecs)<as.numeric(sunupsecs),ymd(Date)-1,ymd(Date))))
Filt_BK<- Filt_BK |>
  mutate(Ser_Per_Year_Date_Diel=paste(Serial2,Period,DataYear2,Date_Corr,Day_Night,sep = "_"))
Filt_BK<-Filt_BK |>
  arrange(Ser_Per_Year_Date_Diel,DATETIMEsecs)
Ser_Year_Per_df <- as.data.frame(unique(Filt_BK$Ser_Per_Year_Date_Diel))
Ser_Year_Per_df <- Ser_Year_Per_df |>
  mutate(Burst1=1:25383)
colnames(Ser_Year_Per_df)<-c("Ser_Per_Year_Date_Diel","Burst_1")
Filt_BK<-Filt_BK |> left_join(Ser_Year_Per_df)
Filt_BK<-Filt_BK |> filter(is.na(DATETIMEsecs)==FALSE)
Filt_BK<-Filt_BK |> arrange(Ser_Per_Year_Date_Diel,DATETIMEsecs)
Filt_BK<-Filt_BK |> mutate(DTsecs_diff=DATETIMEsecs-lag(DATETIMEsecs))
Filt_BK<-Filt_BK |> mutate(Burst3=ifelse(Ser_Per_Year_Date_Diel!=lag(Ser_Per_Year_Date_Diel),0,
                                         ifelse(is.na(DTsecs_diff)==TRUE,0,      
                                                ifelse(Ser_Per_Year_Date_Diel==lag(Ser_Per_Year_Date_Diel)&DTsecs_diff<=43200,0,1))))
Filt_BK<-Filt_BK |> mutate(Burst3=ifelse(is.na(Burst3)==TRUE,0,Burst3))
Filt_BK<-Filt_BK |> mutate(Burst_b=cumsum(Burst3)+Burst_1)

Burst_dur_12h<-Filt_BK|>group_by(Burst_b)|>summarise(Hour_Dur=(max(DATETIMEsecs)-min(DATETIMEsecs))/(60*60),PosBurst=n())
Filt_BK<-Filt_BK|>left_join(Burst_dur_12h,by="Burst_b")

Ser_Burst<-Filt_BK|>group_by(DataYear,Sex,MatStageComb,Ser_Per_Year_Date_Diel,Burst_b,Length,Year)|>summarise(PosN=n())
Ser_Burst_TY<-Ser_Burst|>filter(DataYear==Year)
Ser_Burst_Month<-Filt_BK|>group_by(DataYear,Month,Sex,MatStageComb,Ser_Per_Year_Date_Diel,Burst_b)|>summarise(PosN=n())
Ser_Burst_check<-Ser_Burst|>group_by(Ser_Per_Year_Date_Diel,Burst_b)|>summarise(PosN=n())

# Home Ranges only Bakkasund
# HRBB files in HRBB_serial_date_all.zip file
file_stem <- "HRBB"  
filenames <- list.files(pattern = paste0(file_stem, ".*\\.csv$"))

data_list <- lapply(filenames, function(file) {
  df <- read_csv(file)
  df <- df |>
    gather(c(2:as.numeric(ncol(df))),key=Burst_b,value=HR_size)|>
    separate(Burst_b,sep=1,c("X","Burst_b"))|>
    mutate(source_file = file)|>
    dplyr::select(-X)
  colnames(df)<-c("Per_HR","Burst_b","HR_size","Source_file")
  return(df)})

combined_hr <- bind_rows(data_list)
combined_hr<-combined_hr[ !duplicated(apply(combined_hr, 1, sort), MARGIN = 2), ]
Ser_Burst_Merge<-Ser_Burst|>filter(MatStageComb=="Mat"&PosN>9)|>dplyr::select(-Year)
Ser_Burst_Merge_TY<-Ser_Burst_TY|>filter(MatStageComb=="Mat"&PosN>9)|>dplyr::select(-Year)
Home_Range_All_feed<-combined_hr|>filter(str_detect(Source_file,"fd"))

# Spawning Period_all_years 50%
Home_Range_All<-combined_hr|>anti_join(Home_Range_All_feed)
Home_Range_All_50<-Home_Range_All|>filter(Per_HR==50)
Home_Range_All_50<-Home_Range_All_50|>mutate(Burst_b=as.numeric(Burst_b))
Home_Range_All_50<-Home_Range_All_50|>inner_join(Ser_Burst_Merge)
Home_Range_All_50<-Home_Range_All_50|>separate("Ser_Per_Year_Date_Diel",sep = "_",c("Serial","Period","Year","Date_Corr","Diel"))
Home_Range_All_50_sum<-Home_Range_All_50|>group_by(Serial,Sex,Diel,Year,Length)|>
  summarise(MHR_50=mean(HR_size),DaysN=n(),TotPos=sum(PosN),MedianPos=median(PosN))
Home_Range_All_50_sum<-Home_Range_All_50_sum|>mutate(Diel=as.numeric(Diel))
Home_Range_All_50_sum<-Home_Range_All_50_sum|>mutate(Day_Night=ifelse(Diel==0,"Day","Night"))  
# Spawning Period_all_years 95% 
Home_Range_All_95 <- Home_Range_All |> filter(Per_HR==95)
Home_Range_All_95 <- Home_Range_All_95 |> mutate(Burst_b=as.numeric(Burst_b))
Home_Range_All_95 <- Home_Range_All_95 |> inner_join(Ser_Burst_Merge)
Home_Range_All_95 <- Home_Range_All_95|>separate("Ser_Per_Year_Date_Diel",sep = "_",c("Serial","Period","Year","Date_Corr","Diel"))
Home_Range_All_95_sum<-Home_Range_All_95|>group_by(Serial,Sex,Diel,Year,Length)|>
  summarise(MHR_95=mean(HR_size),DaysN=n(),TotPos=sum(PosN),MedianPos=median(PosN))
Home_Range_All_95_sum<-Home_Range_All_95_sum|>mutate(Diel=as.numeric(Diel))
Home_Range_All_95_sum<-Home_Range_All_95_sum|>mutate(Day_Night=ifelse(Diel==0,"Day","Night"))
HR_50_merge<-Home_Range_All_50_sum|>ungroup|>dplyr::select(Serial,Year,Diel,MHR_50)
Home_Range_All_Bakka<-Home_Range_All_95_sum|>left_join(HR_50_merge,by=c("Serial"="Serial","Year"="Year","Diel"="Diel"))

############################
## Dean Overlap / Jaccard ##
############################

path <- file.path("") # fill in own trajectory
path
setwd(path)

# serialHR files can be found in the Dean_overlap_serial_date_all.zip file
# Site affinity analyses
file_stem <- "serialHR"
filenames <- list.files(pattern = paste0(file_stem, ".*\\.csv$"))

data_list <- lapply(filenames, function(file) {
  df <- read_csv(file)
  df <- df |>
    gather(c(2:as.numeric(ncol(df))),key=Ser2,value=HR_Overlap)|>
    mutate(Ser2=as.numeric(Ser2))|>
    mutate(source_file = file)
  return(df)})  

combined_df <- bind_rows(data_list)
names(Home_Range_All_95)
HR_95_Merge<-Home_Range_All_95|>dplyr::select(Burst_b,HR_size,Serial,Sex,DataYear,Period,Date_Corr,Diel)
combined_df_merge<-combined_df|>inner_join(HR_95_Merge,by=c("...1"="Burst_b"))|>
  inner_join(HR_95_Merge,by=c("Ser2"="Burst_b"))
names(combined_df_merge)
combined_df_merge<-combined_df_merge|>mutate(Overlap_area=HR_Overlap*HR_size.x)
key <- apply(combined_df_merge[, 1:2], 1, 
             function(x) paste(sort(x), collapse = "_"))
combined_df_nodup <- combined_df_merge[!duplicated(key), ]
combined_df_nodup<-combined_df_nodup|>
  mutate(Dean_Overlap=100*(Overlap_area/(HR_size.x+HR_size.y-Overlap_area)))

Same_Fish_Next_Day<-combined_df_nodup|>filter(Serial.x==Serial.y&Diel.x==Diel.y&Date_Corr.x!=Date_Corr.y)
Same_Fish_Next_Day<-Same_Fish_Next_Day|>mutate(Day_Diff=abs(as.numeric(as.Date(Date_Corr.x)-as.numeric(as.Date(Date_Corr.y)))))
Same_Fish_Next_Day<-Same_Fish_Next_Day|>filter(Day_Diff==1)
Same_Fish_Next_Day<-Same_Fish_Next_Day[ !duplicated(apply(Same_Fish_Next_Day, 1, sort), MARGIN = 2), ]##Take out duplicates

Sum_SFND<-Same_Fish_Next_Day|>group_by(Serial.x,Diel.x,Sex.x,DataYear.x)|>
  summarise(Site_affinity=mean(Dean_Overlap),DayO=n()+1)
Sum_SFND<-Sum_SFND|>mutate(Diel=as.numeric(Diel.x),Day_Night=ifelse(Diel==0,"Day","Night"))

means_df <- Sum_SFND |>
  filter(Sex.x != "?") |>
  group_by(Sex.x, Day_Night) |>
  summarise(mean_affinity_weight = weighted.mean(Site_affinity, DayO,na.rm = TRUE),.groups = "drop",
            mean_affinity=mean(Site_affinity,na.rm = TRUE))

Sum_SFND_table<-Same_Fish_Next_Day|>group_by(Serial.x,Diel.x,Sex.x,DataYear.x)|>
  summarise(Site_affinity=mean(Dean_Overlap))|>
  mutate(Diel=ifelse(Diel.x==0,"Day","Night"),Year=DataYear.x,Sex=Sex.x)|>
  group_by(Year,Sex,Diel)|>
  summarise(Site_affinity_mean=mean(Site_affinity),Site_affinity_sd=sd(Site_affinity),Nfish=n())|>
  mutate(across(c(Site_affinity_mean, Site_affinity_sd), ~ round(.x, 2)))
print(Sum_SFND_table)
write.csv(Sum_SFND_table,file="Site_affinity_Dean_all.csv",row.names = FALSE)
tab_df(Sum_SFND_table,file="Site_affinity_Dean_all.doc")

HR_95new<-Home_Range_All_95_sum
HR_95new<-HR_95new|>mutate(Year=as.numeric(Year))
Sum_SFND_Analyses<-Sum_SFND|>mutate(Diel.x=as.numeric(Diel.x))|>
  left_join(HR_95new,by=c("Serial.x"="Serial",
                          "Diel.x"="Diel","DataYear.x"="Year"))

Mod1_affinity<-lmer(Site_affinity~factor(Diel.x)*factor(Sex.x)+I(log(MHR_95))+(1|Serial.x)+(1|DataYear.x),
                    data = Sum_SFND_Analyses,
                    weights = sqrt(DayO),
                    na.action = "na.fail")
dredge(Mod1_affinity)
summary(Mod1_affinity)
Mod2_affinity<-lmer(Site_affinity~factor(Diel.x)+factor(Sex.x)+I(log(MHR_95))+(1|Serial.x)+(1|DataYear.x),
                    data = Sum_SFND_Analyses,
                    weights = sqrt(DayO))
summary(Mod2_affinity)
MuMIn::AICc(Mod1_affinity, Mod2_affinity)
tab_model(Mod1_affinity,file="Site_Affinity_Dean.doc")

# Aggregation intensity
# dateHR files can be found in the Dean_overlap_serial_date_all.zip file
file_stem <- "dateHR"
filenames <- list.files(pattern = paste0(file_stem, ".*\\.csv$"))
data_list <- lapply(filenames, function(file) {
  df <- read_csv(file)
  df <- df |>
    gather(c(2:as.numeric(ncol(df))),key=Ser2,value=HR_Overlap)|>
    mutate(Ser2=as.numeric(Ser2))|>
    mutate(source_file = file)
  return(df)})

combined_of <- bind_rows(data_list)
HR_95_Merge<-Home_Range_All_95|>dplyr::select(Burst_b,HR_size,Serial,Sex,DataYear,Period,Date_Corr,Diel)
combined_of_merge<-combined_of|>inner_join(HR_95_Merge,by=c("...1"="Burst_b"))|>
  inner_join(HR_95_Merge,by=c("Ser2"="Burst_b"))
combined_of_merge<-combined_of_merge|>
  mutate(Overlap_area=HR_Overlap*HR_size.x)
combined_of_merge<-combined_of_merge|>
  mutate(Dean_Overlap=100*(Overlap_area/(HR_size.x+HR_size.y-Overlap_area)))
key <- apply(combined_of_merge[, 1:2], 1, 
             function(x) paste(sort(x), collapse = "_"))

combined_of_nodup <- combined_of_merge[!duplicated(key), ]
Tot_comb_of<-combined_of_nodup
Diff_Fish_Same_Day<-Tot_comb_of|>filter(Serial.x!=Serial.y&Diel.x==Diel.y&Date_Corr.x==Date_Corr.y)
Diff_Fish_Same_Day<-Diff_Fish_Same_Day[ !duplicated(apply(Diff_Fish_Same_Day, 1, sort), MARGIN = 2), ]
Diff_Fish_Same_Day<-Diff_Fish_Same_Day|>mutate(Sex_Comb=paste(Sex.x,Sex.y,sep=""))
unique(Diff_Fish_Same_Day$Sex_Comb)
DFSD1<-Diff_Fish_Same_Day|>dplyr::select(Serial.x,Sex.x,Sex_Comb,Diel.x,DataYear.x,Dean_Overlap,Date_Corr.x)
DFSD2<-Diff_Fish_Same_Day|>dplyr::select(Serial.y,Sex.y,Sex_Comb,Diel.y,DataYear.y,Dean_Overlap,Date_Corr.y)
colnames(DFSD2)<-names(DFSD1)
DFSD<-rbind(DFSD1,DFSD2)
colnames(DFSD)<-c("Serial","Sex","Sex_Comb","Diel","Year","Overlap","Date_Corr")
DFSD_Sex_Comb_date<-DFSD|>group_by(Sex_Comb,Diel,Date_Corr,Serial)|>
  summarise(Pos=n())|>group_by(Sex_Comb,Diel,Date_Corr)|>
  summarise(FishNOverLap=n())

DFSD_sum<-DFSD|>mutate(Sex_Comb=ifelse(Sex_Comb=="MF","FM",Sex_Comb),
                       Day_Night=ifelse(as.numeric(Diel)==0,"Day","Night"))|>
  group_by(Serial,Sex_Comb,Day_Night,Year)|>
  summarise(MeanO=mean(Overlap),Numb=n())

DFSD_sum2<-DFSD|>mutate(Sex_Comb=ifelse(Sex_Comb=="MF","FM",Sex_Comb),
                        Day_Night=ifelse(as.numeric(Diel)==0,"Day","Night"))|>
  group_by(Serial,Sex,Sex_Comb,Day_Night,Year,Date_Corr)|>
  summarise(MeanO=mean(Overlap),Numb=n())|>
  group_by(Serial,Sex,Sex_Comb,Day_Night,Year)|>
  summarise(MeanO_agg=mean(MeanO),DayO=n())

Agg_Intensity_Table<-DFSD_sum2|>group_by(Year,Sex_Comb,Day_Night)|>
  summarise(Agg_Intensity=mean(MeanO_agg),sd=sd(MeanO_agg))|>
  mutate(across(c(Agg_Intensity, sd), ~ round(.x, 2)))

write.csv(Agg_Intensity_Table,file = "Agg_Intensity_Table_1026.csv",row.names = FALSE)
tab_df(Agg_Intensity_Table,file="Agg_Intensity_Table_1026.doc")

OvDF_BK<-DFSD_sum|>group_by(Sex_Comb,Day_Night)|>
  summarise(MMO=100*mean(MeanO),St_Dev=100*sd(MeanO),Numb=n())
write.csv(OvDF_BK,file="ODVF_BK.csv",row.names = FALSE)

Mod_dean_AI<-lmer(I(log(MeanO_agg+0.0001)))~Sex_Comb*Day_Night+(1|Serial2)

Mod_dean_AI <- lmer(log(MeanO_agg+0.000001) ~ Sex_Comb*Day_Night + (1 | Serial) + (1 | Year),
                    data    = DFSD_sum2,
                    na.action = "na.fail",
                    weights = sqrt(DayO))
summary(Mod_dean_AI)
M2<-dredge(Mod_dean_AI)
M2

DFSD_sum2$Sex_Comb <- fct_relevel(DFSD_sum2$Sex_Comb, "MM")

Mod_dean_AI_fin <- lmer(log(MeanO_agg+0.000001) ~ Sex_Comb+Day_Night + (1 | Serial) + (1 | Year),
                        data    = DFSD_sum2,
                        na.action = "na.fail",
                        weights = sqrt(DayO))
summary(Mod_dean_AI_fin)
tab_model(Mod_dean_AI_fin,file="Mod_dean_AI_fin.doc")

###############################
## Female deep dive detector ##
###############################

# SpawnSeis_Positional data
SpawnSeis_data<-read_csv("Bakkasund_filt_19_24_land_removed.csv")
SpawnSeis_data<-SpawnSeis_data|>mutate(Month=data.table::month(DATETIME),Year=data.table::year(DATETIME),Period=ifelse(Month%in%c(2:3),0,1))

Sensor_Type_Info<-SpawnSeis_data|>group_by(SensorUnit_2)|>summarise(Det=n())
tab_df(Sensor_Type_Info,file="Summary_data.doc")

# Create datasets for the spawning period
Spawn_mat_spawn<-SpawnSeis_data|>filter(MatStageComb=="Mat"&Period==0&SensorUnit_2=="P")
Spawn_mat_spawn2<-SpawnSeis_data|>filter(MatStageComb=="Mat"&Period==0&SensorUnit_2=="DEPTH")
Spawn_mat_spawn3<-rbind(Spawn_mat_spawn, Spawn_mat_spawn2)

ggplot(subset(Spawn_mat_spawn3,
              Serial2==1304619 & Year==2019 & DATETIME>"2019-02-27" & DATETIME<"2019-03-15"),
       aes(DATETIME,Depth2))+
  geom_line(color = "red") +
  geom_point(color = "red") +
  scale_y_reverse() +
  scale_x_datetime(date_breaks = "2 day",
                   date_labels = "%d %b")+
  theme_JE +
  theme(axis.text = element_text(size = 13),
        axis.title = element_text(size = 13)) +
  scale_x_datetime(limits = as.POSIXct(c("2019-02-27 00:00:00", "2019-03-14 23:59:59"),
                                       tz = "UTC"),
                   breaks = seq(as.POSIXct("2019-02-27", tz = "UTC"),
                                as.POSIXct("2019-03-14", tz = "UTC"),
                                by = "2 days"),
                   date_labels = "%d %b",
                   expand = c(0, 0)) +
  geom_hline(yintercept = c(25),lty=2) +
  ylab("Depth (m)") +
  xlab("Time")

# Spawning period 2019
Sp_2019_SpawnSeis<-Spawn_mat_spawn3 |> 
  filter(Year==2019)
Sp_2019_SpawnSeis$Month <- month(Sp_2019_SpawnSeis$Date)
Sp_2019_inp <- Sp_2019_SpawnSeis |>
  dplyr::select(Serial2,Sex,DATETIME,Depth2, Month,Day_Night)
Sp_2019_inp$DT <- as.POSIXct(Sp_2019_inp$DATETIME,format="%Y-%m-%d %H:%M:%OS",tz="UTC")

# Calculate daily range
Fish_cat_2019_Range <- Sp_2019_inp |>
  dplyr::select(Serial2,Sex,DATETIME,Depth2) |>
  mutate(Date=as.Date(DATETIME))|>
  group_by(Date,Serial2,Sex) |>
  summarise(Range=max(Depth2)-min(Depth2),
            MaxDepth=max(Depth2))
# Fill in NA's where missing data so that values only are calculated for continuous data, i.e. 3 days with depth data
dplyr_correct_df = expand.grid(Serial2 = sort(unique(Fish_cat_2019_Range$Serial2)),
                               Date   = seq(from = min(Fish_cat_2019_Range$Date), 
                                            to = max(Fish_cat_2019_Range$Date),1)) |>
  left_join(Fish_cat_2019_Range)
Fish_cat_2019_Range<-dplyr_correct_df

# Calculate moving averages
Fish_cat_2019_Range <- Fish_cat_2019_Range |>
  arrange(Serial2,Date)
Fish_cat_2019_Range <- Fish_cat_2019_Range |>
  group_by(Serial2) |>
  mutate(cma=rollmean(Range, k = 3, fill = NA), 
         tma=rollmean(Range, k = 3, fill = NA, align = "right"),
         cmd=rollmean(MaxDepth,k = 3, fill = NA))

# Compare daily range to the moving average
Fish_cat_2019_Range$RI <- Fish_cat_2019_Range$Range/Fish_cat_2019_Range$cma
Fish_cat_2019_Range$MDI <- Fish_cat_2019_Range$MaxDepth/Fish_cat_2019_Range$cmd

# Range_file
Range_2019 <- Fish_cat_2019_Range |>
  filter(MDI>1.286) |>
  group_by(Serial2,Date,Sex) |>
  arrange(Serial2,Date) |>
  transform(Lag_Date=lag(Date),Lag_Ser=lag(Serial2)) |>
  mutate(Date_Diff=ifelse(Serial2==Lag_Ser,data.table::yday(Date)-data.table::yday(Lag_Date),NA),
         Count=ifelse(is.na(Date_Diff)==TRUE|Date_Diff>6,1.01,1))
Range_2019_1 <- Range_2019 |>
  dplyr::select(Serial2,Count) |>
  group_by(grp = cumsum(Count == 1.01)) |> 
  mutate(cumsum = cumsum(Count)) |>
  group_by(Serial2) |>
  summarise(Longest_sequence=round(max(cumsum)),
            Periodic_Descents=n())
Fish_dat_19 <- Fish_cat_2019_Range |>
  filter(MDI>1.286) |>
  group_by(Serial2) |>
  summarise(Fist_Desc=min(Date),Last_Desc=max(Date))
Spawn_pd_19 <- Spawn_mat_spawn3 |>
  filter(Year==2019) |> 
  group_by(Serial2,Sex,Date,Location,Sampling.Day,Length,Weight) |>
  summarise(Det=n()) |>
  group_by(Serial2,Sex,Location,Sampling.Day,Length,Weight) |>
  summarise(Det=sum(Det),DaysN=n(),MinDate=min(Date),MaxDate=max(Date)) |>
  left_join(Range_2019_1)|>
  left_join(Fish_dat_19) |>
  mutate(Year=2019,Daily_Det=Det/DaysN)
Spawn_pd_19<-Spawn_mat_spawn3 |>
  filter(Year==2019) |>
  group_by(Serial2) |>
  summarise(MDepth=mean(Depth2)) |>
  left_join(Spawn_pd_19)

# Spawning period 2020
Sp_2020_SpawnSeis<-Spawn_mat_spawn3 |> 
  filter(Year==2020)
Sp_2020_SpawnSeis$Month <- month(Sp_2020_SpawnSeis$Date)
Sp_2020_inp <- Sp_2020_SpawnSeis |>
  dplyr::select(Serial2,Sex,DATETIME,Depth2, Month,Day_Night)
Sp_2020_inp$DT <- as.POSIXct(Sp_2020_inp$DATETIME,format="%Y-%m-%d %H:%M:%OS",tz="UTC")

# Calculate daily range
Fish_cat_2020_Range <- Sp_2020_inp |>
  dplyr::select(Serial2,Sex,DATETIME,Depth2) |>
  mutate(Date=as.Date(DATETIME))|>
  group_by(Date,Serial2,Sex) |>
  summarise(Range=max(Depth2)-min(Depth2),
            MaxDepth=max(Depth2))
# Fill in NA's where missing data so that values only are calculated for continuous data, i.e. 3 days with depth data
dplyr_correct_df = expand.grid(Serial2 = sort(unique(Fish_cat_2020_Range$Serial2)),
                               Date   = seq(from = min(Fish_cat_2020_Range$Date), 
                                            to = max(Fish_cat_2020_Range$Date),1)) |>
  left_join(Fish_cat_2020_Range)
Fish_cat_2020_Range<-dplyr_correct_df

# Calculate moving averages
Fish_cat_2020_Range <- Fish_cat_2020_Range |>
  arrange(Serial2,Date)
Fish_cat_2020_Range <- Fish_cat_2020_Range |>
  group_by(Serial2) |>
  mutate(cma=rollmean(Range, k = 3, fill = NA), 
         tma=rollmean(Range, k = 3, fill = NA, align = "right"),
         cmd=rollmean(MaxDepth,k = 3, fill = NA))

# Compare daily range to the moving average
Fish_cat_2020_Range$RI <- Fish_cat_2020_Range$Range/Fish_cat_2020_Range$cma
Fish_cat_2020_Range$MDI <- Fish_cat_2020_Range$MaxDepth/Fish_cat_2020_Range$cmd

# Range_file
Range_2020 <- Fish_cat_2020_Range |>
  filter(MDI>1.286) |>
  group_by(Serial2,Date,Sex) |>
  arrange(Serial2,Date) |>
  transform(Lag_Date=lag(Date),Lag_Ser=lag(Serial2)) |>
  mutate(Date_Diff=ifelse(Serial2==Lag_Ser,data.table::yday(Date)-data.table::yday(Lag_Date),NA),
         Count=ifelse(is.na(Date_Diff)==TRUE|Date_Diff>6,1.01,1))
Range_2020_1 <- Range_2020 |>
  dplyr::select(Serial2,Count) |>
  group_by(grp = cumsum(Count == 1.01)) |> 
  mutate(cumsum = cumsum(Count)) |>
  group_by(Serial2) |>
  summarise(Longest_sequence=round(max(cumsum)),
            Periodic_Descents=n())
Fish_dat_20 <- Fish_cat_2020_Range |>
  filter(MDI>1.286) |>
  group_by(Serial2) |>
  summarise(Fist_Desc=min(Date),Last_Desc=max(Date))
Spawn_pd_20 <- Spawn_mat_spawn3 |>
  filter(Year==2020) |> 
  group_by(Serial2,Sex,Date,Location,Sampling.Day,Length,Weight) |>
  summarise(Det=n()) |>
  group_by(Serial2,Sex,Location,Sampling.Day,Length,Weight) |>
  summarise(Det=sum(Det),DaysN=n(),MinDate=min(Date),MaxDate=max(Date)) |>
  left_join(Range_2020_1)|>
  left_join(Fish_dat_20) |>
  mutate(Year=2020,Daily_Det=Det/DaysN)
Spawn_pd_20<-Spawn_mat_spawn3 |>
  filter(Year==2020) |>
  group_by(Serial2) |>
  summarise(MDepth=mean(Depth2)) |>
  left_join(Spawn_pd_20)

# Spawning period 2021
Sp_2021_SpawnSeis<-Spawn_mat_spawn3 |> 
  filter(Year==2021)
Sp_2021_SpawnSeis$Month <- month(Sp_2021_SpawnSeis$Date)
Sp_2021_inp <- Sp_2021_SpawnSeis |>
  dplyr::select(Serial2,Sex,DATETIME,Depth2, Month,Day_Night)
Sp_2021_inp$DT <- as.POSIXct(Sp_2021_inp$DATETIME,format="%Y-%m-%d %H:%M:%OS",tz="UTC")

# Calculate daily range
Fish_cat_2021_Range <- Sp_2021_inp |>
  dplyr::select(Serial2,Sex,DATETIME,Depth2) |>
  mutate(Date=as.Date(DATETIME))|>
  group_by(Date,Serial2,Sex) |>
  summarise(Range=max(Depth2)-min(Depth2),
            MaxDepth=max(Depth2))
# Fill in NA's where missing data so that values only are calculated for continuous data, i.e. 3 days with depth data
dplyr_correct_df = expand.grid(Serial2 = sort(unique(Fish_cat_2021_Range$Serial2)),
                               Date   = seq(from = min(Fish_cat_2021_Range$Date), 
                                            to = max(Fish_cat_2021_Range$Date),1)) |>
  left_join(Fish_cat_2021_Range)
Fish_cat_2021_Range<-dplyr_correct_df

# Calculate moving averages
Fish_cat_2021_Range <- Fish_cat_2021_Range |>
  arrange(Serial2,Date)
Fish_cat_2021_Range <- Fish_cat_2021_Range |>
  group_by(Serial2) |>
  mutate(cma=rollmean(Range, k = 3, fill = NA), 
         tma=rollmean(Range, k = 3, fill = NA, align = "right"),
         cmd=rollmean(MaxDepth,k = 3, fill = NA))

# Compare daily range to the moving average
Fish_cat_2021_Range$RI <- Fish_cat_2021_Range$Range/Fish_cat_2021_Range$cma
Fish_cat_2021_Range$MDI <- Fish_cat_2021_Range$MaxDepth/Fish_cat_2021_Range$cmd

# Range_file
Range_2021 <- Fish_cat_2021_Range |>
  filter(MDI>1.286) |>
  group_by(Serial2,Date,Sex) |>
  arrange(Serial2,Date) |>
  transform(Lag_Date=lag(Date),Lag_Ser=lag(Serial2)) |>
  mutate(Date_Diff=ifelse(Serial2==Lag_Ser,data.table::yday(Date)-data.table::yday(Lag_Date),NA),
         Count=ifelse(is.na(Date_Diff)==TRUE|Date_Diff>6,1.01,1))
Range_2021_1 <- Range_2021 |>
  dplyr::select(Serial2,Count) |>
  group_by(grp = cumsum(Count == 1.01)) |> 
  mutate(cumsum = cumsum(Count)) |>
  group_by(Serial2) |>
  summarise(Longest_sequence=round(max(cumsum)),
            Periodic_Descents=n())
Fish_dat_21 <- Fish_cat_2021_Range |>
  filter(MDI>1.286) |>
  group_by(Serial2) |>
  summarise(Fist_Desc=min(Date),Last_Desc=max(Date))
Spawn_pd_21 <- Spawn_mat_spawn3 |>
  filter(Year==2021) |> 
  group_by(Serial2,Sex,Date,Location,Sampling.Day,Length,Weight) |>
  summarise(Det=n()) |>
  group_by(Serial2,Sex,Location,Sampling.Day,Length,Weight) |>
  summarise(Det=sum(Det),DaysN=n(),MinDate=min(Date),MaxDate=max(Date)) |>
  left_join(Range_2021_1)|>
  left_join(Fish_dat_21) |>
  mutate(Year=2021,Daily_Det=Det/DaysN)
Spawn_pd_21<-Spawn_mat_spawn3 |>
  filter(Year==2021) |>
  group_by(Serial2) |>
  summarise(MDepth=mean(Depth2)) |>
  left_join(Spawn_pd_21)

# Spawning period 2022
Sp_2022_SpawnSeis<-Spawn_mat_spawn3 |> 
  filter(Year==2022)
Sp_2022_SpawnSeis$Month <- month(Sp_2022_SpawnSeis$Date)
Sp_2022_inp <- Sp_2022_SpawnSeis |>
  dplyr::select(Serial2,Sex,DATETIME,Depth2, Month,Day_Night)
Sp_2022_inp$DT <- as.POSIXct(Sp_2022_inp$DATETIME,format="%Y-%m-%d %H:%M:%OS",tz="UTC")

# Calculate daily range
Fish_cat_2022_Range <- Sp_2022_inp |>
  dplyr::select(Serial2,Sex,DATETIME,Depth2) |>
  mutate(Date=as.Date(DATETIME))|>
  group_by(Date,Serial2,Sex) |>
  summarise(Range=max(Depth2)-min(Depth2),
            MaxDepth=max(Depth2))

# Fill in NA's where missing data so that values only are calculated for continuous data, i.e. 3 days with depth data
dplyr_correct_df = expand.grid(Serial2 = sort(unique(Fish_cat_2022_Range$Serial2)),
                               Date   = seq(from = min(Fish_cat_2022_Range$Date), 
                                            to = max(Fish_cat_2022_Range$Date),1)) |>
  left_join(Fish_cat_2022_Range)
Fish_cat_2022_Range<-dplyr_correct_df

# Calculate moving averages
Fish_cat_2022_Range <- Fish_cat_2022_Range |>
  arrange(Serial2,Date)
Fish_cat_2022_Range <- Fish_cat_2022_Range |>
  group_by(Serial2) |>
  mutate(cma=rollmean(Range, k = 3, fill = NA), 
         tma=rollmean(Range, k = 3, fill = NA, align = "right"),
         cmd=rollmean(MaxDepth,k = 3, fill = NA))

# Compare daily range to the moving average
Fish_cat_2022_Range$RI <- Fish_cat_2022_Range$Range/Fish_cat_2022_Range$cma
Fish_cat_2022_Range$MDI <- Fish_cat_2022_Range$MaxDepth/Fish_cat_2022_Range$cmd

# Range_file
Range_2022 <- Fish_cat_2022_Range |>
  filter(MDI>1.286) |>
  group_by(Serial2,Date,Sex) |>
  arrange(Serial2,Date) |>
  transform(Lag_Date=lag(Date),Lag_Ser=lag(Serial2)) |>
  mutate(Date_Diff=ifelse(Serial2==Lag_Ser,data.table::yday(Date)-data.table::yday(Lag_Date),NA),
         Count=ifelse(is.na(Date_Diff)==TRUE|Date_Diff>6,1.01,1))
Range_2022_1 <- Range_2022 |>
  dplyr::select(Serial2,Count) |>
  group_by(grp = cumsum(Count == 1.01)) |> 
  mutate(cumsum = cumsum(Count)) |>
  group_by(Serial2) |>
  summarise(Longest_sequence=round(max(cumsum)),
            Periodic_Descents=n())
Fish_dat_22 <- Fish_cat_2022_Range |>
  filter(MDI>1.286) |>
  group_by(Serial2) |>
  summarise(Fist_Desc=min(Date),Last_Desc=max(Date))
Spawn_pd_22 <- Spawn_mat_spawn3 |>
  filter(Year==2022) |> 
  group_by(Serial2,Sex,Date,Location,Sampling.Day,Length,Weight) |>
  summarise(Det=n()) |>
  group_by(Serial2,Sex,Location,Sampling.Day,Length,Weight) |>
  summarise(Det=sum(Det),DaysN=n(),MinDate=min(Date),MaxDate=max(Date)) |>
  left_join(Range_2022_1)|>
  left_join(Fish_dat_22) |>
  mutate(Year=2022,Daily_Det=Det/DaysN)
Spawn_pd_22<-Spawn_mat_spawn3 |>
  filter(Year==2022) |>
  group_by(Serial2) |>
  summarise(MDepth=mean(Depth2)) |>
  left_join(Spawn_pd_22)

# Spawning period 2023
Sp_2023_SpawnSeis<-Spawn_mat_spawn3 |> 
  filter(Year==2023)
Sp_2023_SpawnSeis$Month <- month(Sp_2023_SpawnSeis$Date)
Sp_2023_inp <- Sp_2023_SpawnSeis |>
  dplyr::select(Serial2,Sex,DATETIME,Depth2, Month,Day_Night)
Sp_2023_inp$DT <- as.POSIXct(Sp_2023_inp$DATETIME,format="%Y-%m-%d %H:%M:%OS",tz="UTC")

# Calculate daily range
Fish_cat_2023_Range <- Sp_2023_inp |>
  dplyr::select(Serial2,Sex,DATETIME,Depth2) |>
  mutate(Date=as.Date(DATETIME))|>
  group_by(Date,Serial2,Sex) |>
  summarise(Range=max(Depth2)-min(Depth2),
            MaxDepth=max(Depth2))
# Fill in NA's where missing data so that values only are calculated for continuous data, i.e. 3 days with depth data
dplyr_correct_df = expand.grid(Serial2 = sort(unique(Fish_cat_2023_Range$Serial2)),
                               Date   = seq(from = min(Fish_cat_2023_Range$Date), 
                                            to = max(Fish_cat_2023_Range$Date),1)) |>
  left_join(Fish_cat_2023_Range)
Fish_cat_2023_Range<-dplyr_correct_df

# Calculate moving averages
Fish_cat_2023_Range <- Fish_cat_2023_Range |>
  arrange(Serial2,Date)
Fish_cat_2023_Range <- Fish_cat_2023_Range |>
  group_by(Serial2) |>
  mutate(cma=rollmean(Range, k = 3, fill = NA), 
         tma=rollmean(Range, k = 3, fill = NA, align = "right"),
         cmd=rollmean(MaxDepth,k = 3, fill = NA))

# Compare daily range to the moving average
Fish_cat_2023_Range$RI <- Fish_cat_2023_Range$Range/Fish_cat_2023_Range$cma
Fish_cat_2023_Range$MDI <- Fish_cat_2023_Range$MaxDepth/Fish_cat_2023_Range$cmd

# Range_file
Range_2023 <- Fish_cat_2023_Range |>
  filter(MDI>1.286) |>
  group_by(Serial2,Date,Sex) |>
  arrange(Serial2,Date) |>
  transform(Lag_Date=lag(Date),Lag_Ser=lag(Serial2)) |>
  mutate(Date_Diff=ifelse(Serial2==Lag_Ser,data.table::yday(Date)-data.table::yday(Lag_Date),NA),
         Count=ifelse(is.na(Date_Diff)==TRUE|Date_Diff>6,1.01,1))
Range_2023_1 <- Range_2023 |>
  dplyr::select(Serial2,Count) |>
  group_by(grp = cumsum(Count == 1.01)) |> 
  mutate(cumsum = cumsum(Count)) |>
  group_by(Serial2) |>
  summarise(Longest_sequence=round(max(cumsum)),
            Periodic_Descents=n())
Fish_dat_23 <- Fish_cat_2023_Range |>
  filter(MDI>1.286) |>
  group_by(Serial2) |>
  summarise(Fist_Desc=min(Date),Last_Desc=max(Date))
Spawn_pd_23 <- Spawn_mat_spawn3 |>
  filter(Year==2023) |> 
  group_by(Serial2,Sex,Date,Location,Sampling.Day,Length,Weight) |>
  summarise(Det=n()) |>
  group_by(Serial2,Sex,Location,Sampling.Day,Length,Weight) |>
  summarise(Det=sum(Det),DaysN=n(),MinDate=min(Date),MaxDate=max(Date)) |>
  left_join(Range_2023_1)|>
  left_join(Fish_dat_23) |>
  mutate(Year=2023,Daily_Det=Det/DaysN)
Spawn_pd_23<-Spawn_mat_spawn3 |>
  filter(Year==2023) |>
  group_by(Serial2) |>
  summarise(MDepth=mean(Depth2)) |>
  left_join(Spawn_pd_23)

# Spawning period 2024
Sp_2024_SpawnSeis<-Spawn_mat_spawn3 |> 
  filter(Year==2024)
Sp_2024_SpawnSeis$Month <- month(Sp_2024_SpawnSeis$Date)
Sp_2024_inp <- Sp_2024_SpawnSeis |>
  dplyr::select(Serial2,Sex,DATETIME,Depth2, Month,Day_Night)
Sp_2024_inp$DT <- as.POSIXct(Sp_2024_inp$DATETIME,format="%Y-%m-%d %H:%M:%OS",tz="UTC")

# Calculate daily range
Fish_cat_2024_Range <- Sp_2024_inp |>
  dplyr::select(Serial2,Sex,DATETIME,Depth2) |>
  mutate(Date=as.Date(DATETIME))|>
  group_by(Date,Serial2,Sex) |>
  summarise(Range=max(Depth2)-min(Depth2),
            MaxDepth=max(Depth2))
# Fill in NA's where missing data so that values only are calculated for continuous data, i.e. 3 days with depth data
dplyr_correct_df = expand.grid(Serial2 = sort(unique(Fish_cat_2024_Range$Serial2)),
                               Date   = seq(from = min(Fish_cat_2024_Range$Date), 
                                            to = max(Fish_cat_2024_Range$Date),1)) |>
  left_join(Fish_cat_2024_Range)
Fish_cat_2024_Range<-dplyr_correct_df

# Calculate moving averages
Fish_cat_2024_Range <- Fish_cat_2024_Range |>
  arrange(Serial2,Date)
Fish_cat_2024_Range <- Fish_cat_2024_Range |>
  group_by(Serial2) |>
  mutate(cma=rollmean(Range, k = 3, fill = NA), 
         tma=rollmean(Range, k = 3, fill = NA, align = "right"),
         cmd=rollmean(MaxDepth,k = 3, fill = NA))

# Compare daily range to the moving average
Fish_cat_2024_Range$RI <- Fish_cat_2024_Range$Range/Fish_cat_2024_Range$cma
Fish_cat_2024_Range$MDI <- Fish_cat_2024_Range$MaxDepth/Fish_cat_2024_Range$cmd

# Range_file
Range_2024 <- Fish_cat_2024_Range |>
  filter(MDI>1.286) |>
  group_by(Serial2,Date,Sex) |>
  arrange(Serial2,Date) |>
  transform(Lag_Date=lag(Date),Lag_Ser=lag(Serial2)) |>
  mutate(Date_Diff=ifelse(Serial2==Lag_Ser,data.table::yday(Date)-data.table::yday(Lag_Date),NA),
         Count=ifelse(is.na(Date_Diff)==TRUE|Date_Diff>6,1.01,1))
Range_2024_1 <- Range_2024 |>
  dplyr::select(Serial2,Count) |>
  group_by(grp = cumsum(Count == 1.01)) |> 
  mutate(cumsum = cumsum(Count)) |>
  group_by(Serial2) |>
  summarise(Longest_sequence=round(max(cumsum)),
            Periodic_Descents=n())
Fish_dat_24 <- Fish_cat_2024_Range |>
  filter(MDI>1.286) |>
  group_by(Serial2) |>
  summarise(Fist_Desc=min(Date),Last_Desc=max(Date))
Spawn_pd_24 <- Spawn_mat_spawn3 |>
  filter(Year==2024) |> 
  group_by(Serial2,Sex,Date,Location,Sampling.Day,Length,Weight) |>
  summarise(Det=n()) |>
  group_by(Serial2,Sex,Location,Sampling.Day,Length,Weight) |>
  summarise(Det=sum(Det),DaysN=n(),MinDate=min(Date),MaxDate=max(Date)) |>
  left_join(Range_2024_1)|>
  left_join(Fish_dat_24) |>
  mutate(Year=2024,Daily_Det=Det/DaysN)
Spawn_pd_24<-Spawn_mat_spawn3 |>
  filter(Year==2024) |>
  group_by(Serial2) |>
  summarise(MDepth=mean(Depth2)) |>
  left_join(Spawn_pd_24)

# Combine
PD_Pos_All <- rbind(Range_2019,Range_2020,Range_2021,Range_2022,Range_2023,Range_2024)
Spawn_merge_PD <- Spawn_mat_spawn3 |>
  dplyr::select(Serial2,Date,DATETIME,X,Y,LAT,LON,Depth2,Day_Night)
PD_Pos_Allb <- PD_Pos_All |> 
  left_join(Spawn_merge_PD,by=c("Serial2"="Serial2","Date"="Date","MaxDepth"="Depth2"))
PD_Pos_Allc <- PD_Pos_Allb |>
  group_by(Serial2,Date,Sex,MaxDepth) |>
  summarise(DATETIMEfirst=min(DATETIME))
Spawn_merge_PD2 <- Spawn_merge_PD |>
  dplyr::select(Serial2,DATETIME,Day_Night,X,Y,LAT,LON)
PD_Pos_Allc <- PD_Pos_Allc |>
  left_join(Spawn_merge_PD2,by=c("Serial2"="Serial2","DATETIMEfirst"="DATETIME"))
write.csv(PD_Pos_Allc,file="PD_Pos_All.csv",row.names = FALSE)

PD_Pos_All_Fem <- PD_Pos_Allc |> filter(Sex=="F")#176
PD_Pos_All_Fem_25 <- PD_Pos_Allc |> filter(Sex=="F"&MaxDepth>25)#167

DL_F_2019_Day   <- PD_Pos_All_Fem_25 |> filter(format(Date, "%Y") == "2019", Day_Night == 0)
DL_F_2019_Night <- PD_Pos_All_Fem_25 |> filter(format(Date, "%Y") == "2019", Day_Night == 1)
DL_F_2020_Day   <- PD_Pos_All_Fem_25 |> filter(format(Date, "%Y") == "2020", Day_Night == 0)
DL_F_2020_Night <- PD_Pos_All_Fem_25 |> filter(format(Date, "%Y") == "2020", Day_Night == 1)
DL_F_2021_Day   <- PD_Pos_All_Fem_25 |> filter(format(Date, "%Y") == "2021", Day_Night == 0)
DL_F_2021_Night <- PD_Pos_All_Fem_25 |> filter(format(Date, "%Y") == "2021", Day_Night == 1)
DL_F_2022_Day   <- PD_Pos_All_Fem_25 |> filter(format(Date, "%Y") == "2022", Day_Night == 0)
DL_F_2022_Night <- PD_Pos_All_Fem_25 |> filter(format(Date, "%Y") == "2022", Day_Night == 1)
DL_F_2023_Day   <- PD_Pos_All_Fem_25 |> filter(format(Date, "%Y") == "2023", Day_Night == 0)
DL_F_2023_Night <- PD_Pos_All_Fem_25 |> filter(format(Date, "%Y") == "2023", Day_Night == 1)
DL_F_2024_Day   <- PD_Pos_All_Fem_25 |> filter(format(Date, "%Y") == "2024", Day_Night == 0)
DL_F_2024_Night <- PD_Pos_All_Fem_25 |> filter(format(Date, "%Y") == "2024", Day_Night == 1)

###################################
## All the maps for the Appendix ##
###################################

################
## 2019 Night ##
################

# UTM coordinates
Filt_sf <- st_as_sf(Filt_BK_spawn_19M_12h_Night_M, coords = c("LON", "LAT"), crs = 4326) |>
  st_transform(32631)
Filt_BK_coords <- Filt_BK_spawn_19M_12h_Night_M |>
  mutate(X_utm = st_coordinates(Filt_sf)[,1], Y_utm = st_coordinates(Filt_sf)[,2])

# Grid
x  <- seq(min(Filt_BK_coords$X_utm) - 2000, max(Filt_BK_coords$X_utm) + 2000, by = 20)
y  <- seq(min(Filt_BK_coords$Y_utm) - 3000, max(Filt_BK_coords$Y_utm) + 3000, by = 20)
xy <- expand.grid(x = x, y = y)
coordinates(xy) <- ~x + y
gridded(xy)     <- TRUE
proj4string(xy) <- CRS(SRS_string = "EPSG:32631")

# Plot frame (WGS84 -> UTM 32631)
frame_bbox <- st_as_sfc(st_bbox(c(xmin = 5.055, 
                                  xmax = 5.110,
                                  ymin = 60.115, 
                                  ymax = 60.130), 
                                crs = 4326)) |>
  st_transform(32631) |>
  st_bbox()

# transform X Y to UTM
utm_coords <- st_coordinates(Filt_sf)
x_offset   <- mean(utm_coords[,1] - Filt_BK_spawn_19M_12h_Night_M$X)
y_offset   <- mean(utm_coords[,2] - Filt_BK_spawn_19M_12h_Night_M$Y)

# # Burst to serial
# burst_to_serial <- Filt_BK_spawn_19M_12h_Night_M |>
#   dplyr::select(Burst_b, Serial, DATETIME, Day_Night) |>
#   distinct() |>
#   mutate(Burst_b = as.character(Burst_b))
# 
# # Get UD50 polygons, shift to UTM and tag per Serial
# burst_list <- lapply(names(tnm_spawn_19M_12h_dd_Night_9), function(nm) {
#   poly <- tryCatch(getverticeshr(tnm_spawn_19M_12h_dd_Night_9[[nm]], percent = 50),
#                    error = function(e) NULL)
#   if (is.null(poly)) return(NULL)
#   
#   sf_poly <- st_as_sf(poly) |>
#     st_set_crs(NA) |>
#     mutate(geometry = geometry + c(x_offset, y_offset)) |>
#     st_set_crs(32631)
#   
#   serial_val     <- burst_to_serial$Serial[burst_to_serial$Burst_b == nm]
#   sf_poly$Serial <- if (length(serial_val) > 0) as.character(serial_val[1]) else NA
#   datetime_val     <- burst_to_serial$DATETIME[burst_to_serial$Burst_b == nm]
#   sf_poly$DATETIME <- if (length(datetime_val) > 0) datetime_val[1] else NA
#   
#   daynight_val      <- burst_to_serial$Day_Night[burst_to_serial$Burst_b == nm]
#   sf_poly$Day_Night <- if (length(daynight_val) > 0) daynight_val[1] else NA
#   sf_poly
# })
# 
# burst_list <- burst_list[!sapply(burst_list, is.null)]
# BBMM_2019_M_Night_all_9 <- do.call(rbind, burst_list)
# 
# # Merge polygons per Serial
# BBMM_2019_M_Night_merged <- BBMM_2019_M_Night_all_9 |>
#   mutate(Serial = factor(Serial)) |>
#   dplyr::group_by(Serial) |>
#   dplyr::summarize(geometry = sf::st_union(geometry)) |>
#   sf::st_as_sf(crs = 32631)

# save(BBMM_2019_M_Night_merged, file="BBMM_2019_M_Night_merged.Rdata")
# save(BBMM_2019_M_Night_all   , file="BBMM_2019_M_Night_all.Rdata")
# save(BBMM_2019_M_Night_all_9, file="BBMM_2019_M_Night_all_9.Rdata")
load("BBMM_2019_M_Night_all_9.Rdata")
load("BBMM_2019_M_Night_merged.Rdata")

# Nice colours
serial_pal <- colorRampPalette(c("#E41A1A", "#377EB6", "#4DAF5A", "#984EB3", "#FF7F03",
                                 "#A65638", "#F781BB", "#999989", "#66C2A6", "#FC8D60",
                                 "#8DA0BB", "#E78CC3", "#A6D754", "#FFD93F", "#E5C496",
                                 "#1B9E76", "#D95F03", "#7570B0", "#E72A98", "#66A62E",
                                 "#E6AB02", "#A6761D"))

BBMM_2019_M_Night_all_9 <- BBMM_2019_M_Night_all_9 |>
  mutate(Serial = factor(Serial))

BBMM_2019_M_Night_by_serial <- BBMM_2019_M_Night_all_9 |> 
  st_make_valid() |> 
  dplyr::group_by(Serial) |> 
  dplyr::summarize(geometry = sf::st_union(geometry), .groups = "drop") |> 
  sf::st_as_sf(crs=32631)

# Plot
Final_Plot_2019_Night_DD <- ggplot() +
  geom_sf(data = land_crop, fill = "white", color = "black", linewidth = 0.2) +
  geom_sf(data = BBMM_2019_M_Night_by_serial, aes(fill = Serial),
          alpha = 0.5, color = "black", linewidth = 0.2) +
  scale_fill_manual(values = serial_pal(22), name = "Serial") +
  annotate("text",
           x      = 614480,    
           y      = 6667650,  
           label  = "2019 Night",
           hjust  = 0.5,             
           vjust  = 0.1,
           size   = 5,
           fontface = "bold") +
  annotate("text",
           x        = 615520,
           y        = 6667450,
           label    = "Stora Karlsøy", hjust    = 0.5, vjust    = 0.5,
           size     = 5, fontface = "italic") +
  theme_bw() +
  theme(panel.background = element_rect(fill = "lightblue"),
        panel.grid       = element_blank(),
        legend.position = "none",
        legend.key.size  = unit(0.4, "cm"),
        legend.text      = element_text(size = 8),
        legend.title     = element_text(size = 9),
        axis.text        = element_blank(),
        axis.ticks       = element_blank())

# Map 2019 Night DD
Final_Plot_2019_Night_DD <- Final_Plot_2019_Night_DD +
  coord_sf(xlim = c(frame_bbox["xmin"], frame_bbox["xmax"]),
           ylim = c(frame_bbox["ymin"], frame_bbox["ymax"]),
           crs = st_crs(32631), expand = FALSE)
print(Final_Plot_2019_Night_DD)

# All merged
merged_geom <- sf::st_union(BBMM_2019_M_Night_all_9) |> st_make_valid()
land_union <- st_union(land_crop) |> st_make_valid()
merged_geom_noland <- st_difference(merged_geom, land_union)
BBMM_2019_M_Night_merged <- sf::st_sf(geometry = merged_geom_noland, crs = 32631)

# Plot
Final_Plot_2019_Night_DD_merged <- ggplot() +
  geom_sf(data = land_crop, fill = "white", color = "black", linewidth = 0.2) +
  geom_sf(data = BBMM_2019_M_Night_merged, fill = "grey40",
          alpha = 0.5, color = "black", linewidth = 0.2) +
  annotate("text",
           x      = 614780,
           y      = 6667650,
           label  = "2019 Night Deep Dive",
           hjust  = 0.5,
           vjust  = 0.1,
           size   = 5,
           fontface = "bold") +
  annotate("text",
           x        = 615520,
           y        = 6667450,
           label    = "Stora Karlsøy",
           hjust    = 0.5,
           vjust    = 0.5,
           size     = 5,
           fontface = "italic") +
  theme_bw() +
  theme(panel.background = element_rect(fill = "lightblue"),
        panel.grid       = element_blank(),
        legend.position  = "none",
        axis.text        = element_blank(),
        axis.ticks       = element_blank())

# Add the Deep Dive locations Night (yellow points)
if (exists("DL_F_2019_Night") && !is.null(DL_F_2019_Night)) {
  pts_sf <- st_as_sf(DL_F_2019_Night, coords = c("LON", "LAT"), crs = 4326) |>
    st_transform(32631)
  inside <- lengths(st_intersects(pts_sf, BBMM_2019_M_Night_merged)) > 0
  pts_inside  <- pts_sf[inside, ]
  pts_outside <- pts_sf[!inside, ]
  Final_Plot_2019_Night_DD_merged <- Final_Plot_2019_Night_DD_merged +
    geom_sf(data = pts_outside, color = "black", fill = "yellow",
            shape = 21, size = 3, stroke = 1) +
    geom_sf(data = pts_inside, color = "black", fill = "red",
            shape = 21, size = 3, stroke = 1)}

# Map 2019 Night DD merged
Final_Plot_2019_Night_DD_merged <- Final_Plot_2019_Night_DD_merged +
  coord_sf(xlim = c(frame_bbox["xmin"], frame_bbox["xmax"]),
           ylim = c(frame_bbox["ymin"], frame_bbox["ymax"]),
           crs = st_crs(32631), expand = FALSE)

print(Final_Plot_2019_Night_DD_merged)

###############################################################################
# 2019 Day
###############################################################################

# UTM coordinates
Filt_sf <- st_as_sf(Filt_BK_spawn_19M_12h_Day_M, coords = c("LON", "LAT"), crs = 4326) |>
  st_transform(32631)
Filt_BK_coords <- Filt_BK_spawn_19M_12h_Day_M |>
  mutate(X_utm = st_coordinates(Filt_sf)[,1], Y_utm = st_coordinates(Filt_sf)[,2])

# Grid
x  <- seq(min(Filt_BK_coords$X_utm) - 2000, max(Filt_BK_coords$X_utm) + 2000, by = 20)
y  <- seq(min(Filt_BK_coords$Y_utm) - 3000, max(Filt_BK_coords$Y_utm) + 3000, by = 20)
xy <- expand.grid(x = x, y = y)
coordinates(xy) <- ~x + y
gridded(xy)     <- TRUE
proj4string(xy) <- CRS(SRS_string = "EPSG:32631")

# Plot frame (WGS84 -> UTM 32631)
frame_bbox <- st_as_sfc(st_bbox(c(xmin = 5.055, 
                                  xmax = 5.110,
                                  ymin = 60.115, 
                                  ymax = 60.130), 
                                crs = 4326)) |>
  st_transform(32631) |>
  st_bbox()

# Offset: local X/Y -> real UTM
utm_coords <- st_coordinates(Filt_sf)
x_offset   <- mean(utm_coords[,1] - Filt_BK_spawn_19M_12h_Day_M$X)
y_offset   <- mean(utm_coords[,2] - Filt_BK_spawn_19M_12h_Day_M$Y)

# # Burst -> Serial lookup
# burst_to_serial <- Filt_BK_spawn_19M_12h_Day_M |>
#   dplyr::select(Burst_b, Serial, DATETIME, Day_Night) |>
#   distinct() |>
#   mutate(Burst_b = as.character(Burst_b))
# 
# # Extract UD50 polygons, shift to real UTM, tag with Serial
# burst_list <- lapply(names(tnm_spawn_19M_12h_dd_Day_9), function(nm) {
#   poly <- tryCatch(getverticeshr(tnm_spawn_19M_12h_dd_Day_9[[nm]], percent = 50),
#                    error = function(e) NULL)
#   if (is.null(poly)) return(NULL)
#   sf_poly <- st_as_sf(poly) |>
#     st_set_crs(NA) |>
#     mutate(geometry = geometry + c(x_offset, y_offset)) |>
#     st_set_crs(32631)
#   serial_val     <- burst_to_serial$Serial[burst_to_serial$Burst_b == nm]
#   sf_poly$Serial <- if (length(serial_val) > 0) as.character(serial_val[1]) else NA
#   datetime_val     <- burst_to_serial$DATETIME[burst_to_serial$Burst_b == nm]
#   sf_poly$DATETIME <- if (length(datetime_val) > 0) datetime_val[1] else NA
#   daynight_val      <- burst_to_serial$Day_Night[burst_to_serial$Burst_b == nm]
#   sf_poly$Day_Night <- if (length(daynight_val) > 0) daynight_val[1] else NA
#   sf_poly})
# 
# burst_list <- burst_list[!sapply(burst_list, is.null)]
# BBMM_2019_M_Day_all_9 <- do.call(rbind, burst_list)
# 
# # Merge polygons per Serial
# BBMM_2019_M_Day_merged <- BBMM_2019_M_Day_all |>
#   dplyr::mutate(Serial = factor(Serial)) |>
#   dplyr::group_by(Serial) |>
#   dplyr::summarize(geometry = sf::st_union(geometry)) |>
#   sf::st_as_sf(crs = 32631)

# save(BBMM_2019_M_Day_merged, file="BBMM_2019_M_Day_merged.Rdata")
# save(BBMM_2019_M_Day_all   , file="BBMM_2019_M_Day_all.Rdata")
# save(BBMM_2019_M_Day_all_9, file="BBMM_2019_M_Day_all_9.Rdata")
load("BBMM_2019_M_Day_merged.Rdata")
load("BBMM_2019_M_Day_all.Rdata")
load("BBMM_2019_M_Day_all_9.Rdata", verbose = TRUE)

BBMM_2019_M_Day_by_serial <- BBMM_2019_M_Day_all_9 |> 
  st_make_valid() |> 
  dplyr::group_by(Serial) |> 
  dplyr::summarize(geometry = sf::st_union(geometry), .groups = "drop") |> 
  sf::st_as_sf(crs=32631)

# Plot
Final_Plot_2019_Day_DD <- ggplot() +
  geom_sf(data = land_crop, fill = "white", color = "black", linewidth = 0.2) +
  geom_sf(data = BBMM_2019_M_Day_by_serial, aes(fill = Serial),
          alpha = 0.5, color = "black", linewidth = 0.2) +
  scale_fill_manual(values = serial_pal(22), name = "Serial") +
  annotate("text",
           x      = 614480,    
           y      = 6667650,  
           label  = "2019 Day",
           hjust  = 0.5,
           vjust  = 0.1,
           size   = 5,
           fontface = "bold") +
  annotate("text",
           x        = 615520,
           y        = 6667450,
           label    = "Stora Karlsøy", hjust    = 0.5, vjust    = 0.5,
           size     = 5, fontface = "italic") +
  theme_bw() +
  theme(panel.background = element_rect(fill = "lightblue"),
        panel.grid       = element_blank(),
        legend.position  = "none",
        legend.key.size  = unit(0.4, "cm"),
        legend.text      = element_text(size = 8),
        legend.title     = element_text(size = 9),
        axis.text        = element_blank(),
        axis.ticks       = element_blank())

# Map 2019 Day DD
Final_Plot_2019_Day_DD <- Final_Plot_2019_Day_DD +
  coord_sf(xlim = c(frame_bbox["xmin"], frame_bbox["xmax"]),
           ylim = c(frame_bbox["ymin"], frame_bbox["ymax"]),
           crs = st_crs(32631), expand = FALSE)
print(Final_Plot_2019_Day_DD)

# All merged
# merged_geom <- sf::st_union(BBMM_2019_M_Day_all)
merged_geom <- sf::st_union(BBMM_2019_M_Day_all_9) |> st_make_valid()
land_union <- st_union(land_crop) |> st_make_valid()
merged_geom_noland <- st_difference(merged_geom, land_union)
BBMM_2019_M_Day_merged <- sf::st_sf(geometry = merged_geom_noland, crs = 32631)

# Plot
Final_Plot_2019_Day_DD_merged <- ggplot() +
  geom_sf(data = land_crop, fill = "white", color = "black", linewidth = 0.2) +
  geom_sf(data = BBMM_2019_M_Day_merged, fill = "grey40",
          alpha = 0.5, color = "black", linewidth = 0.2) +
  annotate("text",
           x      = 614730,
           y      = 6667650,
           label  = "2019 Day Deep Dive",
           hjust  = 0.5,
           vjust  = 0.1,
           size   = 5,
           fontface = "bold") +
  annotate("text",
           x        = 615520,
           y        = 6667450,
           label    = "Stora Karlsøy",
           hjust    = 0.5,
           vjust    = 0.5,
           size     = 5,
           fontface = "italic") +
  theme_bw() +
  theme(panel.background = element_rect(fill = "lightblue"),
        panel.grid       = element_blank(),
        legend.position  = "none",
        axis.text        = element_blank(),
        axis.ticks       = element_blank())

# Add the Deep Dive locations (red and yellow)
if (exists("DL_F_2019_Day") && !is.null(DL_F_2019_Day)) {
  pts_sf <- st_as_sf(DL_F_2019_Day, coords = c("LON", "LAT"), crs = 4326) |>
    st_transform(32631)
  inside <- lengths(st_intersects(pts_sf, BBMM_2019_M_Day_merged)) > 0
  pts_inside  <- pts_sf[inside, ]
  pts_outside <- pts_sf[!inside, ]
  Final_Plot_2019_Day_DD_merged <- Final_Plot_2019_Day_DD_merged +
    geom_sf(data = pts_outside, color = "black", fill = "yellow",
            shape = 21, size = 3, stroke = 1) +
    geom_sf(data = pts_inside, color = "black", fill = "red",
            shape = 21, size = 3, stroke = 1)}

# Map 2019 Day DD merged
Final_Plot_2019_Day_DD_merged <- Final_Plot_2019_Day_DD_merged +
  coord_sf(xlim = c(frame_bbox["xmin"], frame_bbox["xmax"]),
           ylim = c(frame_bbox["ymin"], frame_bbox["ymax"]),
           crs = st_crs(32631), expand = FALSE)

print(Final_Plot_2019_Day_DD_merged)

(Final_Plot_2019_Day_DD | Final_Plot_2019_Night_DD) /
  (Final_Plot_2019_Day_DD_merged | Final_Plot_2019_Night_DD_merged) +
  plot_annotation(tag_levels = 'A') &
  theme(plot.tag.position = c(0.96, 0.96),
        plot.tag = element_text(size = 14, face = "bold"))

###############################################################################
###############################################################################
# 2020 Night
###############################################################################
###############################################################################

# UTM coordinates
Filt_sf <- st_as_sf(Filt_BK_spawn_20M_12h_Night_M, coords = c("LON", "LAT"), crs = 4326) |>
  st_transform(32631)
Filt_BK_coords <- Filt_BK_spawn_20M_12h_Night_M |>
  mutate(X_utm = st_coordinates(Filt_sf)[,1], Y_utm = st_coordinates(Filt_sf)[,2])

# Grid
x  <- seq(min(Filt_BK_coords$X_utm) - 2000, max(Filt_BK_coords$X_utm) + 2000, by = 20)
y  <- seq(min(Filt_BK_coords$Y_utm) - 3000, max(Filt_BK_coords$Y_utm) + 3000, by = 20)
xy <- expand.grid(x = x, y = y)
coordinates(xy) <- ~x + y
gridded(xy)     <- TRUE
proj4string(xy) <- CRS(SRS_string = "EPSG:32631")

# Plot frame (WGS84 -> UTM 32631)
frame_bbox <- st_as_sfc(st_bbox(c(xmin = 5.055, 
                                  xmax = 5.110,
                                  ymin = 60.115, 
                                  ymax = 60.130), 
                                crs = 4326)) |>
  st_transform(32631) |>
  st_bbox()

# transform X Y to UTM
utm_coords <- st_coordinates(Filt_sf)
x_offset   <- mean(utm_coords[,1] - Filt_BK_spawn_20M_12h_Night_M$X)
y_offset   <- mean(utm_coords[,2] - Filt_BK_spawn_20M_12h_Night_M$Y)

# # Burst to serial
# burst_to_serial <- Filt_BK_spawn_20M_12h_Night_M |>
#   dplyr::select(Burst_b, Serial, DATETIME, Day_Night) |>
#   distinct() |>
#   mutate(Burst_b = as.character(Burst_b))
# 
# # Get UD50 polygons, shift to UTM and tag per Serial
# burst_list <- lapply(names(tnm_spawn_20M_12h_dd_Night_9), function(nm) {
#   poly <- tryCatch(getverticeshr(tnm_spawn_20M_12h_dd_Night_9[[nm]], percent = 50),
#                    error = function(e) NULL)
#   if (is.null(poly)) return(NULL)
#   
#   sf_poly <- st_as_sf(poly) |>
#     st_set_crs(NA) |>
#     mutate(geometry = geometry + c(x_offset, y_offset)) |>
#     st_set_crs(32631)
#   
#   serial_val     <- burst_to_serial$Serial[burst_to_serial$Burst_b == nm]
#   sf_poly$Serial <- if (length(serial_val) > 0) as.character(serial_val[1]) else NA
#   datetime_val     <- burst_to_serial$DATETIME[burst_to_serial$Burst_b == nm]
#   sf_poly$DATETIME <- if (length(datetime_val) > 0) datetime_val[1] else NA
#   
#   daynight_val      <- burst_to_serial$Day_Night[burst_to_serial$Burst_b == nm]
#   sf_poly$Day_Night <- if (length(daynight_val) > 0) daynight_val[1] else NA
#   sf_poly
# })
# 
# burst_list <- burst_list[!sapply(burst_list, is.null)]
# BBMM_2020_M_Night_all_9 <- do.call(rbind, burst_list)
# 
# # Merge polygons per Serial
# BBMM_2020_M_Night_merged <- BBMM_2020_M_Night_all_9 |>
#   mutate(Serial = factor(Serial)) |>
#   dplyr::group_by(Serial) |>
#   dplyr::summarize(geometry = sf::st_union(geometry)) |>
#   sf::st_as_sf(crs = 32631)

# save(BBMM_2020_M_Night_merged, file="BBMM_2020_M_Night_merged.Rdata")
# save(BBMM_2020_M_Night_all   , file="BBMM_2020_M_Night_all.Rdata")
# save(BBMM_2020_M_Night_all_9, file="BBMM_2020_M_Night_all_9.Rdata")
load("BBMM_2020_M_Night_all_9.Rdata")
load("BBMM_2020_M_Night_merged.Rdata")

BBMM_2020_M_Night_all_9 <- BBMM_2020_M_Night_all_9 |>
  mutate(Serial = factor(Serial))

BBMM_2020_M_Night_by_serial <- BBMM_2020_M_Night_all_9 |> 
  st_make_valid() |> 
  dplyr::group_by(Serial) |> 
  dplyr::summarize(geometry = sf::st_union(geometry), .groups = "drop") |> 
  sf::st_as_sf(crs=32631)

# Plot
Final_Plot_2020_Night_DD <- ggplot() +
  geom_sf(data = land_crop, fill = "white", color = "black", linewidth = 0.2) +
  geom_sf(data = BBMM_2020_M_Night_by_serial, aes(fill = Serial),
          alpha = 0.5, color = "black", linewidth = 0.2) +
  scale_fill_manual(values = serial_pal(22), name = "Serial") +
  annotate("text",
           x      = 614480,    
           y      = 6667650,  
           label  = "2020 Night",
           hjust  = 0.5,             
           vjust  = 0.1,
           size   = 5,
           fontface = "bold") +
  annotate("text",
           x        = 615520,
           y        = 6667450,
           label    = "Stora Karlsøy", hjust    = 0.5, vjust    = 0.5,
           size     = 5, fontface = "italic") +
  theme_bw() +
  theme(panel.background = element_rect(fill = "lightblue"),
        panel.grid       = element_blank(),
        legend.position = "none",
        legend.key.size  = unit(0.4, "cm"),
        legend.text      = element_text(size = 8),
        legend.title     = element_text(size = 9),
        axis.text        = element_blank(),
        axis.ticks       = element_blank())

# Map 2020 Night DD
Final_Plot_2020_Night_DD <- Final_Plot_2020_Night_DD +
  coord_sf(xlim = c(frame_bbox["xmin"], frame_bbox["xmax"]),
           ylim = c(frame_bbox["ymin"], frame_bbox["ymax"]),
           crs = st_crs(32631), expand = FALSE)
print(Final_Plot_2020_Night_DD)

# All merged
merged_geom <- sf::st_union(BBMM_2020_M_Night_all_9) |> st_make_valid()
land_union <- st_union(land_crop) |> st_make_valid()
merged_geom_noland <- st_difference(merged_geom, land_union)
BBMM_2020_M_Night_merged <- sf::st_sf(geometry = merged_geom_noland, crs = 32631)

# Plot
Final_Plot_2020_Night_DD_merged <- ggplot() +
  geom_sf(data = land_crop, fill = "white", color = "black", linewidth = 0.2) +
  geom_sf(data = BBMM_2020_M_Night_merged, fill = "grey40",
          alpha = 0.5, color = "black", linewidth = 0.2) +
  annotate("text",
           x      = 614780,
           y      = 6667650,
           label  = "2020 Night Deep Dive",
           hjust  = 0.5,
           vjust  = 0.1,
           size   = 5,
           fontface = "bold") +
  annotate("text",
           x        = 615520,
           y        = 6667450,
           label    = "Stora Karlsøy",
           hjust    = 0.5,
           vjust    = 0.5,
           size     = 5,
           fontface = "italic") +
  theme_bw() +
  theme(panel.background = element_rect(fill = "lightblue"),
        panel.grid       = element_blank(),
        legend.position  = "none",
        axis.text        = element_blank(),
        axis.ticks       = element_blank())

# Add the Deep Dive locations Night (yellow points)
if (exists("DL_F_2020_Night") && !is.null(DL_F_2020_Night)) {
  pts_sf <- st_as_sf(DL_F_2020_Night, coords = c("LON", "LAT"), crs = 4326) |>
    st_transform(32631)
  inside <- lengths(st_intersects(pts_sf, BBMM_2020_M_Night_merged)) > 0
  pts_inside  <- pts_sf[inside, ]
  pts_outside <- pts_sf[!inside, ]
  Final_Plot_2020_Night_DD_merged <- Final_Plot_2020_Night_DD_merged +
    geom_sf(data = pts_outside, color = "black", fill = "yellow",
            shape = 21, size = 3, stroke = 1) +
    geom_sf(data = pts_inside, color = "black", fill = "red",
            shape = 21, size = 3, stroke = 1)}

# Map 2020 Night DD merged
Final_Plot_2020_Night_DD_merged <- Final_Plot_2020_Night_DD_merged +
  coord_sf(xlim = c(frame_bbox["xmin"], frame_bbox["xmax"]),
           ylim = c(frame_bbox["ymin"], frame_bbox["ymax"]),
           crs = st_crs(32631), expand = FALSE)

print(Final_Plot_2020_Night_DD_merged)

###############################################################################
# 2020 Day
###############################################################################

# UTM coordinates
Filt_sf <- st_as_sf(Filt_BK_spawn_20M_12h_Day_M, coords = c("LON", "LAT"), crs = 4326) |>
  st_transform(32631)
Filt_BK_coords <- Filt_BK_spawn_20M_12h_Day_M |>
  mutate(X_utm = st_coordinates(Filt_sf)[,1], Y_utm = st_coordinates(Filt_sf)[,2])

# Grid
x  <- seq(min(Filt_BK_coords$X_utm) - 2000, max(Filt_BK_coords$X_utm) + 2000, by = 20)
y  <- seq(min(Filt_BK_coords$Y_utm) - 3000, max(Filt_BK_coords$Y_utm) + 3000, by = 20)
xy <- expand.grid(x = x, y = y)
coordinates(xy) <- ~x + y
gridded(xy)     <- TRUE
proj4string(xy) <- CRS(SRS_string = "EPSG:32631")

# Plot frame (WGS84 -> UTM 32631)
frame_bbox <- st_as_sfc(st_bbox(c(xmin = 5.055, 
                                  xmax = 5.110,
                                  ymin = 60.115, 
                                  ymax = 60.130), 
                                crs = 4326)) |>
  st_transform(32631) |>
  st_bbox()

# Offset: local X/Y -> real UTM
utm_coords <- st_coordinates(Filt_sf)
x_offset   <- mean(utm_coords[,1] - Filt_BK_spawn_20M_12h_Day_M$X)
y_offset   <- mean(utm_coords[,2] - Filt_BK_spawn_20M_12h_Day_M$Y)

# # Burst -> Serial lookup
# burst_to_serial <- Filt_BK_spawn_20M_12h_Day_M |>
#   dplyr::select(Burst_b, Serial, DATETIME, Day_Night) |>
#   distinct() |>
#   mutate(Burst_b = as.character(Burst_b))
# 
# # Extract UD50 polygons, shift to real UTM, tag with Serial
# burst_list <- lapply(names(tnm_spawn_20M_12h_dd_Day_9), function(nm) {
#   poly <- tryCatch(getverticeshr(tnm_spawn_20M_12h_dd_Day_9[[nm]], percent = 50),
#                    error = function(e) NULL)
#   if (is.null(poly)) return(NULL)
#   sf_poly <- st_as_sf(poly) |>
#     st_set_crs(NA) |>
#     mutate(geometry = geometry + c(x_offset, y_offset)) |>
#     st_set_crs(32631)
#   serial_val     <- burst_to_serial$Serial[burst_to_serial$Burst_b == nm]
#   sf_poly$Serial <- if (length(serial_val) > 0) as.character(serial_val[1]) else NA
#   datetime_val     <- burst_to_serial$DATETIME[burst_to_serial$Burst_b == nm]
#   sf_poly$DATETIME <- if (length(datetime_val) > 0) datetime_val[1] else NA
#   daynight_val      <- burst_to_serial$Day_Night[burst_to_serial$Burst_b == nm]
#   sf_poly$Day_Night <- if (length(daynight_val) > 0) daynight_val[1] else NA
#   sf_poly})
# 
# burst_list <- burst_list[!sapply(burst_list, is.null)]
# BBMM_2020_M_Day_all_9 <- do.call(rbind, burst_list)
# 
# # Merge polygons per Serial
# BBMM_2020_M_Day_merged <- BBMM_2020_M_Day_all |>
#   dplyr::mutate(Serial = factor(Serial)) |>
#   dplyr::group_by(Serial) |>
#   dplyr::summarize(geometry = sf::st_union(geometry)) |>
#   sf::st_as_sf(crs = 32631)

# save(BBMM_2020_M_Day_merged, file="BBMM_2020_M_Day_merged.Rdata")
# save(BBMM_2020_M_Day_all   , file="BBMM_2020_M_Day_all.Rdata")
# save(BBMM_2020_M_Day_all_9, file="BBMM_2020_M_Day_all_9.Rdata")
load("BBMM_2020_M_Day_merged.Rdata")
load("BBMM_2020_M_Day_all.Rdata")
load("BBMM_2020_M_Day_all_9.Rdata", verbose = TRUE)

BBMM_2020_M_Day_by_serial <- BBMM_2020_M_Day_all_9 |> 
  st_make_valid() |> 
  dplyr::group_by(Serial) |> 
  dplyr::summarize(geometry = sf::st_union(geometry), .groups = "drop") |> 
  sf::st_as_sf(crs=32631)

# Plot
Final_Plot_2020_Day_DD <- ggplot() +
  geom_sf(data = land_crop, fill = "white", color = "black", linewidth = 0.2) +
  geom_sf(data = BBMM_2020_M_Day_by_serial, aes(fill = Serial),
          alpha = 0.5, color = "black", linewidth = 0.2) +
  scale_fill_manual(values = serial_pal(22), name = "Serial") +
  annotate("text",
           x      = 614480,    
           y      = 6667650,  
           label  = "2020 Day",
           hjust  = 0.5,
           vjust  = 0.1,
           size   = 5,
           fontface = "bold") +
  annotate("text",
           x        = 615520,
           y        = 6667450,
           label    = "Stora Karlsøy", hjust    = 0.5, vjust    = 0.5,
           size     = 5, fontface = "italic") +
  theme_bw() +
  theme(panel.background = element_rect(fill = "lightblue"),
        panel.grid       = element_blank(),
        legend.position  = "none",
        legend.key.size  = unit(0.4, "cm"),
        legend.text      = element_text(size = 8),
        legend.title     = element_text(size = 9),
        axis.text        = element_blank(),
        axis.ticks       = element_blank())

# Map 2020 Day DD
Final_Plot_2020_Day_DD <- Final_Plot_2020_Day_DD +
  coord_sf(xlim = c(frame_bbox["xmin"], frame_bbox["xmax"]),
           ylim = c(frame_bbox["ymin"], frame_bbox["ymax"]),
           crs = st_crs(32631), expand = FALSE)
print(Final_Plot_2020_Day_DD)

# All merged
# merged_geom <- sf::st_union(BBMM_2020_M_Day_all)
merged_geom <- sf::st_union(BBMM_2020_M_Day_all_9) |> st_make_valid()
land_union <- st_union(land_crop) |> st_make_valid()
merged_geom_noland <- st_difference(merged_geom, land_union)
BBMM_2020_M_Day_merged <- sf::st_sf(geometry = merged_geom_noland, crs = 32631)

# Plot
Final_Plot_2020_Day_DD_merged <- ggplot() +
  geom_sf(data = land_crop, fill = "white", color = "black", linewidth = 0.2) +
  geom_sf(data = BBMM_2020_M_Day_merged, fill = "grey40",
          alpha = 0.5, color = "black", linewidth = 0.2) +
  annotate("text",
           x      = 614730,
           y      = 6667650,
           label  = "2020 Day Deep Dive",
           hjust  = 0.5,
           vjust  = 0.1,
           size   = 5,
           fontface = "bold") +
  annotate("text",
           x        = 615520,
           y        = 6667450,
           label    = "Stora Karlsøy",
           hjust    = 0.5,
           vjust    = 0.5,
           size     = 5,
           fontface = "italic") +
  theme_bw() +
  theme(panel.background = element_rect(fill = "lightblue"),
        panel.grid       = element_blank(),
        legend.position  = "none",
        axis.text        = element_blank(),
        axis.ticks       = element_blank())

# Add the Deep Dive locations (red and yellow)
if (exists("DL_F_2020_Day") && !is.null(DL_F_2020_Day)) {
  pts_sf <- st_as_sf(DL_F_2020_Day, coords = c("LON", "LAT"), crs = 4326) |>
    st_transform(32631)
  inside <- lengths(st_intersects(pts_sf, BBMM_2020_M_Day_merged)) > 0
  pts_inside  <- pts_sf[inside, ]
  pts_outside <- pts_sf[!inside, ]
  Final_Plot_2020_Day_DD_merged <- Final_Plot_2020_Day_DD_merged +
    geom_sf(data = pts_outside, color = "black", fill = "yellow",
            shape = 21, size = 3, stroke = 1) +
    geom_sf(data = pts_inside, color = "black", fill = "red",
            shape = 21, size = 3, stroke = 1)}

# Map 2020 Day DD merged
Final_Plot_2020_Day_DD_merged <- Final_Plot_2020_Day_DD_merged +
  coord_sf(xlim = c(frame_bbox["xmin"], frame_bbox["xmax"]),
           ylim = c(frame_bbox["ymin"], frame_bbox["ymax"]),
           crs = st_crs(32631), expand = FALSE)

print(Final_Plot_2020_Day_DD_merged)

(Final_Plot_2020_Day_DD | Final_Plot_2020_Night_DD) /
  (Final_Plot_2020_Day_DD_merged | Final_Plot_2020_Night_DD_merged) +
  plot_annotation(tag_levels = 'A') &
  theme(plot.tag.position = c(0.96, 0.96),
        plot.tag = element_text(size = 14, face = "bold"))

###############################################################################
# 2021 Night
###############################################################################

# UTM coordinates
Filt_sf <- st_as_sf(Filt_BK_spawn_21M_12h_Night_M, coords = c("LON", "LAT"), crs = 4326) |>
  st_transform(32631)
Filt_BK_coords <- Filt_BK_spawn_21M_12h_Night_M |>
  mutate(X_utm = st_coordinates(Filt_sf)[,1], Y_utm = st_coordinates(Filt_sf)[,2])

# Grid
x  <- seq(min(Filt_BK_coords$X_utm) - 2000, max(Filt_BK_coords$X_utm) + 2000, by = 20)
y  <- seq(min(Filt_BK_coords$Y_utm) - 3000, max(Filt_BK_coords$Y_utm) + 3000, by = 20)
xy <- expand.grid(x = x, y = y)
coordinates(xy) <- ~x + y
gridded(xy)     <- TRUE
proj4string(xy) <- CRS(SRS_string = "EPSG:32631")

# Plot frame (WGS84 -> UTM 32631)
frame_bbox <- st_as_sfc(st_bbox(c(xmin = 5.055, 
                                  xmax = 5.110,
                                  ymin = 60.115, 
                                  ymax = 60.130), 
                                crs = 4326)) |>
  st_transform(32631) |>
  st_bbox()

# transform X Y to UTM
utm_coords <- st_coordinates(Filt_sf)
x_offset   <- mean(utm_coords[,1] - Filt_BK_spawn_21M_12h_Night_M$X)
y_offset   <- mean(utm_coords[,2] - Filt_BK_spawn_21M_12h_Night_M$Y)

# # Burst to serial
# burst_to_serial <- Filt_BK_spawn_21M_12h_Night_M |>
#   dplyr::select(Burst_b, Serial, DATETIME, Day_Night) |>
#   distinct() |>
#   mutate(Burst_b = as.character(Burst_b))
# 
# # Get UD50 polygons, shift to UTM and tag per Serial
# burst_list <- lapply(names(tnm_spawn_21M_12h_dd_Night_9), function(nm) {
#   poly <- tryCatch(getverticeshr(tnm_spawn_21M_12h_dd_Night_9[[nm]], percent = 50),
#                    error = function(e) NULL)
#   if (is.null(poly)) return(NULL)
#   
#   sf_poly <- st_as_sf(poly) |>
#     st_set_crs(NA) |>
#     mutate(geometry = geometry + c(x_offset, y_offset)) |>
#     st_set_crs(32631)
#   
#   serial_val     <- burst_to_serial$Serial[burst_to_serial$Burst_b == nm]
#   sf_poly$Serial <- if (length(serial_val) > 0) as.character(serial_val[1]) else NA
#   datetime_val     <- burst_to_serial$DATETIME[burst_to_serial$Burst_b == nm]
#   sf_poly$DATETIME <- if (length(datetime_val) > 0) datetime_val[1] else NA
#   
#   daynight_val      <- burst_to_serial$Day_Night[burst_to_serial$Burst_b == nm]
#   sf_poly$Day_Night <- if (length(daynight_val) > 0) daynight_val[1] else NA
#   sf_poly
# })
# 
# burst_list <- burst_list[!sapply(burst_list, is.null)]
# BBMM_2021_M_Night_all_9 <- do.call(rbind, burst_list)
# 
# # Merge polygons per Serial
# BBMM_2021_M_Night_merged <- BBMM_2021_M_Night_all_9 |>
#   mutate(Serial = factor(Serial)) |>
#   dplyr::group_by(Serial) |>
#   dplyr::summarize(geometry = sf::st_union(geometry)) |>
#   sf::st_as_sf(crs = 32631)

# save(BBMM_2021_M_Night_merged, file="BBMM_2021_M_Night_merged.Rdata")
# save(BBMM_2021_M_Night_all   , file="BBMM_2021_M_Night_all.Rdata")
# save(BBMM_2021_M_Night_all_9, file="BBMM_2021_M_Night_all_9.Rdata")
load("BBMM_2021_M_Night_all_9.Rdata")
load("BBMM_2021_M_Night_merged.Rdata")

BBMM_2021_M_Night_all_9 <- BBMM_2021_M_Night_all_9 |>
  mutate(Serial = factor(Serial))

BBMM_2021_M_Night_by_serial <- BBMM_2021_M_Night_all_9 |> 
  st_make_valid() |> 
  dplyr::group_by(Serial) |> 
  dplyr::summarize(geometry = sf::st_union(geometry), .groups = "drop") |> 
  sf::st_as_sf(crs=32631)

# Plot
Final_Plot_2021_Night_DD <- ggplot() +
  geom_sf(data = land_crop, fill = "white", color = "black", linewidth = 0.2) +
  geom_sf(data = BBMM_2021_M_Night_by_serial, aes(fill = Serial),
          alpha = 0.5, color = "black", linewidth = 0.2) +
  scale_fill_manual(values = serial_pal(22), name = "Serial") +
  annotate("text",
           x      = 614480,    
           y      = 6667650,  
           label  = "2021 Night",
           hjust  = 0.5,             
           vjust  = 0.1,
           size   = 5,
           fontface = "bold") +
  annotate("text",
           x        = 615520,
           y        = 6667450,
           label    = "Stora Karlsøy", hjust    = 0.5, vjust    = 0.5,
           size     = 5, fontface = "italic") +
  theme_bw() +
  theme(panel.background = element_rect(fill = "lightblue"),
        panel.grid       = element_blank(),
        legend.position = "none",
        legend.key.size  = unit(0.4, "cm"),
        legend.text      = element_text(size = 8),
        legend.title     = element_text(size = 9),
        axis.text        = element_blank(),
        axis.ticks       = element_blank())

# Map 2021 Night DD
Final_Plot_2021_Night_DD <- Final_Plot_2021_Night_DD +
  coord_sf(xlim = c(frame_bbox["xmin"], frame_bbox["xmax"]),
           ylim = c(frame_bbox["ymin"], frame_bbox["ymax"]),
           crs = st_crs(32631), expand = FALSE)
print(Final_Plot_2021_Night_DD)

# All merged
merged_geom <- sf::st_union(BBMM_2021_M_Night_all_9) |> st_make_valid()
land_union <- st_union(land_crop) |> st_make_valid()
merged_geom_noland <- st_difference(merged_geom, land_union)
BBMM_2021_M_Night_merged <- sf::st_sf(geometry = merged_geom_noland, crs = 32631)

# Plot
Final_Plot_2021_Night_DD_merged <- ggplot() +
  geom_sf(data = land_crop, fill = "white", color = "black", linewidth = 0.2) +
  geom_sf(data = BBMM_2021_M_Night_merged, fill = "grey40",
          alpha = 0.5, color = "black", linewidth = 0.2) +
  annotate("text",
           x      = 614780,
           y      = 6667650,
           label  = "2021 Night Deep Dive",
           hjust  = 0.5,
           vjust  = 0.1,
           size   = 5,
           fontface = "bold") +
  annotate("text",
           x        = 615520,
           y        = 6667450,
           label    = "Stora Karlsøy",
           hjust    = 0.5,
           vjust    = 0.5,
           size     = 5,
           fontface = "italic") +
  theme_bw() +
  theme(panel.background = element_rect(fill = "lightblue"),
        panel.grid       = element_blank(),
        legend.position  = "none",
        axis.text        = element_blank(),
        axis.ticks       = element_blank())

# Add the Deep Dive locations Night (yellow points)
if (exists("DL_F_2021_Night") && !is.null(DL_F_2021_Night)) {
  pts_sf <- st_as_sf(DL_F_2021_Night, coords = c("LON", "LAT"), crs = 4326) |>
    st_transform(32631)
  inside <- lengths(st_intersects(pts_sf, BBMM_2021_M_Night_merged)) > 0
  pts_inside  <- pts_sf[inside, ]
  pts_outside <- pts_sf[!inside, ]
  Final_Plot_2021_Night_DD_merged <- Final_Plot_2021_Night_DD_merged +
    geom_sf(data = pts_outside, color = "black", fill = "yellow",
            shape = 21, size = 3, stroke = 1) +
    geom_sf(data = pts_inside, color = "black", fill = "red",
            shape = 21, size = 3, stroke = 1)}

# Map 2021 Night DD merged
Final_Plot_2021_Night_DD_merged <- Final_Plot_2021_Night_DD_merged +
  coord_sf(xlim = c(frame_bbox["xmin"], frame_bbox["xmax"]),
           ylim = c(frame_bbox["ymin"], frame_bbox["ymax"]),
           crs = st_crs(32631), expand = FALSE)

print(Final_Plot_2021_Night_DD_merged)

###############################################################################
# 2021 Day
###############################################################################

# UTM coordinates
Filt_sf <- st_as_sf(Filt_BK_spawn_21M_12h_Day_M, coords = c("LON", "LAT"), crs = 4326) |>
  st_transform(32631)
Filt_BK_coords <- Filt_BK_spawn_21M_12h_Day_M |>
  mutate(X_utm = st_coordinates(Filt_sf)[,1], Y_utm = st_coordinates(Filt_sf)[,2])

# Grid
x  <- seq(min(Filt_BK_coords$X_utm) - 2000, max(Filt_BK_coords$X_utm) + 2000, by = 20)
y  <- seq(min(Filt_BK_coords$Y_utm) - 3000, max(Filt_BK_coords$Y_utm) + 3000, by = 20)
xy <- expand.grid(x = x, y = y)
coordinates(xy) <- ~x + y
gridded(xy)     <- TRUE
proj4string(xy) <- CRS(SRS_string = "EPSG:32631")

# Plot frame (WGS84 -> UTM 32631)
frame_bbox <- st_as_sfc(st_bbox(c(xmin = 5.055, 
                                  xmax = 5.110,
                                  ymin = 60.115, 
                                  ymax = 60.130), 
                                crs = 4326)) |>
  st_transform(32631) |>
  st_bbox()

# Offset: local X/Y -> real UTM
utm_coords <- st_coordinates(Filt_sf)
x_offset   <- mean(utm_coords[,1] - Filt_BK_spawn_21M_12h_Day_M$X)
y_offset   <- mean(utm_coords[,2] - Filt_BK_spawn_21M_12h_Day_M$Y)

# # Burst -> Serial lookup
# burst_to_serial <- Filt_BK_spawn_21M_12h_Day_M |>
#   dplyr::select(Burst_b, Serial, DATETIME, Day_Night) |>
#   distinct() |>
#   mutate(Burst_b = as.character(Burst_b))
# 
# # Extract UD50 polygons, shift to real UTM, tag with Serial
# burst_list <- lapply(names(tnm_spawn_21M_12h_dd_Day_9), function(nm) {
#   poly <- tryCatch(getverticeshr(tnm_spawn_21M_12h_dd_Day_9[[nm]], percent = 50),
#                    error = function(e) NULL)
#   if (is.null(poly)) return(NULL)
#   sf_poly <- st_as_sf(poly) |>
#     st_set_crs(NA) |>
#     mutate(geometry = geometry + c(x_offset, y_offset)) |>
#     st_set_crs(32631)
#   serial_val     <- burst_to_serial$Serial[burst_to_serial$Burst_b == nm]
#   sf_poly$Serial <- if (length(serial_val) > 0) as.character(serial_val[1]) else NA
#   datetime_val     <- burst_to_serial$DATETIME[burst_to_serial$Burst_b == nm]
#   sf_poly$DATETIME <- if (length(datetime_val) > 0) datetime_val[1] else NA
#   daynight_val      <- burst_to_serial$Day_Night[burst_to_serial$Burst_b == nm]
#   sf_poly$Day_Night <- if (length(daynight_val) > 0) daynight_val[1] else NA
#   sf_poly})
# 
# burst_list <- burst_list[!sapply(burst_list, is.null)]
# BBMM_2021_M_Day_all_9 <- do.call(rbind, burst_list)
# 
# # Merge polygons per Serial
# BBMM_2021_M_Day_merged <- BBMM_2021_M_Day_all |>
#   dplyr::mutate(Serial = factor(Serial)) |>
#   dplyr::group_by(Serial) |>
#   dplyr::summarize(geometry = sf::st_union(geometry)) |>
#   sf::st_as_sf(crs = 32631)

# save(BBMM_2021_M_Day_merged, file="BBMM_2021_M_Day_merged.Rdata")
# save(BBMM_2021_M_Day_all   , file="BBMM_2021_M_Day_all.Rdata")
# save(BBMM_2021_M_Day_all_9, file="BBMM_2021_M_Day_all_9.Rdata")
load("BBMM_2021_M_Day_merged.Rdata")
load("BBMM_2021_M_Day_all.Rdata")
load("BBMM_2021_M_Day_all_9.Rdata", verbose = TRUE)

BBMM_2021_M_Day_by_serial <- BBMM_2021_M_Day_all_9 |> 
  st_make_valid() |> 
  dplyr::group_by(Serial) |> 
  dplyr::summarize(geometry = sf::st_union(geometry), .groups = "drop") |> 
  sf::st_as_sf(crs=32631)

# Plot
Final_Plot_2021_Day_DD <- ggplot() +
  geom_sf(data = land_crop, fill = "white", color = "black", linewidth = 0.2) +
  geom_sf(data = BBMM_2021_M_Day_by_serial, aes(fill = Serial),
          alpha = 0.5, color = "black", linewidth = 0.2) +
  scale_fill_manual(values = serial_pal(22), name = "Serial") +
  annotate("text",
           x      = 614480,    
           y      = 6667650,  
           label  = "2021 Day",
           hjust  = 0.5,
           vjust  = 0.1,
           size   = 5,
           fontface = "bold") +
  annotate("text",
           x        = 615520,
           y        = 6667450,
           label    = "Stora Karlsøy", hjust    = 0.5, vjust    = 0.5,
           size     = 5, fontface = "italic") +
  theme_bw() +
  theme(panel.background = element_rect(fill = "lightblue"),
        panel.grid       = element_blank(),
        legend.position  = "none",
        legend.key.size  = unit(0.4, "cm"),
        legend.text      = element_text(size = 8),
        legend.title     = element_text(size = 9),
        axis.text        = element_blank(),
        axis.ticks       = element_blank())

# Map 2021 Day DD
Final_Plot_2021_Day_DD <- Final_Plot_2021_Day_DD +
  coord_sf(xlim = c(frame_bbox["xmin"], frame_bbox["xmax"]),
           ylim = c(frame_bbox["ymin"], frame_bbox["ymax"]),
           crs = st_crs(32631), expand = FALSE)
print(Final_Plot_2021_Day_DD)

# All merged
# merged_geom <- sf::st_union(BBMM_2021_M_Day_all)
merged_geom <- sf::st_union(BBMM_2021_M_Day_all_9) |> st_make_valid()
land_union <- st_union(land_crop) |> st_make_valid()
merged_geom_noland <- st_difference(merged_geom, land_union)
BBMM_2021_M_Day_merged <- sf::st_sf(geometry = merged_geom_noland, crs = 32631)

# Plot
Final_Plot_2021_Day_DD_merged <- ggplot() +
  geom_sf(data = land_crop, fill = "white", color = "black", linewidth = 0.2) +
  geom_sf(data = BBMM_2021_M_Day_merged, fill = "grey40",
          alpha = 0.5, color = "black", linewidth = 0.2) +
  annotate("text",
           x      = 614730,
           y      = 6667650,
           label  = "2021 Day Deep Dive",
           hjust  = 0.5,
           vjust  = 0.1,
           size   = 5,
           fontface = "bold") +
  annotate("text",
           x        = 615520,
           y        = 6667450,
           label    = "Stora Karlsøy",
           hjust    = 0.5,
           vjust    = 0.5,
           size     = 5,
           fontface = "italic") +
  theme_bw() +
  theme(panel.background = element_rect(fill = "lightblue"),
        panel.grid       = element_blank(),
        legend.position  = "none",
        axis.text        = element_blank(),
        axis.ticks       = element_blank())

# Add the Deep Dive locations (red and yellow)
if (exists("DL_F_2021_Day") && !is.null(DL_F_2021_Day)) {
  pts_sf <- st_as_sf(DL_F_2021_Day, coords = c("LON", "LAT"), crs = 4326) |>
    st_transform(32631)
  inside <- lengths(st_intersects(pts_sf, BBMM_2021_M_Day_merged)) > 0
  pts_inside  <- pts_sf[inside, ]
  pts_outside <- pts_sf[!inside, ]
  Final_Plot_2021_Day_DD_merged <- Final_Plot_2021_Day_DD_merged +
    geom_sf(data = pts_outside, color = "black", fill = "yellow",
            shape = 21, size = 3, stroke = 1) +
    geom_sf(data = pts_inside, color = "black", fill = "red",
            shape = 21, size = 3, stroke = 1)}

# Map 2021 Day DD merged
Final_Plot_2021_Day_DD_merged <- Final_Plot_2021_Day_DD_merged +
  coord_sf(xlim = c(frame_bbox["xmin"], frame_bbox["xmax"]),
           ylim = c(frame_bbox["ymin"], frame_bbox["ymax"]),
           crs = st_crs(32631), expand = FALSE)

print(Final_Plot_2021_Day_DD_merged)

(Final_Plot_2021_Day_DD | Final_Plot_2021_Night_DD) /
  (Final_Plot_2021_Day_DD_merged | Final_Plot_2021_Night_DD_merged) +
  plot_annotation(tag_levels = 'A') &
  theme(plot.tag.position = c(0.96, 0.96),
        plot.tag = element_text(size = 14, face = "bold"))

###############################################################################
# 2022 Night
###############################################################################

# UTM coordinates
Filt_sf <- st_as_sf(Filt_BK_spawn_22M_12h_Night_M, coords = c("LON", "LAT"), crs = 4326) |>
  st_transform(32631)
Filt_BK_coords <- Filt_BK_spawn_22M_12h_Night_M |>
  mutate(X_utm = st_coordinates(Filt_sf)[,1], Y_utm = st_coordinates(Filt_sf)[,2])

# Grid
x  <- seq(min(Filt_BK_coords$X_utm) - 2000, max(Filt_BK_coords$X_utm) + 2000, by = 20)
y  <- seq(min(Filt_BK_coords$Y_utm) - 3000, max(Filt_BK_coords$Y_utm) + 3000, by = 20)
xy <- expand.grid(x = x, y = y)
coordinates(xy) <- ~x + y
gridded(xy)     <- TRUE
proj4string(xy) <- CRS(SRS_string = "EPSG:32631")

# Plot frame (WGS84 -> UTM 32631)
frame_bbox <- st_as_sfc(st_bbox(c(xmin = 5.055, 
                                  xmax = 5.110,
                                  ymin = 60.115, 
                                  ymax = 60.130), 
                                crs = 4326)) |>
  st_transform(32631) |>
  st_bbox()

# transform X Y to UTM
utm_coords <- st_coordinates(Filt_sf)
x_offset   <- mean(utm_coords[,1] - Filt_BK_spawn_22M_12h_Night_M$X)
y_offset   <- mean(utm_coords[,2] - Filt_BK_spawn_22M_12h_Night_M$Y)

# # Burst to serial
# burst_to_serial <- Filt_BK_spawn_22M_12h_Night_M |>
#   dplyr::select(Burst_b, Serial, DATETIME, Day_Night) |>
#   distinct() |>
#   mutate(Burst_b = as.character(Burst_b))
# 
# # Get UD50 polygons, shift to UTM and tag per Serial
# burst_list <- lapply(names(tnm_spawn_22M_12h_dd_Night_9), function(nm) {
#   poly <- tryCatch(getverticeshr(tnm_spawn_22M_12h_dd_Night_9[[nm]], percent = 50),
#                    error = function(e) NULL)
#   if (is.null(poly)) return(NULL)
#   
#   sf_poly <- st_as_sf(poly) |>
#     st_set_crs(NA) |>
#     mutate(geometry = geometry + c(x_offset, y_offset)) |>
#     st_set_crs(32631)
#   
#   serial_val     <- burst_to_serial$Serial[burst_to_serial$Burst_b == nm]
#   sf_poly$Serial <- if (length(serial_val) > 0) as.character(serial_val[1]) else NA
#   datetime_val     <- burst_to_serial$DATETIME[burst_to_serial$Burst_b == nm]
#   sf_poly$DATETIME <- if (length(datetime_val) > 0) datetime_val[1] else NA
#   
#   daynight_val      <- burst_to_serial$Day_Night[burst_to_serial$Burst_b == nm]
#   sf_poly$Day_Night <- if (length(daynight_val) > 0) daynight_val[1] else NA
#   sf_poly
# })
# 
# burst_list <- burst_list[!sapply(burst_list, is.null)]
# BBMM_2022_M_Night_all_9 <- do.call(rbind, burst_list)
# 
# # Merge polygons per Serial
# BBMM_2022_M_Night_merged <- BBMM_2022_M_Night_all_9 |>
#   mutate(Serial = factor(Serial)) |>
#   dplyr::group_by(Serial) |>
#   dplyr::summarize(geometry = sf::st_union(geometry)) |>
#   sf::st_as_sf(crs = 32631)

# save(BBMM_2022_M_Night_merged, file="BBMM_2022_M_Night_merged.Rdata")
# save(BBMM_2022_M_Night_all   , file="BBMM_2022_M_Night_all.Rdata")
# save(BBMM_2022_M_Night_all_9, file="BBMM_2022_M_Night_all_9.Rdata")
load("BBMM_2022_M_Night_all_9.Rdata")
load("BBMM_2022_M_Night_merged.Rdata")

BBMM_2022_M_Night_all_9 <- BBMM_2022_M_Night_all_9 |>
  mutate(Serial = factor(Serial))

BBMM_2022_M_Night_by_serial <- BBMM_2022_M_Night_all_9 |> 
  st_make_valid() |> 
  dplyr::group_by(Serial) |> 
  dplyr::summarize(geometry = sf::st_union(geometry), .groups = "drop") |> 
  sf::st_as_sf(crs=32631)

# Plot
Final_Plot_2022_Night_DD <- ggplot() +
  geom_sf(data = land_crop, fill = "white", color = "black", linewidth = 0.2) +
  geom_sf(data = BBMM_2022_M_Night_by_serial, aes(fill = Serial),
          alpha = 0.5, color = "black", linewidth = 0.2) +
  scale_fill_manual(values = serial_pal(22), name = "Serial") +
  annotate("text",
           x      = 614480,    
           y      = 6667650,  
           label  = "2022 Night",
           hjust  = 0.5,             
           vjust  = 0.1,
           size   = 5,
           fontface = "bold") +
  annotate("text",
           x        = 615520,
           y        = 6667450,
           label    = "Stora Karlsøy", hjust    = 0.5, vjust    = 0.5,
           size     = 5, fontface = "italic") +
  theme_bw() +
  theme(panel.background = element_rect(fill = "lightblue"),
        panel.grid       = element_blank(),
        legend.position = "none",
        legend.key.size  = unit(0.4, "cm"),
        legend.text      = element_text(size = 8),
        legend.title     = element_text(size = 9),
        axis.text        = element_blank(),
        axis.ticks       = element_blank())

# Map 2022 Night DD
Final_Plot_2022_Night_DD <- Final_Plot_2022_Night_DD +
  coord_sf(xlim = c(frame_bbox["xmin"], frame_bbox["xmax"]),
           ylim = c(frame_bbox["ymin"], frame_bbox["ymax"]),
           crs = st_crs(32631), expand = FALSE)
print(Final_Plot_2022_Night_DD)

# All merged
merged_geom <- sf::st_union(BBMM_2022_M_Night_all_9) |> st_make_valid()
land_union <- st_union(land_crop) |> st_make_valid()
merged_geom_noland <- st_difference(merged_geom, land_union)
BBMM_2022_M_Night_merged <- sf::st_sf(geometry = merged_geom_noland, crs = 32631)

# Plot
Final_Plot_2022_Night_DD_merged <- ggplot() +
  geom_sf(data = land_crop, fill = "white", color = "black", linewidth = 0.2) +
  geom_sf(data = BBMM_2022_M_Night_merged, fill = "grey40",
          alpha = 0.5, color = "black", linewidth = 0.2) +
  annotate("text",
           x      = 614780,
           y      = 6667650,
           label  = "2022 Night Deep Dive",
           hjust  = 0.5,
           vjust  = 0.1,
           size   = 5,
           fontface = "bold") +
  annotate("text",
           x        = 615520,
           y        = 6667450,
           label    = "Stora Karlsøy",
           hjust    = 0.5,
           vjust    = 0.5,
           size     = 5,
           fontface = "italic") +
  theme_bw() +
  theme(panel.background = element_rect(fill = "lightblue"),
        panel.grid       = element_blank(),
        legend.position  = "none",
        axis.text        = element_blank(),
        axis.ticks       = element_blank())

# Add the Deep Dive locations Night (yellow points)
if (exists("DL_F_2022_Night") && !is.null(DL_F_2022_Night)) {
  pts_sf <- st_as_sf(DL_F_2022_Night, coords = c("LON", "LAT"), crs = 4326) |>
    st_transform(32631)
  inside <- lengths(st_intersects(pts_sf, BBMM_2022_M_Night_merged)) > 0
  pts_inside  <- pts_sf[inside, ]
  pts_outside <- pts_sf[!inside, ]
  Final_Plot_2022_Night_DD_merged <- Final_Plot_2022_Night_DD_merged +
    geom_sf(data = pts_outside, color = "black", fill = "yellow",
            shape = 21, size = 3, stroke = 1) +
    geom_sf(data = pts_inside, color = "black", fill = "red",
            shape = 21, size = 3, stroke = 1)}

# Map 2022 Night DD merged
Final_Plot_2022_Night_DD_merged <- Final_Plot_2022_Night_DD_merged +
  coord_sf(xlim = c(frame_bbox["xmin"], frame_bbox["xmax"]),
           ylim = c(frame_bbox["ymin"], frame_bbox["ymax"]),
           crs = st_crs(32631), expand = FALSE)

print(Final_Plot_2022_Night_DD_merged)

###############################################################################
###############################################################################
# 2022 Day
###############################################################################
###############################################################################

# UTM coordinates
Filt_sf <- st_as_sf(Filt_BK_spawn_22M_12h_Day_M, coords = c("LON", "LAT"), crs = 4326) |>
  st_transform(32631)
Filt_BK_coords <- Filt_BK_spawn_22M_12h_Day_M |>
  mutate(X_utm = st_coordinates(Filt_sf)[,1], Y_utm = st_coordinates(Filt_sf)[,2])

# Grid
x  <- seq(min(Filt_BK_coords$X_utm) - 2000, max(Filt_BK_coords$X_utm) + 2000, by = 20)
y  <- seq(min(Filt_BK_coords$Y_utm) - 3000, max(Filt_BK_coords$Y_utm) + 3000, by = 20)
xy <- expand.grid(x = x, y = y)
coordinates(xy) <- ~x + y
gridded(xy)     <- TRUE
proj4string(xy) <- CRS(SRS_string = "EPSG:32631")

# Plot frame (WGS84 -> UTM 32631)
frame_bbox <- st_as_sfc(st_bbox(c(xmin = 5.055, 
                                  xmax = 5.110,
                                  ymin = 60.115, 
                                  ymax = 60.130), 
                                crs = 4326)) |>
  st_transform(32631) |>
  st_bbox()

# Offset: local X/Y -> real UTM
utm_coords <- st_coordinates(Filt_sf)
x_offset   <- mean(utm_coords[,1] - Filt_BK_spawn_22M_12h_Day_M$X)
y_offset   <- mean(utm_coords[,2] - Filt_BK_spawn_22M_12h_Day_M$Y)

# # Burst -> Serial lookup
# burst_to_serial <- Filt_BK_spawn_22M_12h_Day_M |>
#   dplyr::select(Burst_b, Serial, DATETIME, Day_Night) |>
#   distinct() |>
#   mutate(Burst_b = as.character(Burst_b))
# 
# # Extract UD50 polygons, shift to real UTM, tag with Serial
# burst_list <- lapply(names(tnm_spawn_22M_12h_dd_Day_9), function(nm) {
#   poly <- tryCatch(getverticeshr(tnm_spawn_22M_12h_dd_Day_9[[nm]], percent = 50),
#                    error = function(e) NULL)
#   if (is.null(poly)) return(NULL)
#   sf_poly <- st_as_sf(poly) |>
#     st_set_crs(NA) |>
#     mutate(geometry = geometry + c(x_offset, y_offset)) |>
#     st_set_crs(32631)
#   serial_val     <- burst_to_serial$Serial[burst_to_serial$Burst_b == nm]
#   sf_poly$Serial <- if (length(serial_val) > 0) as.character(serial_val[1]) else NA
#   datetime_val     <- burst_to_serial$DATETIME[burst_to_serial$Burst_b == nm]
#   sf_poly$DATETIME <- if (length(datetime_val) > 0) datetime_val[1] else NA
#   daynight_val      <- burst_to_serial$Day_Night[burst_to_serial$Burst_b == nm]
#   sf_poly$Day_Night <- if (length(daynight_val) > 0) daynight_val[1] else NA
#   sf_poly})
# 
# burst_list <- burst_list[!sapply(burst_list, is.null)]
# BBMM_2022_M_Day_all_9 <- do.call(rbind, burst_list)
# 
# # Merge polygons per Serial
# BBMM_2022_M_Day_merged <- BBMM_2022_M_Day_all |>
#   dplyr::mutate(Serial = factor(Serial)) |>
#   dplyr::group_by(Serial) |>
#   dplyr::summarize(geometry = sf::st_union(geometry)) |>
#   sf::st_as_sf(crs = 32631)

# save(BBMM_2022_M_Day_merged, file="BBMM_2022_M_Day_merged.Rdata")
# save(BBMM_2022_M_Day_all   , file="BBMM_2022_M_Day_all.Rdata")
# save(BBMM_2022_M_Day_all_9, file="BBMM_2022_M_Day_all_9.Rdata")
load("BBMM_2022_M_Day_merged.Rdata")
load("BBMM_2022_M_Day_all.Rdata")
load("BBMM_2022_M_Day_all_9.Rdata", verbose = TRUE)

BBMM_2022_M_Day_by_serial <- BBMM_2022_M_Day_all_9 |> 
  st_make_valid() |> 
  dplyr::group_by(Serial) |> 
  dplyr::summarize(geometry = sf::st_union(geometry), .groups = "drop") |> 
  sf::st_as_sf(crs=32631)

# Plot
Final_Plot_2022_Day_DD <- ggplot() +
  geom_sf(data = land_crop, fill = "white", color = "black", linewidth = 0.2) +
  geom_sf(data = BBMM_2022_M_Day_by_serial, aes(fill = Serial),
          alpha = 0.5, color = "black", linewidth = 0.2) +
  scale_fill_manual(values = serial_pal(22), name = "Serial") +
  annotate("text",
           x      = 614480,    
           y      = 6667650,  
           label  = "2022 Day",
           hjust  = 0.5,
           vjust  = 0.1,
           size   = 5,
           fontface = "bold") +
  annotate("text",
           x        = 615520,
           y        = 6667450,
           label    = "Stora Karlsøy", hjust    = 0.5, vjust    = 0.5,
           size     = 5, fontface = "italic") +
  theme_bw() +
  theme(panel.background = element_rect(fill = "lightblue"),
        panel.grid       = element_blank(),
        legend.position  = "none",
        legend.key.size  = unit(0.4, "cm"),
        legend.text      = element_text(size = 8),
        legend.title     = element_text(size = 9),
        axis.text        = element_blank(),
        axis.ticks       = element_blank())

# Map 2022 Day DD
Final_Plot_2022_Day_DD <- Final_Plot_2022_Day_DD +
  coord_sf(xlim = c(frame_bbox["xmin"], frame_bbox["xmax"]),
           ylim = c(frame_bbox["ymin"], frame_bbox["ymax"]),
           crs = st_crs(32631), expand = FALSE)
print(Final_Plot_2022_Day_DD)

# All merged
# merged_geom <- sf::st_union(BBMM_2022_M_Day_all)
merged_geom <- sf::st_union(BBMM_2022_M_Day_all_9) |> st_make_valid()
land_union <- st_union(land_crop) |> st_make_valid()
merged_geom_noland <- st_difference(merged_geom, land_union)
BBMM_2022_M_Day_merged <- sf::st_sf(geometry = merged_geom_noland, crs = 32631)

# Plot
Final_Plot_2022_Day_DD_merged <- ggplot() +
  geom_sf(data = land_crop, fill = "white", color = "black", linewidth = 0.2) +
  geom_sf(data = BBMM_2022_M_Day_merged, fill = "grey40",
          alpha = 0.5, color = "black", linewidth = 0.2) +
  annotate("text",
           x      = 614730,
           y      = 6667650,
           label  = "2022 Day Deep Dive",
           hjust  = 0.5,
           vjust  = 0.1,
           size   = 5,
           fontface = "bold") +
  annotate("text",
           x        = 615520,
           y        = 6667450,
           label    = "Stora Karlsøy",
           hjust    = 0.5,
           vjust    = 0.5,
           size     = 5,
           fontface = "italic") +
  theme_bw() +
  theme(panel.background = element_rect(fill = "lightblue"),
        panel.grid       = element_blank(),
        legend.position  = "none",
        axis.text        = element_blank(),
        axis.ticks       = element_blank())

# Add the Deep Dive locations (red and yellow)
if (exists("DL_F_2022_Day") && !is.null(DL_F_2022_Day)) {
  pts_sf <- st_as_sf(DL_F_2022_Day, coords = c("LON", "LAT"), crs = 4326) |>
    st_transform(32631)
  inside <- lengths(st_intersects(pts_sf, BBMM_2022_M_Day_merged)) > 0
  pts_inside  <- pts_sf[inside, ]
  pts_outside <- pts_sf[!inside, ]
  Final_Plot_2022_Day_DD_merged <- Final_Plot_2022_Day_DD_merged +
    geom_sf(data = pts_outside, color = "black", fill = "yellow",
            shape = 21, size = 3, stroke = 1) +
    geom_sf(data = pts_inside, color = "black", fill = "red",
            shape = 21, size = 3, stroke = 1)}

# Map 2022 Day DD merged
Final_Plot_2022_Day_DD_merged <- Final_Plot_2022_Day_DD_merged +
  coord_sf(xlim = c(frame_bbox["xmin"], frame_bbox["xmax"]),
           ylim = c(frame_bbox["ymin"], frame_bbox["ymax"]),
           crs = st_crs(32631), expand = FALSE)

print(Final_Plot_2022_Day_DD_merged)

(Final_Plot_2022_Day_DD | Final_Plot_2022_Night_DD) /
  (Final_Plot_2022_Day_DD_merged | Final_Plot_2022_Night_DD_merged) +
  plot_annotation(tag_levels = 'A') &
  theme(plot.tag.position = c(0.96, 0.96),
        plot.tag = element_text(size = 14, face = "bold"))

###############################################################################
# 2023 Night
###############################################################################

# UTM coordinates
Filt_sf <- st_as_sf(Filt_BK_spawn_23M_12h_Night_M, coords = c("LON", "LAT"), crs = 4326) |>
  st_transform(32631)
Filt_BK_coords <- Filt_BK_spawn_23M_12h_Night_M |>
  mutate(X_utm = st_coordinates(Filt_sf)[,1], Y_utm = st_coordinates(Filt_sf)[,2])

# Grid
x  <- seq(min(Filt_BK_coords$X_utm) - 2000, max(Filt_BK_coords$X_utm) + 2000, by = 20)
y  <- seq(min(Filt_BK_coords$Y_utm) - 3000, max(Filt_BK_coords$Y_utm) + 3000, by = 20)
xy <- expand.grid(x = x, y = y)
coordinates(xy) <- ~x + y
gridded(xy)     <- TRUE
proj4string(xy) <- CRS(SRS_string = "EPSG:32631")

# Plot frame (WGS84 -> UTM 32631)
frame_bbox <- st_as_sfc(st_bbox(c(xmin = 5.055, 
                                  xmax = 5.110,
                                  ymin = 60.115, 
                                  ymax = 60.130), 
                                crs = 4326)) |>
  st_transform(32631) |>
  st_bbox()

# transform X Y to UTM
utm_coords <- st_coordinates(Filt_sf)
x_offset   <- mean(utm_coords[,1] - Filt_BK_spawn_23M_12h_Night_M$X)
y_offset   <- mean(utm_coords[,2] - Filt_BK_spawn_23M_12h_Night_M$Y)

# # Burst to serial
# burst_to_serial <- Filt_BK_spawn_23M_12h_Night_M |>
#   dplyr::select(Burst_b, Serial, DATETIME, Day_Night) |>
#   distinct() |>
#   mutate(Burst_b = as.character(Burst_b))
# 
# # Get UD50 polygons, shift to UTM and tag per Serial
# burst_list <- lapply(names(tnm_spawn_23M_12h_dd_Night_9), function(nm) {
#   poly <- tryCatch(getverticeshr(tnm_spawn_23M_12h_dd_Night_9[[nm]], percent = 50),
#                    error = function(e) NULL)
#   if (is.null(poly)) return(NULL)
#   
#   sf_poly <- st_as_sf(poly) |>
#     st_set_crs(NA) |>
#     mutate(geometry = geometry + c(x_offset, y_offset)) |>
#     st_set_crs(32631)
#   
#   serial_val     <- burst_to_serial$Serial[burst_to_serial$Burst_b == nm]
#   sf_poly$Serial <- if (length(serial_val) > 0) as.character(serial_val[1]) else NA
#   datetime_val     <- burst_to_serial$DATETIME[burst_to_serial$Burst_b == nm]
#   sf_poly$DATETIME <- if (length(datetime_val) > 0) datetime_val[1] else NA
#   
#   daynight_val      <- burst_to_serial$Day_Night[burst_to_serial$Burst_b == nm]
#   sf_poly$Day_Night <- if (length(daynight_val) > 0) daynight_val[1] else NA
#   sf_poly
# })
# 
# burst_list <- burst_list[!sapply(burst_list, is.null)]
# BBMM_2023_M_Night_all_9 <- do.call(rbind, burst_list)
# 
# # Merge polygons per Serial
# BBMM_2023_M_Night_merged <- BBMM_2023_M_Night_all_9 |>
#   mutate(Serial = factor(Serial)) |>
#   dplyr::group_by(Serial) |>
#   dplyr::summarize(geometry = sf::st_union(geometry)) |>
#   sf::st_as_sf(crs = 32631)

# save(BBMM_2023_M_Night_merged, file="BBMM_2023_M_Night_merged.Rdata")
# save(BBMM_2023_M_Night_all   , file="BBMM_2023_M_Night_all.Rdata")
# save(BBMM_2023_M_Night_all_9, file="BBMM_2023_M_Night_all_9.Rdata")
load("BBMM_2023_M_Night_all_9.Rdata")
load("BBMM_2023_M_Night_merged.Rdata")

BBMM_2023_M_Night_all_9 <- BBMM_2023_M_Night_all_9 |>
  mutate(Serial = factor(Serial))

BBMM_2023_M_Night_by_serial <- BBMM_2023_M_Night_all_9 |> 
  st_make_valid() |> 
  dplyr::group_by(Serial) |> 
  dplyr::summarize(geometry = sf::st_union(geometry), .groups = "drop") |> 
  sf::st_as_sf(crs=32631)

# Plot
Final_Plot_2023_Night_DD <- ggplot() +
  geom_sf(data = land_crop, fill = "white", color = "black", linewidth = 0.2) +
  geom_sf(data = BBMM_2023_M_Night_by_serial, aes(fill = Serial),
          alpha = 0.5, color = "black", linewidth = 0.2) +
  scale_fill_manual(values = serial_pal(22), name = "Serial") +
  annotate("text",
           x      = 614480,    
           y      = 6667650,  
           label  = "2023 Night",
           hjust  = 0.5,             
           vjust  = 0.1,
           size   = 5,
           fontface = "bold") +
  annotate("text",
           x        = 615520,
           y        = 6667450,
           label    = "Stora Karlsøy", hjust    = 0.5, vjust    = 0.5,
           size     = 5, fontface = "italic") +
  theme_bw() +
  theme(panel.background = element_rect(fill = "lightblue"),
        panel.grid       = element_blank(),
        legend.position = "none",
        legend.key.size  = unit(0.4, "cm"),
        legend.text      = element_text(size = 8),
        legend.title     = element_text(size = 9),
        axis.text        = element_blank(),
        axis.ticks       = element_blank())

# Map 2023 Night DD
Final_Plot_2023_Night_DD <- Final_Plot_2023_Night_DD +
  coord_sf(xlim = c(frame_bbox["xmin"], frame_bbox["xmax"]),
           ylim = c(frame_bbox["ymin"], frame_bbox["ymax"]),
           crs = st_crs(32631), expand = FALSE)
print(Final_Plot_2023_Night_DD)

# All merged
merged_geom <- sf::st_union(BBMM_2023_M_Night_all_9) |> st_make_valid()
land_union <- st_union(land_crop) |> st_make_valid()
merged_geom_noland <- st_difference(merged_geom, land_union)
BBMM_2023_M_Night_merged <- sf::st_sf(geometry = merged_geom_noland, crs = 32631)

# Plot
Final_Plot_2023_Night_DD_merged <- ggplot() +
  geom_sf(data = land_crop, fill = "white", color = "black", linewidth = 0.2) +
  geom_sf(data = BBMM_2023_M_Night_merged, fill = "grey40",
          alpha = 0.5, color = "black", linewidth = 0.2) +
  annotate("text",
           x      = 614780,
           y      = 6667650,
           label  = "2023 Night Deep Dive",
           hjust  = 0.5,
           vjust  = 0.1,
           size   = 5,
           fontface = "bold") +
  annotate("text",
           x        = 615520,
           y        = 6667450,
           label    = "Stora Karlsøy",
           hjust    = 0.5,
           vjust    = 0.5,
           size     = 5,
           fontface = "italic") +
  theme_bw() +
  theme(panel.background = element_rect(fill = "lightblue"),
        panel.grid       = element_blank(),
        legend.position  = "none",
        axis.text        = element_blank(),
        axis.ticks       = element_blank())

# Add the Deep Dive locations Night (yellow points)
if (exists("DL_F_2023_Night") && !is.null(DL_F_2023_Night)) {
  pts_sf <- st_as_sf(DL_F_2023_Night, coords = c("LON", "LAT"), crs = 4326) |>
    st_transform(32631)
  inside <- lengths(st_intersects(pts_sf, BBMM_2023_M_Night_merged)) > 0
  pts_inside  <- pts_sf[inside, ]
  pts_outside <- pts_sf[!inside, ]
  Final_Plot_2023_Night_DD_merged <- Final_Plot_2023_Night_DD_merged +
    geom_sf(data = pts_outside, color = "black", fill = "yellow",
            shape = 21, size = 3, stroke = 1) +
    geom_sf(data = pts_inside, color = "black", fill = "red",
            shape = 21, size = 3, stroke = 1)}

# Map 2023 Night DD merged
Final_Plot_2023_Night_DD_merged <- Final_Plot_2023_Night_DD_merged +
  coord_sf(xlim = c(frame_bbox["xmin"], frame_bbox["xmax"]),
           ylim = c(frame_bbox["ymin"], frame_bbox["ymax"]),
           crs = st_crs(32631), expand = FALSE)

print(Final_Plot_2023_Night_DD_merged)

###############################################################################
# 2023 Day
###############################################################################

# UTM coordinates
Filt_sf <- st_as_sf(Filt_BK_spawn_23M_12h_Day_M, coords = c("LON", "LAT"), crs = 4326) |>
  st_transform(32631)
Filt_BK_coords <- Filt_BK_spawn_23M_12h_Day_M |>
  mutate(X_utm = st_coordinates(Filt_sf)[,1], Y_utm = st_coordinates(Filt_sf)[,2])

# Grid
x  <- seq(min(Filt_BK_coords$X_utm) - 2000, max(Filt_BK_coords$X_utm) + 2000, by = 20)
y  <- seq(min(Filt_BK_coords$Y_utm) - 3000, max(Filt_BK_coords$Y_utm) + 3000, by = 20)
xy <- expand.grid(x = x, y = y)
coordinates(xy) <- ~x + y
gridded(xy)     <- TRUE
proj4string(xy) <- CRS(SRS_string = "EPSG:32631")

# Plot frame (WGS84 -> UTM 32631)
frame_bbox <- st_as_sfc(st_bbox(c(xmin = 5.055, 
                                  xmax = 5.110,
                                  ymin = 60.115, 
                                  ymax = 60.130), 
                                crs = 4326)) |>
  st_transform(32631) |>
  st_bbox()

# Offset: local X/Y -> real UTM
utm_coords <- st_coordinates(Filt_sf)
x_offset   <- mean(utm_coords[,1] - Filt_BK_spawn_23M_12h_Day_M$X)
y_offset   <- mean(utm_coords[,2] - Filt_BK_spawn_23M_12h_Day_M$Y)

# # Burst -> Serial lookup
# burst_to_serial <- Filt_BK_spawn_23M_12h_Day_M |>
#   dplyr::select(Burst_b, Serial, DATETIME, Day_Night) |>
#   distinct() |>
#   mutate(Burst_b = as.character(Burst_b))
# 
# # Extract UD50 polygons, shift to real UTM, tag with Serial
# burst_list <- lapply(names(tnm_spawn_23M_12h_dd_Day_9), function(nm) {
#   poly <- tryCatch(getverticeshr(tnm_spawn_23M_12h_dd_Day_9[[nm]], percent = 50),
#                    error = function(e) NULL)
#   if (is.null(poly)) return(NULL)
#   sf_poly <- st_as_sf(poly) |>
#     st_set_crs(NA) |>
#     mutate(geometry = geometry + c(x_offset, y_offset)) |>
#     st_set_crs(32631)
#   serial_val     <- burst_to_serial$Serial[burst_to_serial$Burst_b == nm]
#   sf_poly$Serial <- if (length(serial_val) > 0) as.character(serial_val[1]) else NA
#   datetime_val     <- burst_to_serial$DATETIME[burst_to_serial$Burst_b == nm]
#   sf_poly$DATETIME <- if (length(datetime_val) > 0) datetime_val[1] else NA
#   daynight_val      <- burst_to_serial$Day_Night[burst_to_serial$Burst_b == nm]
#   sf_poly$Day_Night <- if (length(daynight_val) > 0) daynight_val[1] else NA
#   sf_poly})
# 
# burst_list <- burst_list[!sapply(burst_list, is.null)]
# BBMM_2023_M_Day_all_9 <- do.call(rbind, burst_list)
# 
# # Merge polygons per Serial
# BBMM_2023_M_Day_merged <- BBMM_2023_M_Day_all |>
#   dplyr::mutate(Serial = factor(Serial)) |>
#   dplyr::group_by(Serial) |>
#   dplyr::summarize(geometry = sf::st_union(geometry)) |>
#   sf::st_as_sf(crs = 32631)

# save(BBMM_2023_M_Day_merged, file="BBMM_2023_M_Day_merged.Rdata")
# save(BBMM_2023_M_Day_all   , file="BBMM_2023_M_Day_all.Rdata")
# save(BBMM_2023_M_Day_all_9, file="BBMM_2023_M_Day_all_9.Rdata")
load("BBMM_2023_M_Day_merged.Rdata")
load("BBMM_2023_M_Day_all.Rdata")
load("BBMM_2023_M_Day_all_9.Rdata", verbose = TRUE)

BBMM_2023_M_Day_by_serial <- BBMM_2023_M_Day_all_9 |> 
  st_make_valid() |> 
  dplyr::group_by(Serial) |> 
  dplyr::summarize(geometry = sf::st_union(geometry), .groups = "drop") |> 
  sf::st_as_sf(crs=32631)

# Plot
Final_Plot_2023_Day_DD <- ggplot() +
  geom_sf(data = land_crop, fill = "white", color = "black", linewidth = 0.2) +
  geom_sf(data = BBMM_2023_M_Day_by_serial, aes(fill = Serial),
          alpha = 0.5, color = "black", linewidth = 0.2) +
  scale_fill_manual(values = serial_pal(22), name = "Serial") +
  annotate("text",
           x      = 614480,    
           y      = 6667650,  
           label  = "2023 Day",
           hjust  = 0.5,
           vjust  = 0.1,
           size   = 5,
           fontface = "bold") +
  annotate("text",
           x        = 615520,
           y        = 6667450,
           label    = "Stora Karlsøy", hjust    = 0.5, vjust    = 0.5,
           size     = 5, fontface = "italic") +
  theme_bw() +
  theme(panel.background = element_rect(fill = "lightblue"),
        panel.grid       = element_blank(),
        legend.position  = "none",
        legend.key.size  = unit(0.4, "cm"),
        legend.text      = element_text(size = 8),
        legend.title     = element_text(size = 9),
        axis.text        = element_blank(),
        axis.ticks       = element_blank())

# Map 2023 Day DD
Final_Plot_2023_Day_DD <- Final_Plot_2023_Day_DD +
  coord_sf(xlim = c(frame_bbox["xmin"], frame_bbox["xmax"]),
           ylim = c(frame_bbox["ymin"], frame_bbox["ymax"]),
           crs = st_crs(32631), expand = FALSE)
print(Final_Plot_2023_Day_DD)

# All merged
# merged_geom <- sf::st_union(BBMM_2023_M_Day_all)
merged_geom <- sf::st_union(BBMM_2023_M_Day_all_9) |> st_make_valid()
land_union <- st_union(land_crop) |> st_make_valid()
merged_geom_noland <- st_difference(merged_geom, land_union)
BBMM_2023_M_Day_merged <- sf::st_sf(geometry = merged_geom_noland, crs = 32631)

# Plot
Final_Plot_2023_Day_DD_merged <- ggplot() +
  geom_sf(data = land_crop, fill = "white", color = "black", linewidth = 0.2) +
  geom_sf(data = BBMM_2023_M_Day_merged, fill = "grey40",
          alpha = 0.5, color = "black", linewidth = 0.2) +
  annotate("text",
           x      = 614730,
           y      = 6667650,
           label  = "2023 Day Deep Dive",
           hjust  = 0.5,
           vjust  = 0.1,
           size   = 5,
           fontface = "bold") +
  annotate("text",
           x        = 615520,
           y        = 6667450,
           label    = "Stora Karlsøy",
           hjust    = 0.5,
           vjust    = 0.5,
           size     = 5,
           fontface = "italic") +
  theme_bw() +
  theme(panel.background = element_rect(fill = "lightblue"),
        panel.grid       = element_blank(),
        legend.position  = "none",
        axis.text        = element_blank(),
        axis.ticks       = element_blank())

# Add the Deep Dive locations (red and yellow)
if (exists("DL_F_2023_Day") && !is.null(DL_F_2023_Day)) {
  pts_sf <- st_as_sf(DL_F_2023_Day, coords = c("LON", "LAT"), crs = 4326) |>
    st_transform(32631)
  inside <- lengths(st_intersects(pts_sf, BBMM_2023_M_Day_merged)) > 0
  pts_inside  <- pts_sf[inside, ]
  pts_outside <- pts_sf[!inside, ]
  Final_Plot_2023_Day_DD_merged <- Final_Plot_2023_Day_DD_merged +
    geom_sf(data = pts_outside, color = "black", fill = "yellow",
            shape = 21, size = 3, stroke = 1) +
    geom_sf(data = pts_inside, color = "black", fill = "red",
            shape = 21, size = 3, stroke = 1)}

# Map 2023 Day DD merged
Final_Plot_2023_Day_DD_merged <- Final_Plot_2023_Day_DD_merged +
  coord_sf(xlim = c(frame_bbox["xmin"], frame_bbox["xmax"]),
           ylim = c(frame_bbox["ymin"], frame_bbox["ymax"]),
           crs = st_crs(32631), expand = FALSE)

print(Final_Plot_2023_Day_DD_merged)

(Final_Plot_2023_Day_DD | Final_Plot_2023_Night_DD) /
  (Final_Plot_2023_Day_DD_merged | Final_Plot_2023_Night_DD_merged) +
  plot_annotation(tag_levels = 'A') &
  theme(plot.tag.position = c(0.96, 0.96),
        plot.tag = element_text(size = 14, face = "bold"))

###############################################################################
# 2024 Night
###############################################################################

# UTM coordinates
Filt_sf <- st_as_sf(Filt_BK_spawn_24M_12h_Night_M, coords = c("LON", "LAT"), crs = 4326) |>
  st_transform(32631)
Filt_BK_coords <- Filt_BK_spawn_24M_12h_Night_M |>
  mutate(X_utm = st_coordinates(Filt_sf)[,1], Y_utm = st_coordinates(Filt_sf)[,2])

# Grid
x  <- seq(min(Filt_BK_coords$X_utm) - 2000, max(Filt_BK_coords$X_utm) + 2000, by = 20)
y  <- seq(min(Filt_BK_coords$Y_utm) - 3000, max(Filt_BK_coords$Y_utm) + 3000, by = 20)
xy <- expand.grid(x = x, y = y)
coordinates(xy) <- ~x + y
gridded(xy)     <- TRUE
proj4string(xy) <- CRS(SRS_string = "EPSG:32631")

# Plot frame (WGS84 -> UTM 32631)
frame_bbox <- st_as_sfc(st_bbox(c(xmin = 5.055, 
                                  xmax = 5.110,
                                  ymin = 60.115, 
                                  ymax = 60.130), 
                                crs = 4326)) |>
  st_transform(32631) |>
  st_bbox()

# transform X Y to UTM
utm_coords <- st_coordinates(Filt_sf)
x_offset   <- mean(utm_coords[,1] - Filt_BK_spawn_24M_12h_Night_M$X)
y_offset   <- mean(utm_coords[,2] - Filt_BK_spawn_24M_12h_Night_M$Y)

# # Burst to serial
# burst_to_serial <- Filt_BK_spawn_24M_12h_Night_M |>
#   dplyr::select(Burst_b, Serial, DATETIME, Day_Night) |>
#   distinct() |>
#   mutate(Burst_b = as.character(Burst_b))
# 
# # Get UD50 polygons, shift to UTM and tag per Serial
# burst_list <- lapply(names(tnm_spawn_24M_12h_dd_Night_9), function(nm) {
#   poly <- tryCatch(getverticeshr(tnm_spawn_24M_12h_dd_Night_9[[nm]], percent = 50),
#                    error = function(e) NULL)
#   if (is.null(poly)) return(NULL)
#   
#   sf_poly <- st_as_sf(poly) |>
#     st_set_crs(NA) |>
#     mutate(geometry = geometry + c(x_offset, y_offset)) |>
#     st_set_crs(32631)
#   
#   serial_val     <- burst_to_serial$Serial[burst_to_serial$Burst_b == nm]
#   sf_poly$Serial <- if (length(serial_val) > 0) as.character(serial_val[1]) else NA
#   datetime_val     <- burst_to_serial$DATETIME[burst_to_serial$Burst_b == nm]
#   sf_poly$DATETIME <- if (length(datetime_val) > 0) datetime_val[1] else NA
#   
#   daynight_val      <- burst_to_serial$Day_Night[burst_to_serial$Burst_b == nm]
#   sf_poly$Day_Night <- if (length(daynight_val) > 0) daynight_val[1] else NA
#   sf_poly
# })
# 
# burst_list <- burst_list[!sapply(burst_list, is.null)]
# BBMM_2024_M_Night_all_9 <- do.call(rbind, burst_list)
# 
# # Merge polygons per Serial
# BBMM_2024_M_Night_merged <- BBMM_2024_M_Night_all_9 |>
#   mutate(Serial = factor(Serial)) |>
#   dplyr::group_by(Serial) |>
#   dplyr::summarize(geometry = sf::st_union(geometry)) |>
#   sf::st_as_sf(crs = 32631)

# save(BBMM_2024_M_Night_merged, file="BBMM_2024_M_Night_merged.Rdata")
# save(BBMM_2024_M_Night_all   , file="BBMM_2024_M_Night_all.Rdata")
# save(BBMM_2024_M_Night_all_9, file="BBMM_2024_M_Night_all_9.Rdata")
load("BBMM_2024_M_Night_all_9.Rdata")
load("BBMM_2024_M_Night_merged.Rdata")

BBMM_2024_M_Night_all_9 <- BBMM_2024_M_Night_all_9 |>
  mutate(Serial = factor(Serial))

BBMM_2024_M_Night_by_serial <- BBMM_2024_M_Night_all_9 |> 
  st_make_valid() |> 
  dplyr::group_by(Serial) |> 
  dplyr::summarize(geometry = sf::st_union(geometry), .groups = "drop") |> 
  sf::st_as_sf(crs=32631)

# Plot
Final_Plot_2024_Night_DD <- ggplot() +
  geom_sf(data = land_crop, fill = "white", color = "black", linewidth = 0.2) +
  geom_sf(data = BBMM_2024_M_Night_by_serial, aes(fill = Serial),
          alpha = 0.5, color = "black", linewidth = 0.2) +
  scale_fill_manual(values = serial_pal(22), name = "Serial") +
  annotate("text",
           x      = 614480,    
           y      = 6667650,  
           label  = "2024 Night",
           hjust  = 0.5,             
           vjust  = 0.1,
           size   = 5,
           fontface = "bold") +
  annotate("text",
           x        = 615520,
           y        = 6667450,
           label    = "Stora Karlsøy", hjust    = 0.5, vjust    = 0.5,
           size     = 5, fontface = "italic") +
  theme_bw() +
  theme(panel.background = element_rect(fill = "lightblue"),
        panel.grid       = element_blank(),
        legend.position = "none",
        legend.key.size  = unit(0.4, "cm"),
        legend.text      = element_text(size = 8),
        legend.title     = element_text(size = 9),
        axis.text        = element_blank(),
        axis.ticks       = element_blank())

# Map 2024 Night DD
Final_Plot_2024_Night_DD <- Final_Plot_2024_Night_DD +
  coord_sf(xlim = c(frame_bbox["xmin"], frame_bbox["xmax"]),
           ylim = c(frame_bbox["ymin"], frame_bbox["ymax"]),
           crs = st_crs(32631), expand = FALSE)
print(Final_Plot_2024_Night_DD)

# All merged
merged_geom <- sf::st_union(BBMM_2024_M_Night_all_9) |> st_make_valid()
land_union <- st_union(land_crop) |> st_make_valid()
merged_geom_noland <- st_difference(merged_geom, land_union)
BBMM_2024_M_Night_merged <- sf::st_sf(geometry = merged_geom_noland, crs = 32631)

# Plot
Final_Plot_2024_Night_DD_merged <- ggplot() +
  geom_sf(data = land_crop, fill = "white", color = "black", linewidth = 0.2) +
  geom_sf(data = BBMM_2024_M_Night_merged, fill = "grey40",
          alpha = 0.5, color = "black", linewidth = 0.2) +
  annotate("text",
           x      = 614780,
           y      = 6667650,
           label  = "2024 Night Deep Dive",
           hjust  = 0.5,
           vjust  = 0.1,
           size   = 5,
           fontface = "bold") +
  annotate("text",
           x        = 615520,
           y        = 6667450,
           label    = "Stora Karlsøy",
           hjust    = 0.5,
           vjust    = 0.5,
           size     = 5,
           fontface = "italic") +
  theme_bw() +
  theme(panel.background = element_rect(fill = "lightblue"),
        panel.grid       = element_blank(),
        legend.position  = "none",
        axis.text        = element_blank(),
        axis.ticks       = element_blank())

# Add the Deep Dive locations Night (yellow points)
if (exists("DL_F_2024_Night") && !is.null(DL_F_2024_Night)) {
  pts_sf <- st_as_sf(DL_F_2024_Night, coords = c("LON", "LAT"), crs = 4326) |>
    st_transform(32631)
  inside <- lengths(st_intersects(pts_sf, BBMM_2024_M_Night_merged)) > 0
  pts_inside  <- pts_sf[inside, ]
  pts_outside <- pts_sf[!inside, ]
  Final_Plot_2024_Night_DD_merged <- Final_Plot_2024_Night_DD_merged +
    geom_sf(data = pts_outside, color = "black", fill = "yellow",
            shape = 21, size = 3, stroke = 1) +
    geom_sf(data = pts_inside, color = "black", fill = "red",
            shape = 21, size = 3, stroke = 1)}

# Map 2024 Night DD merged
Final_Plot_2024_Night_DD_merged <- Final_Plot_2024_Night_DD_merged +
  coord_sf(xlim = c(frame_bbox["xmin"], frame_bbox["xmax"]),
           ylim = c(frame_bbox["ymin"], frame_bbox["ymax"]),
           crs = st_crs(32631), expand = FALSE)

print(Final_Plot_2024_Night_DD_merged)

###############################################################################
# 2024 Day
###############################################################################

# UTM coordinates
Filt_sf <- st_as_sf(Filt_BK_spawn_24M_12h_Day_M, coords = c("LON", "LAT"), crs = 4326) |>
  st_transform(32631)
Filt_BK_coords <- Filt_BK_spawn_24M_12h_Day_M |>
  mutate(X_utm = st_coordinates(Filt_sf)[,1], Y_utm = st_coordinates(Filt_sf)[,2])

# Grid
x  <- seq(min(Filt_BK_coords$X_utm) - 2000, max(Filt_BK_coords$X_utm) + 2000, by = 20)
y  <- seq(min(Filt_BK_coords$Y_utm) - 3000, max(Filt_BK_coords$Y_utm) + 3000, by = 20)
xy <- expand.grid(x = x, y = y)
coordinates(xy) <- ~x + y
gridded(xy)     <- TRUE
proj4string(xy) <- CRS(SRS_string = "EPSG:32631")

# Plot frame (WGS84 -> UTM 32631)
frame_bbox <- st_as_sfc(st_bbox(c(xmin = 5.055, 
                                  xmax = 5.110,
                                  ymin = 60.115, 
                                  ymax = 60.130), 
                                crs = 4326)) |>
  st_transform(32631) |>
  st_bbox()

# Offset: local X/Y -> real UTM
utm_coords <- st_coordinates(Filt_sf)
x_offset   <- mean(utm_coords[,1] - Filt_BK_spawn_24M_12h_Day_M$X)
y_offset   <- mean(utm_coords[,2] - Filt_BK_spawn_24M_12h_Day_M$Y)

# # Burst -> Serial lookup
# burst_to_serial <- Filt_BK_spawn_24M_12h_Day_M |>
#   dplyr::select(Burst_b, Serial, DATETIME, Day_Night) |>
#   distinct() |>
#   mutate(Burst_b = as.character(Burst_b))
# 
# # Extract UD50 polygons, shift to real UTM, tag with Serial
# burst_list <- lapply(names(tnm_spawn_24M_12h_dd_Day_9), function(nm) {
#   poly <- tryCatch(getverticeshr(tnm_spawn_24M_12h_dd_Day_9[[nm]], percent = 50),
#                    error = function(e) NULL)
#   if (is.null(poly)) return(NULL)
#   sf_poly <- st_as_sf(poly) |>
#     st_set_crs(NA) |>
#     mutate(geometry = geometry + c(x_offset, y_offset)) |>
#     st_set_crs(32631)
#   serial_val     <- burst_to_serial$Serial[burst_to_serial$Burst_b == nm]
#   sf_poly$Serial <- if (length(serial_val) > 0) as.character(serial_val[1]) else NA
#   datetime_val     <- burst_to_serial$DATETIME[burst_to_serial$Burst_b == nm]
#   sf_poly$DATETIME <- if (length(datetime_val) > 0) datetime_val[1] else NA
#   daynight_val      <- burst_to_serial$Day_Night[burst_to_serial$Burst_b == nm]
#   sf_poly$Day_Night <- if (length(daynight_val) > 0) daynight_val[1] else NA
#   sf_poly})
# 
# burst_list <- burst_list[!sapply(burst_list, is.null)]
# BBMM_2024_M_Day_all_9 <- do.call(rbind, burst_list)
# 
# # Merge polygons per Serial
# BBMM_2024_M_Day_merged <- BBMM_2024_M_Day_all |>
#   dplyr::mutate(Serial = factor(Serial)) |>
#   dplyr::group_by(Serial) |>
#   dplyr::summarize(geometry = sf::st_union(geometry)) |>
#   sf::st_as_sf(crs = 32631)

# save(BBMM_2024_M_Day_merged, file="BBMM_2024_M_Day_merged.Rdata")
# save(BBMM_2024_M_Day_all   , file="BBMM_2024_M_Day_all.Rdata")
# save(BBMM_2024_M_Day_all_9, file="BBMM_2024_M_Day_all_9.Rdata")
load("BBMM_2024_M_Day_merged.Rdata")
load("BBMM_2024_M_Day_all.Rdata")
load("BBMM_2024_M_Day_all_9.Rdata", verbose = TRUE)

BBMM_2024_M_Day_by_serial <- BBMM_2024_M_Day_all_9 |> 
  st_make_valid() |> 
  dplyr::group_by(Serial) |> 
  dplyr::summarize(geometry = sf::st_union(geometry), .groups = "drop") |> 
  sf::st_as_sf(crs=32631)

# Plot
Final_Plot_2024_Day_DD <- ggplot() +
  geom_sf(data = land_crop, fill = "white", color = "black", linewidth = 0.2) +
  geom_sf(data = BBMM_2024_M_Day_by_serial, aes(fill = Serial),
          alpha = 0.5, color = "black", linewidth = 0.2) +
  scale_fill_manual(values = serial_pal(22), name = "Serial") +
  annotate("text",
           x      = 614480,    
           y      = 6667650,  
           label  = "2024 Day",
           hjust  = 0.5,
           vjust  = 0.1,
           size   = 5,
           fontface = "bold") +
  annotate("text",
           x        = 615520,
           y        = 6667450,
           label    = "Stora Karlsøy", hjust    = 0.5, vjust    = 0.5,
           size     = 5, fontface = "italic") +
  theme_bw() +
  theme(panel.background = element_rect(fill = "lightblue"),
        panel.grid       = element_blank(),
        legend.position  = "none",
        legend.key.size  = unit(0.4, "cm"),
        legend.text      = element_text(size = 8),
        legend.title     = element_text(size = 9),
        axis.text        = element_blank(),
        axis.ticks       = element_blank())

# Map 2024 Day DD
Final_Plot_2024_Day_DD <- Final_Plot_2024_Day_DD +
  coord_sf(xlim = c(frame_bbox["xmin"], frame_bbox["xmax"]),
           ylim = c(frame_bbox["ymin"], frame_bbox["ymax"]),
           crs = st_crs(32631), expand = FALSE)
print(Final_Plot_2024_Day_DD)

# All merged
# merged_geom <- sf::st_union(BBMM_2024_M_Day_all)
merged_geom <- sf::st_union(BBMM_2024_M_Day_all_9) |> st_make_valid()
land_union <- st_union(land_crop) |> st_make_valid()
merged_geom_noland <- st_difference(merged_geom, land_union)
BBMM_2024_M_Day_merged <- sf::st_sf(geometry = merged_geom_noland, crs = 32631)

# Plot
Final_Plot_2024_Day_DD_merged <- ggplot() +
  geom_sf(data = land_crop, fill = "white", color = "black", linewidth = 0.2) +
  geom_sf(data = BBMM_2024_M_Day_merged, fill = "grey40",
          alpha = 0.5, color = "black", linewidth = 0.2) +
  annotate("text",
           x      = 614730,
           y      = 6667650,
           label  = "2024 Day Deep Dive",
           hjust  = 0.5,
           vjust  = 0.1,
           size   = 5,
           fontface = "bold") +
  annotate("text",
           x        = 615520,
           y        = 6667450,
           label    = "Stora Karlsøy",
           hjust    = 0.5,
           vjust    = 0.5,
           size     = 5,
           fontface = "italic") +
  theme_bw() +
  theme(panel.background = element_rect(fill = "lightblue"),
        panel.grid       = element_blank(),
        legend.position  = "none",
        axis.text        = element_blank(),
        axis.ticks       = element_blank())

# Add the Deep Dive locations (red and yellow)
if (exists("DL_F_2024_Day") && !is.null(DL_F_2024_Day)) {
  pts_sf <- st_as_sf(DL_F_2024_Day, coords = c("LON", "LAT"), crs = 4326) |>
    st_transform(32631)
  inside <- lengths(st_intersects(pts_sf, BBMM_2024_M_Day_merged)) > 0
  pts_inside  <- pts_sf[inside, ]
  pts_outside <- pts_sf[!inside, ]
  Final_Plot_2024_Day_DD_merged <- Final_Plot_2024_Day_DD_merged +
    geom_sf(data = pts_outside, color = "black", fill = "yellow",
            shape = 21, size = 3, stroke = 1) +
    geom_sf(data = pts_inside, color = "black", fill = "red",
            shape = 21, size = 3, stroke = 1)}

# Map 2024 Day DD merged
Final_Plot_2024_Day_DD_merged <- Final_Plot_2024_Day_DD_merged +
  coord_sf(xlim = c(frame_bbox["xmin"], frame_bbox["xmax"]),
           ylim = c(frame_bbox["ymin"], frame_bbox["ymax"]),
           crs = st_crs(32631), expand = FALSE)

print(Final_Plot_2024_Day_DD_merged)

(Final_Plot_2024_Day_DD | Final_Plot_2024_Night_DD) /
  (Final_Plot_2024_Day_DD_merged | Final_Plot_2024_Night_DD_merged) +
  plot_annotation(tag_levels = 'A') &
  theme(plot.tag.position = c(0.96, 0.96),
        plot.tag = element_text(size = 14, face = "bold"))


########################################################
###  GLMM deep dives inside compound male core area  ###
########################################################

load("BBMM_2019_M_Day_merged.Rdata")
load("BBMM_2019_M_Night_merged.Rdata")
load("BBMM_2020_M_Day_merged.Rdata")
load("BBMM_2020_M_Night_merged.Rdata")
load("BBMM_2021_M_Day_merged.Rdata")
load("BBMM_2021_M_Night_merged.Rdata")
load("BBMM_2022_M_Day_merged.Rdata")
load("BBMM_2022_M_Night_merged.Rdata")
load("BBMM_2023_M_Day_merged.Rdata")
load("BBMM_2023_M_Night_merged.Rdata")
load("BBMM_2024_M_Day_merged.Rdata")
load("BBMM_2024_M_Night_merged.Rdata")

BBMM_2019_M_Night_25 <- st_intersection(BBMM_2019_M_Night_merged, concave_water_25)
BBMM_2019_M_Day_25   <- st_intersection(BBMM_2019_M_Day_merged,   concave_water_25)
BBMM_2020_M_Night_25 <- st_intersection(BBMM_2020_M_Night_merged, concave_water_25)
BBMM_2020_M_Day_25   <- st_intersection(BBMM_2020_M_Day_merged,   concave_water_25)
BBMM_2021_M_Night_25 <- st_intersection(BBMM_2021_M_Night_merged, concave_water_25)
BBMM_2021_M_Day_25   <- st_intersection(BBMM_2021_M_Day_merged,   concave_water_25)
BBMM_2022_M_Night_25 <- st_intersection(BBMM_2022_M_Night_merged, concave_water_25)
BBMM_2022_M_Day_25   <- st_intersection(BBMM_2022_M_Day_merged,   concave_water_25)
BBMM_2023_M_Night_25 <- st_intersection(BBMM_2023_M_Night_merged, concave_water_25)
BBMM_2023_M_Day_25   <- st_intersection(BBMM_2023_M_Day_merged,   concave_water_25)
BBMM_2024_M_Night_25 <- st_intersection(BBMM_2024_M_Night_merged, concave_water_25)
BBMM_2024_M_Day_25   <- st_intersection(BBMM_2024_M_Day_merged,   concave_water_25)

# make a list
ud_list <- list(list(bbmm = BBMM_2019_M_Night_merged, DataYear = 2019, Day_Night = "Night"),
                list(bbmm = BBMM_2019_M_Day_merged,   DataYear = 2019, Day_Night = "Day"),
                list(bbmm = BBMM_2020_M_Night_merged, DataYear = 2020, Day_Night = "Night"),
                list(bbmm = BBMM_2020_M_Day_merged,   DataYear = 2020, Day_Night = "Day"),
                list(bbmm = BBMM_2021_M_Night_merged, DataYear = 2021, Day_Night = "Night"),
                list(bbmm = BBMM_2021_M_Day_merged,   DataYear = 2021, Day_Night = "Day"),
                list(bbmm = BBMM_2022_M_Night_merged, DataYear = 2022, Day_Night = "Night"),
                list(bbmm = BBMM_2022_M_Day_merged,   DataYear = 2022, Day_Night = "Day"),
                list(bbmm = BBMM_2023_M_Night_merged, DataYear = 2023, Day_Night = "Night"),
                list(bbmm = BBMM_2023_M_Day_merged,   DataYear = 2023, Day_Night = "Day"),
                list(bbmm = BBMM_2024_M_Night_merged, DataYear = 2024, Day_Night = "Night"),
                list(bbmm = BBMM_2024_M_Day_merged,   DataYear = 2024, Day_Night = "Day"))

# make a list for 25 m depth
ud_list_25 <- list(list(bbmm = BBMM_2019_M_Night_25, DataYear = 2019, Day_Night = "Night"),
                   list(bbmm = BBMM_2019_M_Day_25,   DataYear = 2019, Day_Night = "Day"),
                   list(bbmm = BBMM_2020_M_Night_25, DataYear = 2020, Day_Night = "Night"),
                   list(bbmm = BBMM_2020_M_Day_25,   DataYear = 2020, Day_Night = "Day"),
                   list(bbmm = BBMM_2021_M_Night_25, DataYear = 2021, Day_Night = "Night"),
                   list(bbmm = BBMM_2021_M_Day_25,   DataYear = 2021, Day_Night = "Day"),
                   list(bbmm = BBMM_2022_M_Night_25, DataYear = 2022, Day_Night = "Night"),
                   list(bbmm = BBMM_2022_M_Day_25,   DataYear = 2022, Day_Night = "Day"),
                   list(bbmm = BBMM_2023_M_Night_25, DataYear = 2023, Day_Night = "Night"),
                   list(bbmm = BBMM_2023_M_Day_25,   DataYear = 2023, Day_Night = "Day"),
                   list(bbmm = BBMM_2024_M_Night_25, DataYear = 2024, Day_Night = "Night"),
                   list(bbmm = BBMM_2024_M_Day_25,   DataYear = 2024, Day_Night = "Day"))

# how big are the areas?
ud_area_lookup <- bind_rows(lapply(ud_list, function(x) {
  area_km2 <- as.numeric(st_area(st_union(x$bbmm)) / 1e6)
  data.frame(DataYear = x$DataYear, Day_Night = x$Day_Night, ud_area_km2 = area_km2)}))
ud_area_lookup_25 <- bind_rows(lapply(ud_list_25, function(x) {
  area_km2 <- as.numeric(st_area(st_union(x$bbmm)) / 1e6)
  data.frame(DataYear = x$DataYear, Day_Night = x$Day_Night, ud_area_km2 = area_km2)}))

# Build a lookup of UD union polygons for spatial join
ud_union_list <- lapply(ud_list_25, function(x) {
  list(union     = st_union(x$bbmm),
       DataYear  = x$DataYear,
       Day_Night = x$Day_Night)})

# Combine all Deep dives point data into one data frame
DD_all <- bind_rows(DL_F_2019_Night |> dplyr::mutate(DataYear = 2019, Day_Night = "Night"),
                    DL_F_2019_Day   |> dplyr::mutate(DataYear = 2019, Day_Night = "Day"),
                    DL_F_2020_Night |> dplyr::mutate(DataYear = 2020, Day_Night = "Night"),
                    DL_F_2020_Day   |> dplyr::mutate(DataYear = 2020, Day_Night = "Day"),
                    DL_F_2021_Night |> dplyr::mutate(DataYear = 2021, Day_Night = "Night"),
                    DL_F_2021_Day   |> dplyr::mutate(DataYear = 2021, Day_Night = "Day"),
                    DL_F_2022_Night |> dplyr::mutate(DataYear = 2022, Day_Night = "Night"),
                    DL_F_2022_Day   |> dplyr::mutate(DataYear = 2022, Day_Night = "Day"),
                    DL_F_2023_Night |> dplyr::mutate(DataYear = 2023, Day_Night = "Night"),
                    DL_F_2023_Day   |> dplyr::mutate(DataYear = 2023, Day_Night = "Day"),
                    DL_F_2024_Night |> dplyr::mutate(DataYear = 2024, Day_Night = "Night"),
                    DL_F_2024_Day   |> dplyr::mutate(DataYear = 2024, Day_Night = "Day"))

DD_all_table <- DD_all |> 
  group_by() |> 
  summarise(n = n(),        
            n_serial = n_distinct(Serial2),
            .groups = "drop")
DD_all_table
DD_all_N <- DD_all |> filter(Day_Night == "Night")
DD_all_D <- DD_all |> filter(Day_Night == "Day")

# Flag each point as within UD50 or not
DD_all$within_ud50 <- FALSE 
for (ud in ud_union_list) {
  # match if they are in the good period, otherwise next
  matching <- DD_all$DataYear == ud$DataYear & DD_all$Day_Night == ud$Day_Night
  if (sum(matching) == 0) next
  # make the locations have the same coordinate system
  pts <- st_as_sf(DD_all[matching, ], coords = c("LON", "LAT"), crs = 4326) |>
    st_transform(32631)  
  ud_union_proj <- st_transform(ud$union, 32631)  
  # flag the dots litterally inside and make a new column
  within_flags <- st_within(pts, ud_union_proj, sparse = FALSE)[, 1]
  DD_all$within_ud50[matching] <- within_flags}
print(DD_all)

# Attach UD area and compute offset, offset on logit scale
total_study_area_km2 <- 1.53
model_dd <- DD_all |>
  left_join(ud_area_lookup_25, by = c("DataYear", "Day_Night"))  |> 
  mutate(p_expected    = ud_area_km2 / total_study_area_km2,
         logit_p_exp   = qlogis(p_expected),
         within_ud50   = as.integer(within_ud50),
         Day_Night     = factor(Day_Night, levels = c("Day", "Night")),
         DataYear      = factor(DataYear))
print(model_dd)

# Mixed-effects logistic regression
model <- glmer(within_ud50 ~ Day_Night + (1 | Serial2) + (1|DataYear),
               data   = model_dd,
               family = binomial,
               offset = logit_p_exp)
summary(model)

dive_table <- DD_all |>
  ungroup() |>
  dplyr::count(within_ud50) |>
  mutate(ud50 = if_else(within_ud50, "Within UD50", "Outside UD50")) |>
  dplyr::select(-within_ud50) |>
  pivot_wider(names_from = ud50, values_from = n, values_fill = 0) |>
  dplyr::mutate(Total = `Within UD50` + `Outside UD50`,
                `% within UD50` = round(100 * `Within UD50` / Total, 1)) |>
  dplyr::arrange()
dive_table
