### self-clock-shifting processing ###

#### loading packages and required data read-in ####
rm(list = ls())

library(dplyr); library(data.table); library(raster); library(stringr); library(geosphere); library(lubridate); library(mixtools); library(sf); library(suncalc); library(ggplot2); library(circular); library(lme4); library(effects); library(rnaturalearth); library(rnaturalearthdata); library(rnaturalearthhires); library(performance); library(cowplot); library(AICcmodavg); library(ggspatial); library(pracma); library(scales); library(grid)


#create dataframe of each colony and its coordinates:
#the mins and maxs refer to the min and max of each colony's cells in the r5 raster, used for the clear beeline function
#the raster cells are 0.016667 degrees across in each dimension
colony_coords <- data.frame(colony = c("cp","sk","skok","lun","rum","ram","kilda"),
                            lon = c(-5.525785, -5.287829, -5.276882, -4.668419, -6.331190, -5.339924, -8.586639),
                            lat = c(54.695025, 51.737449, 51.697395, 51.176569, 57.005972, 51.866831, 57.815077),
                            lon_min = c(-5.533334, -5.300001, -5.283334, -4.666667, -6.450001, -5.350001, -8.648728),
                            lon_max = c(-5.516666, -5.283333, -5.266666, -4.649999, -6.249999, -5.283333, -8.471564),
                            lat_min = c(54.616666, 51.733333, 51.700000, 51.166666, 56.589999, 51.866666, 57.88143),
                            lat_max = c(54.683334, 51.750001, 51.716667, 51.200001, 57.066667, 51.900001, 57.79175),
                            max_elevation_m = c(24, 79, 55, 143, 812, 136, 430),
                            max_visibility_km = c(sqrt(13*c(24, 79, 55, 143, 812, 136, 430))))


#load a shapefile of British Isles with 30km buffer to find fixes wihtin 30km of land
buffer_bi <- st_read(dsn = "")
st_crs(buffer_bi)
#change the crs to lon lat and unify the features
buffer_bi <- st_transform(buffer_bi, crs = "+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0")
buffer_bi <- st_union(buffer_bi)
#load raster of steradians of visible land around UK
load("")


#### GPS read-in ####
#Set directory to look for GPS files in
dir <- ""

#get names of csv files in directory, including subfolders
names <- list.files(dir, pattern = ".csv", recursive = TRUE)

#create an empty list to be filled with processed tracks
all_metadata <- list()

#set the desired interpolated fix interval
desired_interval_secs <- 300



#loop through each file in turn
gps_list <- lapply(names, function(file){
  
  #read one file
  data <- read.csv(paste(dir,file,sep = "/"), skipNul = TRUE)
  
  #get the column names of the file; these will determine the necessary processing
  col_names <- colnames(data)
  
  #if column names are VX and there are a certain number of column names, rename them accordingly
  if("V1" %in% col_names & length(col_names) == 8){
    data %>% rename(lon = V3, lat = V2, comma_datetime = V1) -> data
    col_names <- colnames(data)
  } else if ("V1" %in% col_names & length(col_names) == 9){
    data %>% rename(lon = V4, lat = V3, Date = V1, Time = V2) -> data
    col_names <- colnames(data)
  } else if ("V1" %in% col_names & length(col_names) == 5){
    data %>% rename(lon = V2, lat = V1, date = V4, time = V5) -> data
    col_names <- colnames(data)
  }
  
  #split the file name up to get the metadata
  metadata <- strsplit(file,"/")
  metadata <- strsplit(metadata[[1]][2], "_")
  
  #extract metadata elements from the filename
  colony <- metadata[[1]][1]
  data$colony <- colony
  burrow <- metadata[[1]][2]
  data$burrow <- burrow
  ring <- metadata[[1]][3]
  data$ring <- ring
  gps <- metadata[[1]][4]
  data$gps <- gps
  gls <- metadata[[1]][5]
  data$gls <- gls
  campaign <- metadata[[1]][6]
  data$campaign <- campaign
  date <- strsplit(metadata[[1]][7], "\\.")
  date <- as.Date(date[[1]][1], format = "%Y%m%d")
  year <- year(date)
  month <- month(date)
  
  
  #add the corresponding colony coordinates to the data
  data$colony_lat <- colony_coords$lat[match(data$colony, colony_coords$colony)]
  data$colony_lon <- colony_coords$lon[match(data$colony, colony_coords$colony)]
  
  #### sorting lon/lat ####
  
  # Identify Long/Lat format and rename consistently (to lon/lat):
  if ("Latitude" %in% col_names){
    data %>% rename(lon = Longitude, lat = Latitude) -> data
  } else if ("long" %in% col_names){
    data %>% rename(lon = long, lat = lat) -> data
  } else if ("longitude" %in% col_names){
    data %>% rename(lon = longitude, lat = latitude) -> data
  } else if ("Lon" %in% col_names){
    data %>% rename(lon = Lon, lat = Lat) -> data
  } else if ("Long" %in% col_names){
    data %>% rename(lon = Long, lat = Lat) -> data
  } else if ("x" %in% col_names){
    data %>% rename(lon = x, lat = y) -> data
  } else if ("Latitude.deg." %in% col_names){
    data %>% rename(lon = Longitude.deg., lat = Latitude.deg.) -> data
  } else if (("i" %in% col_names)&("j" %in% col_names)&!("lat"%in%col_names)){
    data %>% rename(lon = j, lat = i) -> data
  } else if ("Longitude.1" %in% col_names){
    data %>% rename(lon = Longitude.1, lat = Latitude.1)
  } else if ("Latitude..deg." %in% col_names){
    data %>% rename(lon = Longitude..deg., lat = Latitude..deg.) -> data
  } else if ("londecd" %in% col_names){
    data$lon <- data$londecd
    data$lat <- data$latdecd
  }
  
  #if there are characters in the lon/lat columns so that they've been read as factors, convert them to characters then numeric
  #this makes character values NA
  if(!is.numeric(data$lat) | !is.numeric(data$lon)){
    data$lat <- as.numeric(as.character(data$lat))
    data$lon <- as.numeric(as.character(data$lon))
  }
  
  #retain rows with latitudes greater than 0 and where lon/lat are not NA
  data <- data[data$lat > 0 & !is.na(data$lat) & !is.na(data$lon),]
  #If latitude is coded without a decimal, divide to get it into correct scale
  if (data$lat[1] > 1000){
    data$lat <- data$lat/100
    data$lon <- data$lon/100
  }
  
  #retain only points within known usual range of Manx foraging trips
  data <- data[data$lat <70 & data$lat > 45 & data$lon < 6 & data$lon > -35,]
  
  
  #### sorting datetime ####
  
  # Identify date/time format and convert to POSIXct:
  if ("datetime" %in% col_names){
    data$datetime <- as.character(data$datetime)
    if(grepl("Z", data$datetime[1]) | grepl("T", data$datetime[1])){
      #remove characters from datetime
      data$datetime <- as.character(unlist(strsplit(data$datetime, "Z")))
      date_time <- as.character(unlist(strsplit(data$datetime, "T")))
      #paste components of datetime back together and make POSIXct object
      data$datetime <- paste(date_time[seq(1,(length(date_time)-1), 2)], date_time[seq(2, length(date_time), 2)], sep = " ")
      data$datetime <- as.POSIXct(data$datetime, format = "%Y-%m-%d %H:%M:%S", tz = "GMT")
    }else{
      #if column name is datetime but no characters in string, remove white space if too long and paste 00 for seconds to end if too short
      str_lengths <- str_length(data$datetime)
      data$datetime[str_lengths > 20] <- trimws(data$datetime[str_lengths > 20], which = "right")
      data$datetime[str_lengths < 20] <- paste0(data$datetime[str_lengths < 20], ':00')
      data$datetime <- as.POSIXct(data$datetime, tryFormats = c("%Y-%m-%dT%H:%M:%SZ", "%Y-%m-%d %H:%M:%S", "%d-%m-%Y %H:%M:%S", "%d/%m/%Y %H:%M:%S", "%d/%m/%Y  %H:%M:%S"), tz = "GMT") #convert datetime of any format to POSIXct
    }
  } else if ("time" %in% col_names & !("date" %in% col_names)){
    #if time in column names but not date, convert straight to POSIXct
    data$datetime <- as.POSIXct(data$time, tryFormats = "%Y-%m-%dT%H:%M:%SZ", tz = "GMT")
  } else if ("date" %in% col_names & !("time" %in% col_names)){
    #if date in names but not time, convert to character
    data$date <- as.character(data$date) 
    #if date is too short, there should be a separate seconds column; make sure it's two characters long and paste it onto the date
    if (str_length(data$date[1]) < 19){
      data$sec <- as.character(data$sec)
      sec_length <- str_length(data$sec)
      data$sec[sec_length <2] <- paste0("0", data$sec[sec_length <2])
      data$date <- paste0(data$date, ":", data$sec) #then paste it to end of date
    }
    data$datetime <- as.POSIXct(data$date, tryFormats = c("%Y/%m/%d %H:%M:%S", "%d/%m/%Y %H:%M:%S"), tz = "GMT")
  } else if ("date" %in% col_names & "time" %in% col_names){
    #if date and time are in column names, add seconds and paste them together
    data$time <- paste0(data$time, ":00")
    data$datetime <- paste(data$date, data$time, sep = " ")
    data$datetime <- as.POSIXct(data$datetime, format = "%d/%m/%Y %H:%M:%S", tz = "GMT")
  } else if ("ime" %in% col_names){
    #if time is misspelt in column names, convert straight to POSIXct
    data$datetime <- as.POSIXct(data$ime, tryFormats = "%d/%m/%Y %H:%M", tz = "GMT")
  } else if ("Date" %in% col_names & !("POSIXct" %in% col_names)){
    #if Date is present but not POSIXct
    #remove rows with NA times
    data <- data[!is.na(data$Time),]
    #if time is numeric (i.e. no colons), make it a character and find whether it is too short (i.e. missing 0s)
    #for rows where it's too short, paste a sufficient number of 0s to the start
    if(is.numeric(data$Time)){
      data$Time <- as.character(data$Time)
      time_length <- str_length(data$Time)
      for(k in 1:nrow(data)){
        if(time_length[k] < 6){
          data$Time[k] <- paste0(paste(rep("0",6-time_length[k]),collapse=""), data$Time[k])
        }
      }
      #paste date and time together
      data$datetime <- paste0(data$Date, " ", data$Time)
      data$datetime <- as.POSIXct(data$datetime, tryFormats = c("%m/%d/%Y %H%M%S"), tz = "GMT")
    }else{
      #otherwise, check whether date contains characters
      data$Time <- as.character(data$Time)
      if(grepl("Z", data$Time[1])){
        #if it does
        #remove characters from datetime
        data$datetime <- as.character(unlist(strsplit(data$Time, "Z")))
        date_time <- as.character(unlist(strsplit(data$datetime, "T")))
        #paste components of datetime back together and make POSIXct object
        data$datetime <- paste(date_time[seq(1,(length(date_time)-1), 2)], date_time[seq(2, length(date_time), 2)], sep = " ")
        data$datetime <- as.POSIXct(data$datetime, format = "%Y-%m-%d %H:%M:%S", tz = "GMT")
      }else{
        #otherwise, remove whitespace and shorten time string to 8 characters
        data$Time <- trimws(data$Time, which = "both")
        data$Time <- str_trunc(data$Time, 8, "right", ellipsis="")
        #then paste date and time together
        data$datetime <- paste0(data$Date, " ", data$Time)#paste to date, with space between
        data$datetime <- as.POSIXct(data$datetime, tryFormats = c("%Y/%m/%d %H:%M:%S", "%d/%m/%Y %H:%M:%S", "%m/%d/%Y %H:%M:%S"), tz = "GMT")
      }
    }
    #if date.yymmdd is in colnames, convert date and time to characters
  } else if ("date.yymmdd" %in% col_names){
    data$date.yymmdd <- as.character(data$date.yymmdd)
    data$time.hhmmss <- as.character(data$time.hhmmss)
    #check how long strings are
    date_length <- str_length(data$date.yymmdd)
    time_length <- str_length(data$time.hhmmss)
    #for date strings that are too short (i.e. actually ymmdd), paste 0 to the start
    data$date.yymmdd[date_length == 5] <- paste0("0", data$date.yymmdd)
    #for time strings that are too short, add a sufficient number of zeroes to the start
    for(k in 1:nrow(data)){
      if(time_length[k] < 6){
        data$time.hhmmss[k] <- paste0(paste(rep("0",6-time_length[k]),collapse=""), data$time.hhmmss[k])
      }
    }
    #paste date and time together
    data$datetime <- paste0(data$date.yymmdd, " ", data$time.hhmmss)
    data$datetime <- as.POSIXct(data$datetime, tryFormats = c("%y%m%d %H%M%S"), tz = "GMT")
  } else if ("year" %in% col_names & !("Date" %in% col_names)){
    #if year is in colnames but not Date, paste all the columns together to get datetime
    #this will depend on what the column names are:
    if("hours" %in% col_names){
      data$datetime <- paste0(data$year,"/", data$month, "/", data$day, " ", data$hours, ":", data$minutes, ":", data$seconds)
      data$datetime <- as.POSIXct(data$datetime, tryFormats = c("%Y/%m/%d %H:%M:%S"), tz = "GMT")
    }else{
      data$datetime <- paste0(data$year,"/", data$month, "/", data$day, " ", data$hour, ":", data$min, ":", data$second)
      data$datetime <- as.POSIXct(data$datetime, tryFormats = c("%y/%m/%d %H:%M:%S"), tz = "GMT")
    }
  } else if ("UTCDate" %in% col_names){
    #if UTCDate in colnames, paste with UTCTime
    paste0(data$UTCDate, " ", data$UTCTime) %>%
      as.POSIXct(., tryFormats = c("%Y-%m-%d %H:%M:%S", "%d-%m-%Y %H:%M:%S", "%d/%m/%Y %H:%M:%S"), tz = "GMT") -> data$datetime
  } else if("Time" %in% col_names & "new_time" %in% col_names){
    if(!is.na(data$Time[1]) & str_length(data$Time[1]) > 10){
      #if there's a time column with strongs long enough to be datetime
      data$Time <- as.character(data$Time)
      #remove characters from datetime
      data$datetime <- as.character(unlist(strsplit(data$Time, "Z")))
      date_time <- as.character(unlist(strsplit(data$datetime, "T")))
      #paste components of datetime back together and make POSIXct object
      data$datetime <- paste(date_time[seq(1,(length(date_time)-1), 2)], date_time[seq(2, length(date_time), 2)], sep = " ")
      data$datetime <- as.POSIXct(data$datetime, format = "%Y-%m-%d %H:%M:%S", tz = "GMT")
    } else if ("DateTime" %in% col_names & !is.na(data$DateTime[1])){
      #remove characters from DateTime
      data$datetime <- as.character(data$DateTime)
      if(grepl("Z", data$DateTime[1])){
        data$datetime <- as.character(unlist(strsplit(as.character(data$DateTime), "Z")))
        date_time <- as.character(unlist(strsplit(data$datetime, "T")))
        #paste components of datetime back together and make POSIXct object
        data$datetime <- paste(date_time[seq(1,(length(date_time)-1), 2)], date_time[seq(2, length(date_time), 2)], sep = " ")
        data$datetime <- as.POSIXct(data$datetime, format = "%Y-%m-%d %H:%M:%S", tz = "GMT")
      } else {
        data$datetime <- as.POSIXct(data$DateTime, format = "%d/%m/%Y %H:%M:%S", tz = "GMT")
      }
    } else if ("POSIXct" %in% col_names){
      if(str_length(as.character(data$POSIXct[1])) == 19){
        #if POSIXct in colnames, convert straight to POSIXct
        data$datetime <- as.POSIXct(data$POSIXct, tryFormats = c("%Y-%m-%d %H:%M:%S", "%d/%m/%Y %H:%M:%S"), tz = "GMT")
      } else if ("Date" %in% col_names & "Time" %in% col_names){
        data$datetime <- paste(data$Date, data$Time, sep = " ")
        data$datetime <- as.POSIXct(data$datetime, format = "%d/%m/%Y %H:%M:%S", tz = "GMT")
      }
    }
  } else if ("Time" %in% col_names & "Date" %in% col_names == F){
    data$Time <- as.character(data$Time)
    date_time <- as.character(unlist(strsplit(data$Time, "Z")))
    #paste components of datetime back together and make POSIXct object
    data$datetime <- paste(date_time[seq(1,(length(date_time)-1), 2)], date_time[seq(2, length(date_time), 2)], sep = " ")
    data$datetime <- as.POSIXct(data$datetime, format = "%Y-%m-%d %H:%M:%S", tz = "GMT")
  } else if ("POSIXct" %in% col_names){
    #if POSIXct in colnames, convert straight to POSIXct
    data$datetime <- as.POSIXct(data$POSIXct, tryFormats = c("%Y-%m-%d %H:%M:%S", "%d/%m/%Y %H:%M:%S"), tz = "GMT")
  } else if ("comma_datetime" %in% col_names){
    #if comma_datetime in colnames (colnames in these files started as VX)
    data$comma_datetime <- as.character(data$comma_datetime)
    #split the datetime by the comma and paste back together
    a <- sapply(strsplit(data$comma_datetime, ","), function(x){x[1]})
    b <- sapply(strsplit(data$comma_datetime, ","), function(x){x[2]})
    data$datetime <- paste(a, b, sep = " ")
    data$datetime <- as.POSIXct(data$datetime, format = "%d/%m/%Y %H:%M:%S", tz = "GMT")
  } else if ("UTC_datetime" %in% col_names){
    #if UTC_datetime in colnames, convert straight to POSIXct
    data$datetime <- as.POSIXct(data$UTC_datetime, format = "%Y-%m-%d %H:%M:%S", tz = "GMT")
  }
  
  #remove rows with missing datetime or times outside the tracking study
  data <- data[!is.na(data$datetime) & data$datetime > as.POSIXct("2004-01-01 00:00:00") & data$datetime < Sys.time(),]
  
  #check for cases where month and day have been reversed
  date_range <- (as.numeric(data$datetime[nrow(data)])-as.numeric(data$datetime[1]))/(3600*24)
  #length_na <- length(which(is.na(data$datetime)))
  
  #if this appears to have happened (indicated by track longer than a month or outside of April to August)
  if(date_range > 30 | any(month(data$datetime) < 4 | month(data$datetime) > 8)){
    #try flipping the datetime
    try(new_datetime <- as.POSIXct(as.character(data$datetime), format = "%Y-%d-%m %H:%M:%S", tz = "GMT"))
    #if this shortens the track or means there are no longer dates outside April to August, keep it
    if((as.numeric(new_datetime[max(which(!is.na(new_datetime)))])-as.numeric(new_datetime[min(which(!is.na(new_datetime)))]))/(3600*24) < date_range & !any(month(new_datetime) < 4 | month(new_datetime) > 8)){
      data$datetime <- new_datetime
    }
  }
  
  #if there are still NA datetimes, remove them
  data <- data[!is.na(data$datetime),]
  
  #find duplicate fixes
  remove <- which((duplicated(data$lat) & duplicated(data$lon)) | duplicated(data$datetime))
  #if there are any duplicate fixes, remove them
  if(length(remove) > 0){
    data <- data[-remove,]
  }
  
  
  
  #### finding gaps and splitting track into continuous sections ####
  
  
  #find the time between successive fixes 
  #find the median time difference, which should be the original resolution of the track
  #find gaps that are more than 10 fixes long
  data$time_diff_h <- c(NA, as.numeric(data$datetime[2:nrow(data)])-as.numeric(data$datetime[1:(nrow(data)-1)]))/3600
  original_resolution_secs <- median(data$time_diff_h,na.rm = T)*3600
  gaps <- which(data$time_diff_h[-1] > 10*original_resolution_secs/3600)
  #find the indices where these long gaps occur
  bounds <- c(1, gaps+1, (nrow(data)+1))
  #and split the track across these gaps
  data <- lapply(1:(length(bounds)-1), function(x){data[bounds[x]:(bounds[x+1]-1),]})
  
  #set a counter for the number of sections the tracks get split into in the lower loop
  no_sections <<- 0
  #create an object to record which tracks contain speed errors
  speed_errors <<- FALSE
  time_errors <<- FALSE
  
  
  
  #within split track, continue processing
  data <- lapply(data, function(sub_data){
    
    #if there are enough fixes to calculate at least one speed
    if(nrow(sub_data) >= 2){
      #find the median year and keep only fixes in the same year
      median_year <- median(year(sub_data$datetime))
      sub_data <- sub_data[year(sub_data$datetime) == median_year | is.na(sub_data$datetime),]
      
      
      #### filtering and re-checking gaps ####
      
      #for snapperGPS data, exclude points with no confidence
      if("confidence" %in% col_names){
        sub_data$confidence <- as.numeric(sub_data$confidence)
        sub_data <- sub_data[!is.na(sub_data$confidence) & !is.infinite(sub_data$confidence),]
      }
      
      #if there's no data left, return nothing
      if(nrow(sub_data) <= 2){return(NULL)}
      
      #find time difference between consecutive points in hours
      sub_data$time_diff_h <- c(NA, as.numeric(sub_data$datetime[2:nrow(sub_data)])-as.numeric(sub_data$datetime[1:(nrow(sub_data)-1)]))/3600
      
      #iteratively remove points with duplicate times and that move back in time
      a <- 0
      while(any(na.omit(sub_data$time_diff_h <= 0))){
        #first, check if the first issue is the problem
        #if it is, remove and recalculate
        if(sub_data$time_diff_h[2] <= 0){
          sub_data <- sub_data[-1,]
          #sub_data$distance_from_last_point_km <- c(NA, distHaversine(sub_data[1:(nrow(sub_data)-1),c("lon","lat")], sub_data[2:nrow(sub_data),c("lon","lat")]))/1000
          sub_data$time_diff_h <- c(NA, as.numeric(sub_data$datetime[2:nrow(sub_data)])-as.numeric(sub_data$datetime[1:(nrow(sub_data)-1)]))/3600
        }
        #then remove any remaining rows with time differences <= 0
        sub_data <- rbind(sub_data[1,],sub_data[which(sub_data$time_diff_h > 0),])
        
        #if there's no data left, record the issue, return NULL and break the while loop
        if(nrow(sub_data) <= 2){
          time_errors <<- TRUE
          return(NULL)
          break
        }
        #recalculate
        sub_data$time_diff_h <- c(NA, as.numeric(sub_data$datetime[2:nrow(sub_data)])-as.numeric(sub_data$datetime[1:(nrow(sub_data)-1)]))/3600
        
        #add one to the counter
        a <- a+1
        
        #if the counter goes above 20, record the issue, return NULL and break the while loop
        if(a > 20){
          time_errors <<- TRUE
          return(NULL)
          break
        }
      }
      
      
      #calculate speed in kmph
      sub_data$distance_from_last_point_km <- c(NA, distHaversine(sub_data[1:(nrow(sub_data)-1),c("lon","lat")], sub_data[2:nrow(sub_data),c("lon","lat")]))/1000
      sub_data$speed_kmph <- sub_data$distance_from_last_point_km/sub_data$time_diff_h
      
      
      #filter based on speed
      #desired speed filter in kmph
      threshold <- 80
      
      #create a counter and then filter based on speed, recalculating each time
      a <- 0
      
      
      while(any(na.omit(sub_data$speed_kmph[-1]) > threshold)){
        #get continuous sections above and below speed threshold
        filtered_sections <- rle(sub_data$speed_kmph[-1] > threshold)
        #split into the values (logical)
        filter <- filtered_sections$values
        #and lengths of each each section
        filter_positions <- filtered_sections$lengths
        #get the index for the last value of each section by cumulatively summing the lengths
        filter_first_positions <- cumsum(filter_positions)+1
        #get just the first index of each section faster than the threshold by adding one to the last indices of each section below the threshold
        filter_first_positions <- filter_first_positions[which(filter == FALSE)]+1
        #if the first speed value (associated with the second fix) is over threshold this is most likely because the first fix is erroneous
        #so add 1 to the filter_first_positions
        if(filter[1]){
          filter_first_positions <- c(1, filter_first_positions)
        }
        #remove these indices from the current track
        sub_data <- sub_data[-filter_first_positions,]
        #if there are no data left, record the issue, return NULL and break the loop
        if(nrow(sub_data) <= 2){
          speed_errors <<- TRUE
          return(NULL)
          break
        }
        #recalculate distance, time elapsed and speed
        #if any speeds are still above threshold, the loop will run again
        sub_data$distance_from_last_point_km <- c(NA, distHaversine(sub_data[1:(nrow(sub_data)-1),c("lon","lat")], sub_data[2:nrow(sub_data),c("lon","lat")])/1000)
        sub_data$time_diff_h <- c(NA, (as.numeric(sub_data$datetime[2:nrow(sub_data)])-as.numeric(sub_data$datetime[1:(nrow(sub_data)-1)]))/3600)
        sub_data$speed_kmph <- sub_data$distance_from_last_point_km/sub_data$time_diff_h
        #add one to the loop counter
        a <- a+1
        #if it's looping too many times, record the issue and break the loop
        if(a > 20){
          speed_errors <<- TRUE
          break
        }
      }
      
      
      #check for gaps again, after speed filtering
      gaps <- which(sub_data$time_diff_h[-1] > 10*original_resolution_secs)
      #find the indices where these long gaps occur
      bounds <- c(1, gaps, (nrow(sub_data)+1))
      #and split the track across these gaps
      sub_data <- lapply(1:(length(bounds)-1), function(x){sub_data[bounds[x]:(bounds[x+1]-1),]})
      
      
      #loop through each continuous section
      sub_data <- lapply(sub_data, function(sub_sub_data){
        
        #### interpolation and re-filtering ####
        #if there are enough fixes for interpolation (excluding ones where the bird hasn't moved)
        if(nrow(sub_sub_data) >= 4 & length(which(sub_sub_data$speed_kmph > 0)) >= 3){
          #resample GPS to exact intervals fixes by
          #finding absolute dif in longitude and latitude between consecutive points
          sub_sub_data$x1 <-  c(abs(sub_sub_data$lon[1:(nrow(sub_sub_data)-1)]-sub_sub_data$lon[2:(nrow(sub_sub_data))]),1)
          sub_sub_data$x2 <-  c(abs(sub_sub_data$lat[1:(nrow(sub_sub_data)-1)]-sub_sub_data$lat[2:(nrow(sub_sub_data))]),1)
          #and the time dif, in seconds, between consecutive fixes (N.B. this is t1 - t2 so should be negative), including NA for the final row
          sub_sub_data$x3 <- c(((-3600)*sub_sub_data$time_diff_h[-1]),NA)
          #remove points that haven't moved in lon and lat, and those with NA time differences
          sub_sub_data <- sub_sub_data[(sub_sub_data$x1 != 0 | sub_sub_data$x2 != 0) & sub_sub_data$x3 < 0 & !is.na(sub_sub_data$x3),]
          #order fixes chronologically
          sub_sub_data <-sub_sub_data[order(sub_sub_data$datetime),]
          #convert datetime to numeric value of seconds since 1st Jan 1970
          sub_sub_data$datetime <- as.numeric(sub_sub_data$datetime)
          #get number of rows
          nrt <- nrow(sub_sub_data)
          #create a sequence from first to last datetime at 5 minute (300 second) intervals
          idt <- seq(from=sub_sub_data$datetime[1], to=sub_sub_data$datetime[nrt], by=desired_interval_secs)
          #interpolate lon and lat to this interval via datetime
          #(this interpolation is 'shape-preserving'; it uses a polynomial approach to determine slopes such that function values do not overshoot sub_sub_data values)
          ix = pchip(sub_sub_data$datetime, sub_sub_data$lon, idt) 
          iy = pchip(sub_sub_data$datetime, sub_sub_data$lat, idt)
          #convert datetime back to POSIXct
          Datetime <- as.POSIXct(idt, origin = '1970-01-01', tz = "GMT") #return to date format
          
          #generate new sub_sub_dataframe retaining only the desired columns
          sub_sub_data<- data.frame(filename = file,
                                    original_resolution_secs = original_resolution_secs,
                                    interpolated_resolution_secs = desired_interval_secs,
                                    track_id = which(names == file),
                                    colony = sub_sub_data$colony[1],
                                    colony_lon = sub_sub_data$colony_lon[1],
                                    colony_lat = sub_sub_data$colony_lat[1],
                                    campaign = campaign,
                                    burrow = burrow,
                                    ring = ring,
                                    gps = gps,
                                    gls = gls,
                                    datetime = Datetime,
                                    lon = ix,
                                    lat = iy)
          
          
          #if this dataframe still contains more than one fix
          if(nrow(sub_sub_data) > 1){
            #### recalculate speeds and filter again ####
            #recalculate distance and speed
            sub_sub_data$distance_from_last_point_km <- c(NA, distHaversine(sub_sub_data[1:(nrow(sub_sub_data)-1),c("lon","lat")], sub_sub_data[2:nrow(sub_sub_data),c("lon","lat")]))/1000
            sub_sub_data$time_diff_h <- c(NA, as.numeric(sub_sub_data$datetime[2:nrow(sub_sub_data)])-as.numeric(sub_sub_data$datetime[1:(nrow(sub_sub_data)-1)]))/3600
            sub_sub_data$speed_kmph <- sub_sub_data$distance_from_last_point_km/sub_sub_data$time_diff_h
            
            
            #filter again
            a <- 0
            while(any(na.omit(sub_sub_data$speed_kmph[-1]) > threshold)){
              #get continuous sections above and below speed threshold
              filtered_sections <- rle(sub_sub_data$speed_kmph[-1] > threshold)
              #split into the values (logical)
              filter <- filtered_sections$values
              #and lengths of each each section
              filter_positions <- filtered_sections$lengths
              #get the index for the last value of each section by cumulatively summing the lengths
              filter_first_positions <- cumsum(filter_positions)+1
              #get just the first index of each section faster than the threshold by adding one to the last indices of each section below the threshold
              filter_first_positions <- filter_first_positions[which(filter == FALSE)]+1
              #if the first speed value (associated with the second fix) is over threshold this is most likely because the first fix is erroneous
              #so add 1 to the filter_first_positions
              if(filter[1]){
                filter_first_positions <- c(1, filter_first_positions)
              }
              #remove these indices from the current track
              sub_sub_data <- sub_sub_data[-filter_first_positions,]
              if(nrow(sub_sub_data) <= 2){
                return(NULL)
                break
              }
              #recalculate distance, time elapsed and speed
              #if any speeds are still above threshold, the loop will run again
              sub_sub_data$distance_from_last_point_km <- c(NA, distHaversine(sub_sub_data[1:(nrow(sub_sub_data)-1),c("lon","lat")], sub_sub_data[2:nrow(sub_sub_data),c("lon","lat")])/1000)
              sub_sub_data$time_diff_h <- c(NA, (as.numeric(sub_sub_data$datetime[2:nrow(sub_sub_data)])-as.numeric(sub_sub_data$datetime[1:(nrow(sub_sub_data)-1)]))/3600)
              sub_sub_data$speed_kmph <- sub_sub_data$distance_from_last_point_km/sub_sub_data$time_diff_h
              #add one to the loop counter
              a <- a+1
              #if it's looping too many times, record the issue and break the loop
              if(a > 20){
                speed_errors <<- TRUE
                break
              }
            }
            
            #### adding navigational and clock variables ####
            
            #calculate instantaneous bearing from one fix to the next
            sub_sub_data$instantaneous_gc_bearing <- c(bearing(sub_sub_data[1:(nrow(sub_sub_data)-1), c("lon","lat")], sub_sub_data[2:nrow(sub_sub_data), c("lon","lat")]), NA)
            
            #from each point to home, using great circle
            sub_sub_data$gc_bearing_to_home <- bearing(sub_sub_data[,c("lon","lat")], sub_sub_data[,c("colony_lon","colony_lat")])
            #find the difference between the instantaneous great circle bearing and the great circle bearing to home
            #again correcting the angle
            sub_sub_data$instantaneous_deflection <- sub_sub_data$instantaneous_gc_bearing-sub_sub_data$gc_bearing_to_home
            sub_sub_data$instantaneous_deflection <- ifelse(sub_sub_data$instantaneous_deflection < -180, 360+sub_sub_data$instantaneous_deflection, sub_sub_data$instantaneous_deflection)
            sub_sub_data$instantaneous_deflection <- ifelse(sub_sub_data$instantaneous_deflection > 180, sub_sub_data$instantaneous_deflection-360, sub_sub_data$instantaneous_deflection)
            
            #make an sf object from the fix coordinates
            coords <- st_as_sf(sub_sub_data[,c("lon","lat")], coords = c("lon", "lat"), crs = "+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0")
            #find whether each fix intersects any features of buffer_bi
            coastal <- lengths(st_intersects(coords, buffer_bi))
            
            #get the steradians value under each fix from the raster
            in_sight <- extract(r5, coords)
            #those with 0 steradians or an NA value are out of sight of land (UK & Ireland)
            sub_sub_data$in_sight <- ifelse(in_sight > 0, TRUE, FALSE)
            #identify fixes which do or do not intersect with any features of the 30km buffered BI
            sub_sub_data$coastal <- ifelse(coastal > 0, TRUE, FALSE)
            #use the in_land to make sure that any identified as being out of sight of land are not within 30km of the coast
            sub_sub_data$in_sight <- ifelse(sub_sub_data$coastal == FALSE, sub_sub_data$in_sight, TRUE)
            #and any fixes outside the raster must be out of sight of land
            sub_sub_data$in_sight[which(is.na(sub_sub_data$in_sight))] <- FALSE
            
            #if any of the data is within 30km of the coast (and doesn't have NA bearing values)
            if(any(sub_sub_data$coastal & !is.na(sub_sub_data$instantaneous_gc_bearing))){
              #get the indices of the fixes which meet these criteria
              indices <- which(sub_sub_data$coastal & !is.na(sub_sub_data$instantaneous_gc_bearing))
              
              #get the bearing 90 degrees anticlockwise of instantaneous bearing
              anticlock <- sub_sub_data$instantaneous_gc_bearing[indices]-90
              anticlock <- ifelse(anticlock < -180, 360+anticlock, anticlock)
              anticlock <- ifelse(anticlock > 180, anticlock-360, anticlock)
              
              #get the bearing 90 degrees clockwise of instantaneous bearing
              clock <- sub_sub_data$instantaneous_gc_bearing[indices]+90
              clock <- ifelse(clock < -180, 360+clock, clock)
              clock <- ifelse(clock > 180, clock-360, clock)
              
              #get the coordinates of these fixes
              coords <- sub_sub_data[indices,c("lon","lat")]
              
              #create points along the perpendicular bearings from each fix
              #up to 30km away, every 100m
              anticlock_dest <- lapply(1:length(indices), function(x){destPoint(coords[x,c("lon","lat")], anticlock[x], seq(100, 30000, 100))})
              clock_dest <- lapply(1:length(indices), function(x){destPoint(coords[x,c("lon","lat")], clock[x], seq(100, 30000, 100))})
              
              #create empty columns to be filled with distance to land data
              sub_sub_data$perpendicular_distance_to_land <- NA
              sub_sub_data$perpendicular_land_anticlock <- NA
              
              #for every fix, find whether any of the clockwise or anticlockwise fixes are over land
              #if they are, set land clockwise or anticlockwise as TRUE
              #and get the distance to this land
              #if there's land both clockwise and anticlockwise, return NA
              land_anticlock_dist <- lapply(1:length(indices), function(x){on_land_anticlock <- is.na(raster::extract(r5,anticlock_dest[[x]]));on_land_clock <- is.na(raster::extract(r5,clock_dest[[x]]));if(any(on_land_anticlock) & !any(on_land_clock)){return(data.frame(TRUE, min(which(on_land_anticlock))*100))}else{if(any(on_land_clock) & !any(on_land_anticlock)){return(data.frame(FALSE, min(which(on_land_clock))*100))}else{return(data.frame(NA, NA))}}})
              
              #apply the distance to land data to the data
              sub_sub_data[indices,c("perpendicular_land_anticlock","perpendicular_distance_to_land")] <- rbindlist(land_anticlock_dist,use.names = F)
              
            }else{
              #if there wasn't any data within 30km of the coast and non-NA bearings
              #fill the columns with NA
              sub_sub_data$perpendicular_distance_to_land <- NA
              sub_sub_data$perpendicular_land_anticlock <- NA
            }
            
            #get the julian day of each fix
            sub_sub_data$jday <- yday(sub_sub_data$datetime)
            #create a date column that's the same as Datetime
            sub_sub_data$date <- sub_sub_data$datetime
            #find the sun's azimuth at each fix location and datetime, using the lon, lat and date columns and convert to degrees
            sub_sub_data$sun_azimuth <- getSunlightPosition(data = sub_sub_data[,c("lon","lat","date")], keep = "azimuth")[,4]*180/pi
            #the function above has south as 0 degrees and north as 180/-180 so convert to 0/360 at north
            sub_sub_data$sun_azimuth <- 360-(180-sub_sub_data$sun_azimuth)
            #now make the date column just the date, without time
            sub_sub_data$date <- as.Date(sub_sub_data$datetime)
            #and use it to find the sunrise time at each fix location
            sub_sub_data$sunrise_time <- getSunlightTimes(data = sub_sub_data[,c("lon","lat","date")], keep = "sunrise")[,4]
            #and the sunset time
            sub_sub_data$sunset_time <- getSunlightTimes(data = sub_sub_data[,c("lon","lat","date")], keep = "sunset")[,4]
            #identify whether a fix falls between sunrise and sunset at its location
            sub_sub_data$diurnal <- as.numeric(sub_sub_data$datetime) < as.numeric(sub_sub_data$sunset_time) & as.numeric(sub_sub_data$datetime) > as.numeric(sub_sub_data$sunrise_time)
            
            #### calculating rolling speeds ####
            #calculate mean speed over a rolling window, determined by the desired time interval and interpolated resolution
            
            #this should be set to whatever your interpolated resolution is
            standardised_resolution_mins <- 5
            
            #this must always be at least double the resolution, otherwise just use the raw speed
            desired_interval_mins <- 15
            
            #convert the desired interval to a number of fixes
            desired_interval_fixes <- desired_interval_mins/standardised_resolution_mins
            
            #create an empty column for rolling speed
            sub_sub_data$rolling_mean_speed_kmph <- NA
            
            #if there are enough fixes to fill at least one interval
            if(nrow(sub_sub_data) > desired_interval_fixes){
              
              #get list of all indices in track
              indices_list <- as.list(1:nrow(sub_sub_data))
              #apply this window to each index
              indices_list <- lapply(indices_list, function(x){ceiling(x-(desired_interval_fixes/2)):ceiling(x+(desired_interval_fixes/2))})
              #remove indices outside the bounds of the sub_sub_dataframe
              indices_list <- lapply(indices_list, function(x){x[x > 0 & x <= nrow(sub_sub_data)]})
              
              #calculate the mean speed over this window
              sub_sub_data$rolling_mean_speed_kmph <- sapply(indices_list, function(x){mean(sub_sub_data$speed_kmph[x], na.rm = T)})
              
            }
          }else{
            #if there was only one row left, remove this section
            sub_sub_data <- NULL
          }
        }else{
          #if there was too little data left to interpolate, remove this section
          sub_sub_data <- NULL
        }
        return(sub_sub_data)
      })
      #get the number of sections created when splitting over gaps
      no_sections <<- no_sections+length(sub_data)
      #bind the sub_sub_dataframes together
      sub_data <- do.call("rbind",sub_data)
    }else{
      sub_data <- NULL
    }
    return(sub_data)
  })
  #### returning data and metadata, including splitting trips ####
  #bind the sub_dataframes together
  data <- do.call("rbind",data)
  #if what's left of the track is less than half an hour, discard
  if(is.null(data)){return(NULL)}
  if(nrow(data) < 60*30/desired_interval_secs){return(NULL)}
  #get instantaneous bearing here so that it runs across gaps and can be used in OJI analysis
  data$oji_instantaneous_bearing <- c(bearing(data[1:(nrow(data)-1), c("lon","lat")], data[2:nrow(data), c("lon","lat")]), NA)
  #recalculate distance from last point here so that it runs across gaps and can be used in OJI analysis
  data$distance_from_last_point_km <- c(NA, distHaversine(data[1:(nrow(data)-1),c("lon","lat")], data[2:nrow(data),c("lon","lat")])/1000)
  
  #get sections where bird is continuously more than 3km from home
  data$distance_from_home_km <- distHaversine(data[,c("lon","lat")], data[,c("colony_lon","colony_lat")])/1000
  #whilst calculating distance from home, also include if home is visible
  data$home_visible_distance <- colony_coords$max_visibility_km[match(data$colony[1], colony_coords$colony)]
  data$home_visible <- ifelse(data$distance_from_home_km < data$home_visible_distance, TRUE, FALSE)
  #now identify when bird is more than 3km from home
  data$out <- ifelse(data$distance_from_home_km < 3, FALSE, TRUE)
  #get periods when the bird is continuously away from the colony
  sections <- rle(data$out)
  values <- sections$values
  lengths <- sections$lengths
  #short returns to colony are fine but we want to filter out very short trips (less than two hours, or 24 fixes)
  values[values & lengths < 24] <- FALSE
  #replace the out variable with the corrected version
  data$out <- rep(values, lengths)
  
  #get continuous sections of corrected 'out'
  trip_id <- rle(data$out)
  lengths <- trip_id$lengths
  #create trip id for each section of continuous out (or not out)
  data$trip_id <- rep(1:length(lengths),lengths)
  
  #combine with the track ID to make a track/trip ID
  data$track_trip_id <- paste(data$track_id, data$trip_id)   
  #create a list of distinct trips (and periods at the colony)
  track_trip_list <- lapply(1:length(lengths), function(this_trip){this_data <- data[data$trip_id == this_trip,]; if(any(!this_data$out)){this_data$trip_id <- NA}; return(this_data)})
  
  #assign metadata to the all_metadata list
  all_metadata[[which(names == file)]] <<- data.frame(colony, ring, burrow, gps, gls, campaign, year, month, original_resolution_secs, time_errors, speed_errors, no_sections)
  
  #return the list of trips
  return(track_trip_list)
  
})

#remove any entries in the gps list with no data left
gps_list <- gps_list[which(sapply(gps_list, length) > 0)]

#bind the all metadata list into a dataframe
all_metadata <- rbindlist(all_metadata)

#save the gps data and metadata
save(gps_list, file = "")
save(all_metadata, file = "")

#### homing ID, start from here if initial processing complete ####
load("")
load("")

#visualise the rolling speeds of shearwaters whilst away from the colony
#it's clearer if you exclude tracks with higher original fix intervals
rolling_speeds <- unlist(lapply(gps_list, function(tracks){unlist(lapply(tracks, function(data){data$rolling_mean_speed_kmph[data$out]}))}))
hist(log(na.omit(rolling_speeds)))

hist(log(rolling_speeds[rolling_speeds > exp(-3)]))
#create a gaussian mixture model on the log rolling mean speed to separate periods of continuous flight from mixed behaviour or resting
#subset it to exclude the really low outlier speeds, otherwise the mixture model doesn't work
mix <- normalmixEM(log(na.omit(rolling_speeds[rolling_speeds > exp(-3)])))
#check the model by plotting it that you get two separate peaks
plot(mix,2)
#find the threshold where the posterior probabilities cross 0.5
threshold <- log(na.omit(rolling_speeds[rolling_speeds > exp(-3)]))[which.min(abs(mix$posterior[,1]-mix$posterior[,2]))]
#exponentiated threshold should be roughly 16.05
exp(threshold)

#use the threshold from the mixture model to assign fast travel to periods of continuous flight
gps_list <- lapply(gps_list, function(track){lapply(track, function(trip){trip$fast_travel <- ifelse(trip$rolling_mean_speed_kmph > exp(threshold), TRUE, FALSE); return(trip)})})


#identify continuous sections of fast travel
#for each trip
gps_list <- lapply(gps_list, function(track){lapply(track, function(data){
  #if there are data
  if(nrow(data)){
    #and if the data include a trip
    if(any(data$out)){
      #homing is TRUE when the bird is travelling fast
      homing <- data$fast_travel
      #any NA values are not homing
      homing[is.na(homing)] <- FALSE
      
      #get continuous sections of homing
      sections <- rle(homing)
      values <- sections$values
      lengths <- sections$lengths
      
      #if a section of non-homing is shorter than 60 mins make it part of surrounding homing
      #if a section of homing is shorter than 15 minutes, make it part of surrounding non-homing
      while(any(lengths[which(values)] < 3) | any(lengths[which(values == FALSE)] < 12)){
        #find which sections are below threshold
        below <- which((lengths < 3 & values) | (lengths < 12 & !values))
        #get indices for section before or after
        neighbours <- lapply(below, function(index){c(index-1, index+1)})
        #unless it's the last or first section
        #in which case, just use the penultimate or second section, respectively
        if(below[length(below)] == length(lengths)){neighbours[[length(neighbours)]] <- length(lengths)-1}
        if(below[1] == 1){neighbours[[1]] <- 2}
        #if sections neighbouring those which are below threshold are themselves above threshold
        #reassign the value of those which are below threshold
        new_values <- sapply(1:length(neighbours), function(index){if(any(lengths[neighbours[[index]]] >= 12) & !values[neighbours[[index]][1]]){FALSE}else{if(any(lengths[neighbours[[index]]] >= 3) & values[neighbours[[index]][1]]){TRUE}else{values[index]}}})
        #and add to the values vector
        values[below] <- new_values
        
        #generate the newly corrected sections to start the while loop again if necessary
        sections <- rle(rep(values, lengths))
        lengths <- sections$lengths
        values <- sections$values
      }
      
      #once all the sections have been corrected, reassign corrected values to the dataframe
      data$homing <- rep(values, lengths)
      #create homing ID
      data$homing_id <- rep(1:length(lengths),lengths)
      data$track_trip_homing_id <- paste(data$track_trip_id, data$homing_id)
      #split trip into homing (and non-homing sections)
      trip_homing_list <- lapply(1:length(lengths), function(id){this_data <- data[data$homing_id == id,]; if(!values[id]){this_data$homing_id <- NA}; return(this_data)})
      
      return(trip_homing_list)
    }else{
      #if this trip ID is just fixes at the colony, return NAs
      data$homing <- NA
      data$homing_id <- NA
      data$track_trip_homing_id <- paste(data$track_trip_id, data$homing_id)
      trip_homing_list <- list(data)
      return(trip_homing_list)
    }
  }else{return(NULL)}
})
})


#next step is to identify those sections which are actually going towards home

#for each section calculate the overall bearing from start to end, relative to the bearing to home from the start
#and the proportional reduction in distance to home from start to end

homing_distribution <- lapply(gps_list, function(track){rbindlist(lapply(track, function(trip){rbindlist(lapply(trip, function(data){
  #if the section contains homing
  if(!any(is.na(data$homing)) & any(data$homing)){
    #get the start location of the section
    start <- data[1,c("lon","lat")]
    #bearing to the end
    bearing <- bearing(start, data[nrow(data),c("lon","lat")])
    #and bearing from the start to home
    homeward <- bearing(start, data[1,c("colony_lon","colony_lat")])
    
    #calculate the difference in degrees (i.e. deflection from homeward direction)
    deflection <- bearing-homeward
    deflection <- ifelse(deflection > 180, deflection-360, deflection)
    deflection <- ifelse(deflection < -180, 360+deflection, deflection)
    
    #get the absolute deflection
    abs_deflection <- abs(deflection)
    
    #record the distance from home at the start of the bout
    start_distance_from_home <- data$distance_from_home_km[1]
    
    #and calculate what proportion of the distance to home at the start of the section
    #the bird has moved by the end
    proportional_movement_to_home <- (start_distance_from_home-data$distance_from_home_km[nrow(data)])/start_distance_from_home
    
    
    
    return(data.frame(abs_deflection, proportional_movement_to_home, start_distance_from_home))
  }else{return(data.frame(NA, NA, NA))}
}), use.names = F, fill = T)}), use.names = F, fill = T)})

#bind into a dataframe
homing_distribution <- rbindlist(homing_distribution)
#set the column names
colnames(homing_distribution) <- c("abs_deflection","proportional_movement_to_home","maximum_distance_from_home")

save(homing_distribution, file = "")

#visualise the distribution of (natural log) absolute deflections
hist(log(homing_distribution$abs_deflection), breaks = seq(-8, 6,0.5))
#use mixture model to identify sections oriented towards home
mix <- normalmixEM(log(na.omit(homing_distribution$abs_deflection)))
plot(mix,2)
#find the threshold where the  posterior probabilities cross 0.5
threshold1 <- log(na.omit(homing_distribution$abs_deflection))[which.min(abs(mix$posterior[,1]-mix$posterior[,2]))]
#exponeniated value should be roughly 72.90
exp(threshold1)

#use a mixture model to remove fixes within homing sections which are not flying from fix to fix (but they still remain a part of a continuous homing section)
speeds <- lapply(gps_list, function(track){lapply(track, function(trip){lapply(trip, function(section){if(any(section$out & section$homing)){return(section$speed_kmph[section$out & section$homing])}else{NULL}})})})
speeds <- unlist(speeds, recursive = T)
#visualise (natural log) speed
hist(log(speeds))
mix <- normalmixEM(log(na.omit(speeds)))
plot(mix,2)
#find the threshold where the  posterior probabilities cross 0.5
threshold2 <- log(na.omit(speeds))[which.min(abs(mix$posterior[,1]-mix$posterior[,2]))]
#threshold should be roughly 16.08
exp(threshold2)

#create counter
a <- 0
#for each section, unless the section starts at least 50km from home,
#has a bearing towards home and the section ends at least 25% closer to home than it started,
#don't count it as homing
gps_list <- lapply(gps_list, function(track){
  lapply(track, function(trip){
    lapply(trip, function(section){
      #add one to the counter
      a <<- a+1
      section$bout_max_dist_from_home_km <- homing_distribution$maximum_distance_from_home[a]
      section$bout_proportional_movement_to_home <- homing_distribution$proportional_movement_to_home[a]
      section$bout_deflection <- homing_distribution$abs_deflection[a]
      #check if this bout meets the criteria
      if(!is.na(homing_distribution$abs_deflection[a]) &
         homing_distribution$abs_deflection[a] < exp(threshold1) &
         homing_distribution$proportional_movement_to_home[a] > 0 &
         homing_distribution$maximum_distance_from_home[a] > 10){
        return(section)
      }else{
        #if it doesn't meet the criteria, record it as not homing
        #and check where it fulfills the criteria of outward flight
        section$homing_id <- NA
        section$homing <- FALSE
        if(!is.na(homing_distribution$abs_deflection[a]) &
           homing_distribution$abs_deflection[a] > exp(threshold1) &
           homing_distribution$proportional_movement_to_home[a] < 0.25){
        }
        return(section)
      }
    })
  })
})


#now check whether each fix in the bout is actually in flight
#if not, it is part of the homing bout but not actually homing itself
gps_list <- lapply(gps_list, function(track){
  lapply(track, function(trip){
    lapply(trip, function(section){
      #apply the threshold to the bout
      section$flying <- ifelse(section$speed_kmph >= exp(threshold2), T, F)
      section$flying[is.na(section$flying)] <- FALSE
      #ensure fixes that don't involve flight aren't recorded as homing
      section$homing[!section$flying] <- FALSE
      if(!any(section$homing)){
        #if none of the bout is flying, remove its homing ID
        section$homing_id <- NA
        return(section)
      }else{
        #otherwise, return it unchanged
        return(section)
      }
    })
  })
})


#save data
save(gps_list, file = "")

#clear environment so you have sufficient memory for the clear beelines
rm(list = ls()[ls() %in% c("gps_list","colony_coords","all_metadata","r5","homing_distribution") == F])


#### clear beeline, start from here if homing already done ####
load("")
load("")

#re-load raster of steradians around UK
#load("")

#re-load colony coords
#colony_coords <- data.frame(colony = c("Copeland","Skomer","Skokholm","Lundy","Rum","Ramsey"),
#                            lon = c(-5.525785, -5.287829, -5.276882, -4.668419, -6.331190, -5.339924),
#                            lat = c(54.695025, 51.737449, 51.697395, 51.176569, 57.005972, 51.866831),
#                            lon_min = c(-5.533334, -5.300001, -5.283334, -4.666667, -6.450001, -5.350001),
#                            lon_max = c(-5.516666, -5.283333, -5.266666, -4.649999, -6.249999, -5.283333),
#                            lat_min = c(54.616666, 51.733333, 51.700000, 51.166666, 56.589999, 51.866666),
#                            lat_max = c(54.683334, 51.750001, 51.716667, 51.200001, 57.066667, 51.900001),
#                            max_elevation_m = c(24, 79, 55, 143, 812, 136),
#                            max_visibility_km = c(sqrt(13*c(24, 79, 55, 143, 812, 136))))



#deterime whether each point has a clear beeline
gps_list <- lapply(gps_list, function(track){
  lapply(track, function(trip){
    lapply(trip, function(data){
      data$clear_beeline <- NA
      
      #don't bother if it's not got homing
      if(any(data$homing)){
        this_colony <- data$colony[1]
        
        #generate lines of 400 points along a great circle from each fix within this section to the colony
        lines <- gcIntermediate(data[,c("lon","lat")],data[,c("colony_lon","colony_lat")], n = 400)
        
        #define an area around the colony which will be removed (because the last point of each line from a fix to home must be at home)
        #so unless points over home are ignored, every fix will be assigned no clear beeline
        colony_xmin <- colony_coords$lon_min[match(this_colony, colony_coords$colony)]
        colony_xmax <- colony_coords$lon_max[match(this_colony, colony_coords$colony)]
        colony_ymin <- colony_coords$lat_min[match(this_colony, colony_coords$colony)]
        colony_ymax <- colony_coords$lat_max[match(this_colony, colony_coords$colony)]
        
        #and for Skomer & Skokholm, remove points that are around St David's Head, otherwise all points to the north are no clear beeline despite tiny obstacle
        colony_xmin2 <- ifelse(this_colony %in% c("sk","skok"), -5.350000, colony_xmin)
        colony_xmax2 <- ifelse(this_colony %in% c("sk","skok"), -5.100000, colony_xmax)
        colony_ymin2 <- ifelse(this_colony %in% c("sk","skok"), 51.866667, colony_ymin)
        colony_ymax2 <- ifelse(this_colony %in% c("sk","skok"), 51.966667, colony_ymax)
        
        
        #if there's only one datapoint, it won't be in list form so sapply fails
        #so make it a list
        if(nrow(data) == 1){lines <- list(lines)}
        #now, excluding points that are at home or St David's Head
        #find whether any points over land (i.e. NA on the r5 raster)
        #if so, there is no clear beeline
        data$clear_beeline <- sapply(lines, function(x){!any(is.na(raster::extract(r5,x[!((colony_xmin < x[,1]) & (x[,1] < colony_xmax) & (colony_ymin < x[,2]) & (x[,2] < colony_ymax)) & !((colony_xmin2 < x[,1]) & (x[,1] < colony_xmax2) & (colony_ymin2 < x[,2]) & (x[,2] < colony_ymax2)),])))})
      }
      return(data)
    })
  })
})

#save data
save(gps_list, file = "")


#### adding magnetic data, start from here if clear beeline done ####
load("")
load("")

#read in data for declination at each fix
magnetic_data <- read.table("", header = T)

#extract numeric decimal declination data from the output of geomag
declination <- as.numeric(unlist(strsplit(as.character(magnetic_data$D_deg), "d"))) - as.numeric(unlist(strsplit(as.character(magnetic_data$D_min), "m")))/60

#using a counter for the number of rows, add the magnetic data to the tracking data
a <- 1
gps_list <- lapply(gps_list, function(track){lapply(track, function(trip){lapply(trip, function(section){section$declination <- declination[a:(a+nrow(section)-1)]; a <<- a+nrow(section);return(section)})})})#section$colony_declination <- colony_declination$declination[match(interaction(year(section$datetime[1]), section$colony[1]), interaction(colony_declination$year, colony_declination$colony))];return(section)})})})

#save data
save(gps_list, file = "")


#### generating daily variables, activity patterns and expected clock-shift, start from here if magnetic data already added ####
load("")
load("")

#for each track
gps_list <- lapply(gps_list, function(track){
  #bind the data into a single dataframe
  track_df <- rbindlist(unlist(track, recursive = F))
  #get all the julian dates covered by that track
  unique_days <- unique(track_df$jday)
  
  #get the starting point for each day, including whether it occurs after local sunrise
  #i.e. we can't be sure where the bird actually started its day (and therefore what jetlag we expect)
  starts <- data.frame(ring = track_df$ring[1],
                       colony = track_df$colony[1],
                       year = year(track_df$datetime[1]),
                       track = track_df$track_id[1],
                       day = unique_days,
                       starts_after_sunrise = ifelse(track_df$datetime[match(unique_days, track_df$jday)] > track_df$sunrise_time[match(unique_days, track_df$jday)], T, F),
                       lon = track_df$lon[track_df$diurnal][match(unique_days, track_df$jday[track_df$diurnal])],
                       lat = track_df$lat[track_df$diurnal][match(unique_days, track_df$jday[track_df$diurnal])],
                       sunrise_time = track_df$sunrise_time[track_df$diurnal][match(unique_days, track_df$jday[track_df$diurnal])])
  
  #get the sunset time as the first local sunset time after the bird has experienced sunset
  starts$sunset_time <- track_df$sunset_time[!track_df$diurnal & track_df$datetime > starts$sunrise_time[match(track_df$jday, starts$day)]][match(unique_days, track_df$jday[!track_df$diurnal & track_df$datetime > starts$sunrise_time[match(track_df$jday, starts$day)]])]
  
  #remove sunrise time and start values if the track started after dawn on a given day
  starts[starts$starts_after_sunrise,c("declination", "lon","lat","sunrise_time")] <- NA
  
  #create an empty vector for the location the bird last sat on the water
  last_sitting_location <- c(NA, NA)
  
  #loop through each bout
  track_list <- lapply(track, function(trip){lapply(trip, function(section){
    
    #get periods of continuous flight
    flying_sections <- rle(section$flying)
    section_values <- flying_sections$values
    section_lengths <- flying_sections$lengths
    #get the cumulative length of each bout to identify the index where each bout ends
    #and use these to get the index of where each bout starts
    section_ends <- cumsum(section_lengths)
    section_starts <- c(1, section_ends[-length(section_ends)]+1)
    
    #for each bout of continuous flight
    coriolis <- lapply(1:length(section_values), function(i){
      #if the bout is not in flight
      if(!section_values[i]){
        #record the end of it as the last sitting position in this section
        last_sitting_location <<- section[section_ends[i],c("lon","lat")]
        return(rep(NA, section_lengths[i]))
      }else{
        #but if it's a bout of flight, find the total latitudinal and longitudinal distance travelled in that bout
        v <- distHaversine(last_sitting_location, cbind(last_sitting_location$lon, section$lat[section_starts[i]:section_ends[i]]))/1000
        u <- distHaversine(last_sitting_location, cbind(section$lon[section_starts[i]:section_ends[i]], last_sitting_location$lat))/1000
        #return the coriolis predictor: sine of the latitude at each fix
        #multiplied by the distance travelled in each component since last sat on the water
        return(sin(section$lat[section_starts[i]:section_ends[i]]*pi/180)*(v+u))
      }
    })
    #get a vector of these coriolis predictors
    section$coriolis_predictor <- unlist(coriolis)
    
    
    #calculate metrics which predict orientation error given movement since sunrise
    #time elapsed since dawn
    section$time_since_sunrise <- as.numeric(difftime(section$datetime, starts$sunrise_time[match(section$jday, starts$day)], units = "hours"))
    #find the latitudinal change since sunrise
    section$lat_change <- section$lat - starts$lat[match(section$jday, starts$day)]
    #get the solar azimuth at the fix time but at the location where the bird experienced sunrise
    azimuth_at_start_location <- (360-(180-(getSunlightPosition(data = data.frame(starts[match(section$jday, starts$day), c("lon","lat")], date = section$datetime), keep = "azimuth")[,4]*180/pi)))
    #find the difference between this azimuth and the azimuth the bird really experiences at that time
    section$sun_deflection <- section$sun_azimuth-azimuth_at_start_location
    #section$date <- as.Date(section$datetime)
    
    #record where the bird was at the start of the day, for randomisation later
    section$sunrise_lon <- starts$lon[match(section$jday, starts$day)]
    section$sunrise_lat <- starts$lat[match(section$jday, starts$day)]
    
    return(section)
  })
  })
  
  #return the gps data
  return(track_list)
})

#save data
save(gps_list, file = "")



#### continuous sections, start from here if sun compass data already added ####
load("")
load("")

#loop through indices of the highest level of the list (so you can also index the metadata)
analysis_list <- lapply(1:length(gps_list), function(index){
  #get that track
  track <- gps_list[[index]]
  #and if it's not too gappy, is of sufficient resolution (30 minute intervals here) and doesn't have speed or time errors
  if(all_metadata$no_sections[index] < 50 & !all_metadata$time_errors[index] & !all_metadata$speed_errors[index] & all_metadata$original_resolution_secs[index] <= 60*30){
    #loop through the sections within this track
    track_list <- lapply(track, function(trip){
      trip_list <- lapply(trip, function(section){
        #if the section represents part of a trip and contains homing
        if(section$out[1] & !is.na(section$homing_id[1]) & any(section$homing)){
          #get sections of continuous diurnal homing out of sight of land and home
          out_of_sight_sections <- rle(section$diurnal & section$homing & !is.na(section$diurnal) & !section$in_sight & !is.na(section$in_sight) & !section$home_visible & !is.na(section$home_visible))
          
          values <- out_of_sight_sections$values
          lengths <- out_of_sight_sections$lengths
          
          #if a section in sight of land/in sight of the colony is shorter than 30 mins make it part of surrounding homing
          #if a section out of sight of land or out of sight of the colony is shorter than 15 minutes, make it part of surrounding non-homing
          while(length(lengths) > 1 & ((any(lengths[which(values)] < 3) & any(lengths[which(values == FALSE)] >= 6)) | (any(lengths[which(values)] >= 3) & any(lengths[which(values == FALSE)] < 6)))){
            #find which sections are below threshold
            below <- which((lengths < 3 & values) | (lengths < 6 & !values))
            #get indices for section before or after
            neighbours <- lapply(below, function(index){c(index-1, index+1)})
            #unless it's the last or first section
            #in which case, just use the penultimate or second section, respectively
            if(below[length(below)] == length(lengths)){neighbours[[length(neighbours)]] <- length(lengths)-1}
            if(below[1] == 1){neighbours[[1]] <- 2}
            #if sections neighbouring those which are below threshold are themselves above threshold
            #reassign the value of those which are below threshold
            new_values <- sapply(1:length(neighbours), function(index){if(any(lengths[neighbours[[index]]] >= 6) & !values[neighbours[[index]][1]]){FALSE}else{if(any(lengths[neighbours[[index]]] >= 3) & values[neighbours[[index]][1]]){TRUE}else{values[index]}}})
            #and add to the values vector
            values[below] <- new_values
            
            #generate the newly correcte sections
            sections <- rle(rep(values, lengths))
            lengths <- sections$lengths
            values <- sections$values
          }
          
          #if there's any sections of homing left less than 3 fixes
          #(which happens if all the sections of both homing and non-homing are too short)
          #set them to FALSE
          if(any(lengths[which(values)] < 3)){
            values[which(values & lengths < 3)] <- FALSE
          }
          #save the corrected sections
          main_values <- values
          main_lengths <- lengths
          #assign them to the dataframe to identify bits of the section for the main model
          
          #now get sections of continuous diurnal homing with land either anticlockwise or clockwise, and either no clear beeline or beyond sight of home
          anticlock_land_sections <- rle(section$diurnal & section$homing & !is.na(section$diurnal) & !is.na(section$perpendicular_land_anticlock) & section$perpendicular_land_anticlock & !is.na(section$clear_beeline) & !is.na(section$home_visible) & (!section$clear_beeline | !section$home_visible))
          clock_land_sections <- rle(section$diurnal & section$homing & !is.na(section$diurnal) & !is.na(section$perpendicular_land_anticlock) & !section$perpendicular_land_anticlock & !is.na(section$clear_beeline) & !is.na(section$home_visible) & (!section$clear_beeline | !section$home_visible))
          
          #for now, correct the anticlockwise sections
          values <- anticlock_land_sections$values
          lengths <- anticlock_land_sections$lengths
          
          #if a section without land anticlockwise/with a clear beeline is shorter than 30 mins make it part of surrounding homing
          #if a section with land anticlockwise/without a clear beeline is shorter than 15 minutes, make it part of surrounding non-homing
          while(length(lengths) > 1 & ((any(lengths[which(values)] < 3) & any(lengths[which(values == FALSE)] >= 6)) | (any(lengths[which(values)] >= 3) & any(lengths[which(values == FALSE)] < 6)))){
            #find which sections are below threshold
            below <- which((lengths < 3 & values) | (lengths < 6 & !values))
            #get indices for section before or after
            neighbours <- lapply(below, function(index){c(index-1, index+1)})
            #unless it's the last or first section
            #in which case, just use the penultimate or second section, respectively
            if(below[length(below)] == length(lengths)){neighbours[[length(neighbours)]] <- length(lengths)-1}
            if(below[1] == 1){neighbours[[1]] <- 2}
            #if sections neighbouring those which are below threshold are themselves above threshold
            #reassign the value of those which are below threshold
            new_values <- sapply(1:length(neighbours), function(index){if(any(lengths[neighbours[[index]]] >= 6) & !values[neighbours[[index]][1]]){FALSE}else{if(any(lengths[neighbours[[index]]] >= 3) & values[neighbours[[index]][1]]){TRUE}else{values[index]}}})
            #and add to the values vector
            values[below] <- new_values
            
            #generate the newly correcte sections
            sections <- rle(rep(values, lengths))
            lengths <- sections$lengths
            values <- sections$values
          }
          
          #if there's any sections of homing left less than 3 fixes
          #(which happens if all the sections of both homing and non-homing are too short)
          #set them to FALSE
          if(any(lengths[which(values)] < 3)){
            values[which(values & lengths < 3)] <- FALSE
          }
          #save these sections
          anticlock_values <- values
          anticlock_lengths <- lengths
          
          #and now switch to correcting the clockwise sections
          values <- clock_land_sections$values
          lengths <- clock_land_sections$lengths
          
          #if a section without land aclockwise/with a clear beeline is shorter than 30 mins make it part of surrounding homing
          #if a section with land clockwise/without a clear beeline is shorter than 15 minutes, make it part of surrounding non-homing
          while(length(lengths) > 1 & ((any(lengths[which(values)] < 3) & any(lengths[which(values == FALSE)] >= 6)) | (any(lengths[which(values)] >= 3) & any(lengths[which(values == FALSE)] < 6)))){
            #find which sections are below threshold
            below <- which((lengths < 3 & values) | (lengths < 6 & !values))
            #get indices for section before or after
            neighbours <- lapply(below, function(index){c(index-1, index+1)})
            #unless it's the last or first section
            #in which case, just use the penultimate or second section, respectively
            if(below[length(below)] == length(lengths)){neighbours[[length(neighbours)]] <- length(lengths)-1}
            if(below[1] == 1){neighbours[[1]] <- 2}
            #if sections neighbouring those which are below threshold are themselves above threshold
            #reassign the value of those which are below threshold
            new_values <- sapply(1:length(neighbours), function(index){if(any(lengths[neighbours[[index]]] >= 6) & !values[neighbours[[index]][1]]){FALSE}else{if(any(lengths[neighbours[[index]]] >= 3) & values[neighbours[[index]][1]]){TRUE}else{values[index]}}})
            #and add to the values vector
            values[below] <- new_values
            
            #generate the newly corrected sections
            sections <- rle(rep(values, lengths))
            lengths <- sections$lengths
            values <- sections$values
          }
          
          #if there's any sections of homing left less than 3 fixes
          #(which happens if all the sections of both homing and non-homing are too short)
          #set them to FALSE
          if(any(lengths[which(values)] < 3)){
            values[which(values & lengths < 3)] <- FALSE
          }
          
          #now get logical vectors for which parts of the section should be part of analysis
          main_sections <- rep(main_values, main_lengths)
          anticlock_sections <- rep(anticlock_values, anticlock_lengths)
          clock_sections <- rep(values, lengths)
          #combine the land ones to be NA for no land perpendicular, TRUE for anticlock and FALSE for clock
          land_perpendicular_anticlock <- anticlock_sections
          land_perpendicular_anticlock[!anticlock_sections] <- NA
          land_perpendicular_anticlock[clock_sections] <- FALSE
          #get sections of continuous land clockwise or anticlockwise (but not both)
          land_sections <- (anticlock_sections | clock_sections) & !(anticlock_sections & clock_sections)
          
          if(any(land_sections[anticlock_sections & clock_sections])){print(section$track_trip_homing_id[1])}
          
          #now get combined vector for whether a fix is part of any analysis
          overall_sections <- main_sections | (anticlock_sections | clock_sections) & !(anticlock_sections & clock_sections)
          overall_sections <- rle(overall_sections)
          values <- overall_sections$values
          lengths <- overall_sections$lengths
          
          #assign vector to dataframe to show whether each fix should be part of the main analysis or 
          #land analysis
          section$main_subset <- main_sections
          section$perpendicular_land_subset <- land_sections
          
          
          #apply the combined vector to the data
          section$analysis_subset_id <- rep(1:length(lengths),lengths)
          section$track_trip_analysis_subset_id <- paste(section$track_trip_homing_id, section$analysis_subset_id)
          
          #split the overall bout into continuous sections for analysis
          #removing the IDs for those which don't meet the criteria
          remove <- c(1:length(lengths))[which(!values)]
          
          section_list <- lapply(1:length(lengths), function(id){data <- section[section$analysis_subset_id == id,];if(id %in% remove){data$analysis_subset_id <- NA}; return(data)})
          
          return(section_list)
        }else{
          #if this section doesn't contain homing, ignore it
          section$main_subset <- FALSE
          section$perpendicular_land_subset <- FALSE
          section$analysis_subset_id <- NA
          section$track_trip_analysis_subset_id <- paste(section$track_trip_homing_id, "1")
          return(list(section))
        }
      })
      return(trip_list)
    })
    return(track_list)
  }else{
    #if the track isn't of good enough quality, ignore it
    track_list <- lapply(track, function(trip){
      trip_list <- lapply(trip, function(section){
        section$main_subset <- FALSE
        section$perpendicular_land_subset <- FALSE
        section$analysis_subset_id <- NA
        section$track_trip_analysis_subset_id <- paste(section$track_trip_homing_id, "1")
        return(list(section))
      })
    })
    return(track_list)}
})


#save data
save(analysis_list, file = "")

#### generating data for analysis ####
load("")
load("")


#get list with only two levels; homing section and within them, analysis sections
analysis_list <- unlist(unlist(unlist(analysis_list, recursive = F), recursive = F), recursive = F)

#for each homing bout out of sight of land
analysis_data <- lapply(analysis_list, function(data){
  if(!is.na(data$analysis_subset_id[1])){
    if(data$main_subset[1]){
      #calculate the median bearing
      median_bearing <- as.numeric(median.circular(circular(data$instantaneous_gc_bearing, units = "degrees"), na.rm = T))
      data$median_bearing <- median_bearing
      data$median_deflection_from_colony <- median_bearing-data$gc_bearing_to_home[which.min(abs(data$instantaneous_gc_bearing - median_bearing))]
      data$median_deflection_from_colony <- ifelse(data$median_deflection_from_colony > 180, data$median_deflection_from_colony-360, data$median_deflection_from_colony)
      data$median_deflection_from_colony <- ifelse(data$median_deflection_from_colony < -180, 360+data$median_deflection_from_colony, data$median_deflection_from_colony)
      #calculate the angular deflection from this bearing
      data$deflection_from_median <- data$instantaneous_gc_bearing - median_bearing
      data$deflection_from_median <- ifelse(data$deflection_from_median > 180, data$deflection_from_median-360, data$deflection_from_median)
      data$deflection_from_median <- ifelse(data$deflection_from_median < -180, 360+data$deflection_from_median, data$deflection_from_median)
      #calculate the expected deflection from the median
      data$relative_sun <- data$sun_deflection - median(data$sun_deflection[data$diurnal], na.rm = T)
      data$relative_declination <- data$declination - median(data$declination, na.rm = T)
      
      #get the initial gc bearing to the end of the bout
      data$gc_to_end <- bearing(data[,c("lon","lat")], data[nrow(data),c("lon","lat")])
      data$gc_deflection <- data$gc_to_end-data$median_bearing
      data$gc_deflection <- ifelse(data$gc_deflection > 180, data$gc_deflection-360, data$gc_deflection)
      data$gc_deflection <- ifelse(data$gc_deflection < -180, 360+data$gc_deflection, data$gc_deflection)
      
      #downsample the data to every 10 fixes to avoid temporal autocorrelation
      if(nrow(data) > 5){
        data <- data[seq(5, nrow(data), 10),]
      }else{
        return(NULL)
      }
    }else{
      data$median_bearing <- NA
      data$median_deflection_from_colony <- NA
      data$deflection_from_median <- NA
      data$relative_sun <- NA
      data$relative_declination <- NA
      data$gc_to_end <- NA
      data$gc_deflection <- NA
      #downsample the data to every 10 fixes to avoid temporal autocorrelation
      if(nrow(data) > 3){
        data <- data[seq(3, nrow(data), 6),]
      }else{
        return(NULL)
      }
    }
    
    
    
    #return the data
    return(data)
  }else{
    return(NULL)
  }
})

analysis_data <- rbindlist(analysis_data)

#bind the data together
out_of_sight_data <- analysis_data[analysis_data$main_subset,]
land_data <- analysis_data[analysis_data$perpendicular_land_subset,]

#### add wind data ####
#get all unique dates in the out of sight of land data
dates <- unique(date(out_of_sight_data$datetime))
#list the relevant wind file names
wind_files <- dir("", pattern = ".tif", full.names = T)

#create empty columns
out_of_sight_data$u <- NA
out_of_sight_data$v <- NA

#for each date
for(i in 1:length(dates)){
  date <- dates[i]
  #subset the data to only this date
  indices <- which(out_of_sight_data$date == date)
  data <- out_of_sight_data[indices,]
  #split the date string
  date_str <- strsplit(as.character(date),"-")
  #retrieve the corresponding file
  file <- wind_files[which(grepl(paste(date_str[[1]][1], date_str[[1]][2], date_str[[1]][3], sep = "_"), wind_files))]
  #read in the file and extract the wind data
  wind <- brick(file)
  
  #find the range of hours in the data from this date
  hours <- min(hour(data$datetime)):max(hour(data$datetime))
  
  #find the relevant layer for each row of data based on the time of the fix
  #currently the if statement is a weird fix because some wind files have all hours 3:23, whereas others have only the hours found in the data
  layer_n <- sapply(1:nrow(data), function(row){which.min(abs(data$datetime[row]-as.POSIXct(paste(date, paste0(if(nlayers(wind) < 42){hours}else{3:23}, ":00")), tz = "GMT")))})
  #and extract u and v components, adding them to the columns
  for(j in unique(layer_n)){
    out_of_sight_data$u[out_of_sight_data$date == date][layer_n == j] <- extract(wind[[j*2-1]], data[layer_n == j,c("lon","lat")])
    out_of_sight_data$v[out_of_sight_data$date == date][layer_n == j] <- extract(wind[[j*2]], data[layer_n == j,c("lon","lat")])
  }
  
  
  print(i)
}
#calculate the crosswind component, relative to the median bearing
out_of_sight_data$crosswind <- out_of_sight_data$u*cos(out_of_sight_data$median_bearing*pi/180)-out_of_sight_data$v*sin(out_of_sight_data$median_bearing*pi/180)

#write csvs
write.csv(out_of_sight_data, "", row.names = F)
write.csv(land_data, "", row.names = F)

#### main analysis ####
load("")
load("")
analysis_list <- unlist(unlist(unlist(analysis_list, recursive = F), recursive = F), recursive = F)

#read in data for analysis
out_of_sight_data <- read.csv("")
land_data <- read.csv("")

#subset the data based on inclusion criteria
main_analysis_df <- out_of_sight_data[out_of_sight_data$main_subset & out_of_sight_data$homing & out_of_sight_data$diurnal & out_of_sight_data$bout_deflection < 75 & out_of_sight_data$bout_max_dist_from_home_km > 50 & out_of_sight_data$bout_proportional_movement_to_home > 0.5,]

#model comparison for rhumb vs. gc
aictab(cand.set = list(lmer(deflection_from_median~relative_sun+lat_change+coriolis_predictor+crosswind+time_since_sunrise+distance_from_home_km+colony+(1|ring), main_analysis_df, REML = F), lmer(deflection_from_median~gc_deflection+relative_sun+lat_change+coriolis_predictor+crosswind+time_since_sunrise+distance_from_home_km+colony+(1|ring), main_analysis_df, REML = F)))

#build a model for out of sight of land homing, including all relevant predictors
main_model <- lmer(deflection_from_median~gc_deflection+relative_sun+lat_change+coriolis_predictor+crosswind+time_since_sunrise+distance_from_home_km+colony+(1|ring), main_analysis_df, REML = F)
#check for collinearity
check_collinearity(main_model)

#extract the residuals from this model
oos_residuals <- resid(main_model)
#check temporal autocorrelation
acf(oos_residuals)

#assess normality using q-q
qqnorm(oos_residuals, main = NULL, col = alpha("skyblue3", 0.5))
qqline(oos_residuals)

#extract fitted  values and plot absolute residuals against fitted to check for constant variance
fitted <- fitted(main_model)
fit <- data.frame(fitted = fitted, residuals = abs(oos_residuals))
oos_variance_check <- ggplot(fit, aes(x = fitted, y = residuals))+
  labs(x = "Fitted values", y = "Residuals")+
  geom_point(colour = "skyblue3", alpha = 0.5)+geom_smooth(method = "loess", span = 0.75, colour = "grey25")+theme_light()


#Kolmogorov-Smirnov test to check normality
ks.test(oos_residuals, "pnorm", mean(oos_residuals), sd(oos_residuals))

#now that assumptions are checked and met to a sufficient degree,
#get coefficients summary
summary(main_model)
confint(main_model)

#LRT on each term in turn, using restricted and full models
main_model_null_gc <- lmer(deflection_from_median~relative_sun+lat_change+coriolis_predictor+crosswind+time_since_sunrise+distance_from_home_km+colony+(1|ring), main_analysis_df, REML = F)
anova(main_model_null_gc, main_model)

main_model_null_sun <- lmer(deflection_from_median~gc_deflection+lat_change+coriolis_predictor+crosswind+time_since_sunrise+distance_from_home_km+colony+(1|ring), main_analysis_df, REML = F)
anova(main_model_null_sun, main_model)

main_model_null_lat <- lmer(deflection_from_median~gc_deflection+relative_sun+coriolis_predictor+crosswind+time_since_sunrise+distance_from_home_km+colony+(1|ring), main_analysis_df, REML = F)
anova(main_model_null_lat, main_model)

main_model_null_coriolis <- lmer(deflection_from_median~gc_deflection+relative_sun+lat_change+crosswind+time_since_sunrise+distance_from_home_km+colony+(1|ring), main_analysis_df, REML = F)
anova(main_model_null_coriolis, main_model)

main_model_null_crosswind <- lmer(deflection_from_median~gc_deflection+relative_sun+lat_change+coriolis_predictor+time_since_sunrise+distance_from_home_km+colony+(1|ring), main_analysis_df, REML = F)
anova(main_model_null_crosswind, main_model)

main_model_null_time <- lmer(deflection_from_median~gc_deflection+relative_sun+lat_change+coriolis_predictor+crosswind+distance_from_home_km+colony+(1|ring), main_analysis_df, REML = F)
anova(main_model_null_time, main_model)

main_model_null_distance <- lmer(deflection_from_median~gc_deflection+relative_sun+lat_change+coriolis_predictor+crosswind+time_since_sunrise+colony+(1|ring), main_analysis_df, REML = F)
anova(main_model_null_distance, main_model)

main_model_null_colony <- lmer(deflection_from_median~gc_deflection+relative_sun+lat_change+coriolis_predictor+crosswind+time_since_sunrise+distance_from_home_km+(1|ring), main_analysis_df, REML = F)
anova(main_model_null_colony, main_model)


#### land analysis ####
#subset analysis data based on inclusion criteria
land_analysis_df <- land_data[land_data$homing & land_data$diurnal & land_data$bout_deflection < 75 & land_data$bout_max_dist_from_home > 50 & land_data$bout_proportional_movement_to_home > 0.5,]
land_analysis_df$perpendicular_distance_to_land <- land_analysis_df$perpendicular_distance_to_land/1000
#construct model for land-following with all relevant terms
land_model <- lmer(perpendicular_distance_to_land~sun_deflection*perpendicular_land_anticlock+colony+time_since_sunrise+distance_from_home_km+(1|ring), land_analysis_df, REML = F)
#check for collinearity
check_collinearity(land_model)
#all collinearity low so continue

#extract residuals
land_residuals <- resid(land_model)

#check autocorrelation
acf(land_residuals)

#assess normality using q-q
qqnorm(land_residuals, main = NULL, col = alpha("skyblue3", 0.5))
qqline(land_residuals)

#extract fitted  values and plot absolute residuals against fitted to check for constant variance
fitted <- fitted(land_model)
fit <- data.frame(fitted = fitted, residuals = abs(land_residuals))
land_variance_check <- ggplot(fit, aes(x = fitted, y = residuals))+
  labs(x = "Fitted values", y = "Residuals")+
  geom_point(colour = "skyblue3", alpha = 0.5)+geom_smooth(method = "loess", span = 0.75, colour = "grey25")+theme_light()

#Kolmogorov-Smirnov test to check normality
ks.test(land_residuals, "pnorm", mean(land_residuals), sd(land_residuals))

#now that assumptions are checked and met to a sufficient degree,
#get coefficients summary
summary(land_model)
confint(land_model)

#LRT on each term in turn, using restricted and full models
land_model_null_interaction <- lmer(perpendicular_distance_to_land~sun_deflection+perpendicular_land_anticlock+colony+time_since_sunrise+distance_from_home_km+(1|ring), land_analysis_df, REML = F)
anova(land_model_null_interaction, land_model)

land_model_null_colony <- lmer(perpendicular_distance_to_land~sun_deflection*perpendicular_land_anticlock+time_since_sunrise+distance_from_home_km+(1|ring), land_analysis_df, REML = F)
anova(land_model_null_colony, land_model)

land_model_null_time <- lmer(perpendicular_distance_to_land~sun_deflection*perpendicular_land_anticlock+colony+distance_from_home_km+(1|ring), land_analysis_df, REML = F)
anova(land_model_null_time, land_model)

land_model_null_distance <- lmer(perpendicular_distance_to_land~sun_deflection*perpendicular_land_anticlock+colony+time_since_sunrise+(1|ring), land_analysis_df, REML = F)
anova(land_model_null_distance, land_model)


#### AICc comparison ####
#build model identical to the out of sight model but replacing expected deflection from sun compass
#with expected deflection from magnetic compass
magnetic_mod <- lmer(deflection_from_median~gc_deflection+relative_declination+lat_change+coriolis_predictor+crosswind+time_since_sunrise+distance_from_home_km+colony+(1|ring), main_analysis_df, REML = F)

#compare AICc from each model
aictab(cand.set = list(main_model, magnetic_mod))

#### supplementary model 1: land between -2 and 2 ####
#build identical model to the land-following model above but subsetted only to the core of data where expected deflections lie between -2 and 2 degrees
land_model2 <- lmer(perpendicular_distance_to_land~sun_deflection*perpendicular_land_anticlock+time_since_sunrise+distance_from_home_km+colony+(1|ring), land_analysis_df[abs(land_analysis_df$sun_deflection) < 2.5,], REML = F)

#get coefficients
summary(land_model2)

#assess significance of interaction using LRT on restricted and full model
land_model2_null_interaction <- lmer(perpendicular_distance_to_land~sun_deflection+perpendicular_land_anticlock+time_since_sunrise+distance_from_home_km+colony+(1|ring), land_analysis_df[abs(land_analysis_df$sun_deflection) < 2.5,], REML = F)
anova(land_model2_null_interaction, land_model2)





#### sensitivity analysis ####
#create empty dataframe
sensitivity <- data.frame()
#create vectors of parameters to be tested in sensitivity analysis
deflection_range <- seq(75, 5, -15)
dist_range <- seq(10, 100, 10)
prop_range <- seq(0.05, 0.95, 0.05)

#for each possible combination of parameters
for(a in 1:length(deflection_range)){
  deflection_threshold <- deflection_range[a]
  for(b in 1:length(dist_range)){
    dist_threshold <- dist_range[b]
    for(c in 1:length(prop_range)){
      prop_threshold <- prop_range[c]
      
      #subset the data using this parameter combination
      data <- out_of_sight_data[out_of_sight_data$main_subset & out_of_sight_data$homing & out_of_sight_data$diurnal & out_of_sight_data$bout_max_dist_from_home_km > dist_threshold & out_of_sight_data$bout_proportional_movement_to_home > prop_threshold &  out_of_sight_data$bout_deflection < deflection_threshold,]
      #fit an identical model to the main model
      mod <- lmer(deflection_from_median~gc_deflection+relative_sun+lat_change+coriolis_predictor+crosswind+time_since_sunrise+distance_from_home_km+colony+(1|ring), data, REML = F)
      
      #extract the slope, p value and sample size
      oos_slope <- as.numeric(summary(mod)$coefficient[3])
      oos_p_val <- as.numeric(anova(lmer(deflection_from_median~gc_deflection+lat_change+coriolis_predictor+crosswind+time_since_sunrise+distance_from_home_km+colony+(1|ring), data, REML = F), mod)$Pr[2])
      oos_n <- length(which(out_of_sight_data$main_subset & out_of_sight_data$homing & out_of_sight_data$diurnal & out_of_sight_data$bout_max_dist_from_home_km > dist_threshold & out_of_sight_data$bout_proportional_movement_to_home > prop_threshold &  out_of_sight_data$bout_deflection < deflection_threshold))
      
      #do the same for the coast following model
      data <- land_data[land_data$perpendicular_land_subset & land_data$homing & land_data$diurnal & land_data$bout_max_dist_from_home_km > dist_threshold & land_data$bout_proportional_movement_to_home > prop_threshold &  land_data$bout_deflection < deflection_threshold,]
      mod <- lmer(perpendicular_distance_to_land~sun_deflection*perpendicular_land_anticlock+colony+time_since_sunrise+distance_from_home_km+(1|ring), data, REML = F)
      
      land_slope <- as.numeric(summary(mod)$coefficient[12])/1000
      land_p_val <- as.numeric(anova(lmer(perpendicular_distance_to_land~sun_deflection+perpendicular_land_anticlock+colony+time_since_sunrise+distance_from_home_km+(1|ring), data, REML = F), mod)$Pr[2])
      land_n <- length(which(land_data$perpendicular_land_subset & land_data$homing & land_data$diurnal &  land_data$bout_max_dist_from_home_km > dist_threshold & land_data$bout_proportional_movement_to_home > prop_threshold &  land_data$bout_deflection < deflection_threshold))
      
      #bind these into a dataframe
      sensitivity <- rbind(sensitivity, data.frame(deflection_threshold, dist_threshold, prop_threshold, oos_slope, oos_p_val, land_slope, land_p_val, oos_n, land_n))
    }
  }
}

#extract the observed coefficients
oos_observed_slope <- as.numeric(summary(main_model)$coefficient[3])
oos_observed_p <- as.numeric(anova(lmer(deflection_from_median~gc_deflection+lat_change+coriolis_predictor+crosswind+time_since_sunrise+distance_from_home_km+colony+(1|ring), main_analysis_df, REML = F), main_model)$Pr[2])

land_observed_slope <- as.numeric(summary(land_model)$coefficient[12])
land_observed_p <- as.numeric(anova(land_model_null_interaction, land_model)$Pr[2])

#compare observed coefficients to those generated with the other parameter combinations
length(which(sensitivity$oos_p_val < 0.05))/nrow(sensitivity)
length(which(sensitivity$oos_p_val < oos_observed_p))/nrow(sensitivity)

length(which(sensitivity$land_p_val < 0.05))/nrow(sensitivity)
length(which(sensitivity$land_p_val < land_observed_p))/nrow(sensitivity)

#### randomisation ####
#get a vector of unique sections of track in the analysis dataframe
unique_analysis_sections <- unique(main_analysis_df$track_trip_analysis_subset_id)

#get the distance and bearing of the shearwater from the colony at sunrise of that day of the track
start_from_home <- lapply(unique_analysis_sections, function(id){
  bearing <- bearing(main_analysis_df[main_analysis_df$track_trip_analysis_subset_id == id,c("colony_lon", "colony_lat")][1,], main_analysis_df[main_analysis_df$track_trip_analysis_subset_id == id,c("sunrise_lon", "sunrise_lat")][1,])
  dist <- distHaversine(main_analysis_df[main_analysis_df$track_trip_analysis_subset_id == id,c("colony_lon", "colony_lat")][1,], main_analysis_df[main_analysis_df$track_trip_analysis_subset_id == id,c("sunrise_lon", "sunrise_lat")][1,])
  
  return(data.frame(bearing, dist))
})

start_from_home <- rbindlist(start_from_home)


#for 1000 iterations
no_perms <- 1000
set.seed(10)

randoms <- lapply(1:no_perms, function(i){
  #randomly extract a bearing and distance from the colony for each row
  random_bearing <- sample(start_from_home$bearing, nrow(start_from_home), replace = T)
  random_dist <- exp(rnorm(nrow(start_from_home), mean(log(start_from_home$dist), na.rm = T), sd(log(start_from_home$dist), na.rm = T)))
  #find the bearing from the true bearing
  bearing_diff <- random_bearing-start_from_home$bearing
  #generate a randomised sunrise location using the randomly picked distance and bearing
  random_start_location <- destPoint(main_analysis_df[match(unique_analysis_sections, main_analysis_df$track_trip_analysis_subset_id),c("colony_lon","colony_lat")], random_bearing, random_dist)
  #using these randomised start locations
  random_data <- lapply(analysis_list, function(data){
    if(!is.na(data$analysis_subset_id[1]) & data$main_subset[1] & data$track_trip_analysis_subset_id[1] %in% unique_analysis_sections){
      
      #generate the expected sun compass error from this randomised starting point
      start_location <- random_start_location[which(unique_analysis_sections == data$track_trip_analysis_subset_id[1]),]
      random_azimuths <- (360-(180-(getSunlightPosition(data = data.frame(lon = start_location[1], lat = start_location[2], date = data$datetime), keep = "azimuth")[,4]*180/pi)))
      
      random_expecteds <- data$sun_azimuth - random_azimuths
      #if there are useable data
      if(length(random_expecteds) < 1){break}
      
      #calculate the median bearing
      median_bearing <- median(data$instantaneous_gc_bearing, na.rm = T)
      random_median <- median_bearing + bearing_diff[which(unique_analysis_sections == data$track_trip_analysis_subset_id[1])]
      #calculate the angular deflection from this bearing
      data$deflection_from_median <- data$instantaneous_gc_bearing - median_bearing
      data$deflection_from_median <- ifelse(data$deflection_from_median > 180, data$deflection_from_median-360, data$deflection_from_median)
      data$deflection_from_median <- ifelse(data$deflection_from_median < -180, 360+data$deflection_from_median, data$deflection_from_median)
      #calculate the expected deflection from the median
      data$relative_sun <- random_expecteds - median(random_expecteds, na.rm = T)
      
      
      #get the initial gc bearing to the end of the bout
      data$gc_to_end <- bearing(data[,c("lon","lat")], data[nrow(data),c("lon","lat")])
      data$gc_deflection <- data$gc_to_end-median_bearing
      data$gc_deflection <- ifelse(data$gc_deflection > 180, data$gc_deflection-360, data$gc_deflection)
      data$gc_deflection <- ifelse(data$gc_deflection < -180, 360+data$gc_deflection, data$gc_deflection)
      
      #downsample the data to every 10 fixes to avoid temporal autocorrelation
      if(nrow(data) > 5){
        data <- data[seq(5, nrow(data), 10),]
      }else{
        return(NULL)
      }
      #return the data
      return(data)
    }else{
      return(NULL)
    }
  })
  # bind the randomised data together
  random_data <- rbindlist(random_data)
  #add crosswind data
  random_data <- random_data[random_data$main_subset & random_data$homing & random_data$diurnal & random_data$bout_deflection < 75 & random_data$bout_max_dist_from_home_km > 50 & random_data$bout_proportional_movement_to_home > 0.5,]
  random_data$crosswind <- main_analysis_df$crosswind
  random_data <- random_data[!is.na(random_data$relative_sun),]
  # fit the same model as above
  random_mod <- lmer(deflection_from_median~gc_deflection+relative_sun+lat_change+coriolis_predictor+crosswind+time_since_sunrise+distance_from_home_km+colony+(1|ring), random_data, REML = F)
  # extract the slope and p value
  slope <- as.numeric(summary(random_mod)$coefficient[3])
  p <- as.numeric(anova(lmer(deflection_from_median~gc_deflection+lat_change+coriolis_predictor+crosswind+time_since_sunrise+distance_from_home_km+colony+(1|ring), random_data, REML = F), random_mod)$Pr[2])
  
  return(data.frame(slope, p))
})
#bind the randomised slopes and p values together
randoms <- rbindlist(randoms)
#visualise them
hist(randoms$slope)
hist(randoms$p, breaks = seq(0,1,0.1))
# compare the slopes from randomised data to the observed slope
length(which(abs(randoms$slope) > abs(oos_observed_slope)))*(1/no_perms)


#### fig1 ####
tracks <- rbindlist(analysis_list)

world <- ne_countries(scale = "medium", returnclass = "sf", country = c("United Kingdom", "Isle of Man", "Ireland", "Faroe Islands", "Iceland", "France"))

world <- st_crop(world, xmin = -40, xmax = 5, ymin = 40, ymax = 70)

small_world <- ne_countries(scale = "medium", returnclass = "sf", country = c("United Kingdom", "Isle of Man", "Ireland"))

small_world <- st_transform(small_world, "+proj=ortho +lat_0=54 +lon_0=-10")
world <- st_transform(world, "+proj=ortho +lat_0=55 +lon_0=-15")

#1a: all tracks with inset
all_tracks_plot <- ggplot(data = world)+
  geom_path(data = tracks,
            aes(x = lon, y = lat, group = track_id), linewidth = 0.5, alpha = 0.5, colour = "grey")+
  geom_point(data = tracks[is.na(tracks$homing_id) | (tracks$bout_deflection > 75 | tracks$bout_max_dist_from_home_km < 50 | tracks$bout_proportional_movement_to_home < 0.5),],
             aes(x = lon, y = lat), size = 0.5, alpha = 0.25, colour = "skyblue3")+
  geom_point(data = tracks[!is.na(tracks$homing_id) & tracks$bout_deflection < 75 & tracks$bout_max_dist_from_home_km > 50 & tracks$bout_proportional_movement_to_home > 0.5,],
             aes(x = lon, y = lat), size = 0.5, alpha = 0.5, colour = "#f5ab0a")+
  geom_sf(fill = "grey40", colour = "grey40")+
  coord_sf(ylim = c(45, 65), xlim = c(-35, 0), expand = F, default_crs = sf::st_crs(4326))+
  scale_x_continuous(breaks = seq(-35, 0, 5))+scale_y_continuous(breaks = seq(45, 65, 5))+
  labs(tag = "A")+
  annotation_scale(location = "br", width_hint = 0.25)+
  annotation_north_arrow(location = "tr", which_north = "true", style = north_arrow_fancy_orienteering)+#can add height and width to this to make sure it's big enough
  theme_light()+theme(panel.background = element_rect(fill = "white"),
                      legend.position = "none",
                      axis.title.x = element_blank(),
                      axis.title.y = element_blank(),
                      axis.text = element_text(size = 12))

#1a-inset

inset <- ggplot(data = small_world)+
  geom_sf(fill = "grey40", colour = "grey40")+
  geom_point(data = colony_coords,
             aes(x = lon, y = lat), size = 3, shape = 23, fill = "#f4720b", colour = "#f4720b", alpha = 0.75)+
  coord_sf(ylim = c(50.5, 58), xlim = c(-9, -4), expand = F, default_crs = sf::st_crs(4326))+
  scale_x_continuous(breaks = seq(-8, 2, 2))+scale_y_continuous(breaks = seq(51, 59, 2))+
  annotation_scale(location = "bl", width_hint = 0.25)+
  annotation_north_arrow(location = "tr", which_north = "true", style = north_arrow_fancy_orienteering, height = unit(0.1, "npc"), width = unit(0.3, "npc"))+#can add height and width to this to make sure it's big enough
  theme_light()+theme(panel.background = element_rect(fill = "white"),
                      plot.background = element_rect(fill = "transparent", colour = NA),
                      legend.position = "none",
                      axis.title.x = element_blank(),
                      axis.title.y = element_blank(),
                      axis.text = element_text(size = 8))



#1b: homing identification
#example <- unique(tracks$track_trip_id[tracks$lon < -11 & tracks$lon > -12 & tracks$lat > 53 & tracks$lat < 54 & tracks$homing])[1]

example <- tracks[tracks$track_trip_id == "397 2",]

id <- 71

start_homing <- example[example$homing_id == id,c("lon","lat")][1,]
end_homing <- example[example$homing_id == id,c("lon","lat")][length(which(example$homing_id == id)),]
home <- example[1,c("colony_lon","colony_lat")]
homeward_bearing <- bearing(start_homing, home)
homeward_distance <- distHaversine(start_homing, home)
just_before_end <- destPoint(start_homing, homeward_bearing, homeward_distance-10000)

abs(bearing(start_homing, end_homing)-homeward_bearing)
distHaversine(end_homing, home)/1000
homeward_distance/1000

(homeward_distance/1000 - distHaversine(end_homing, home)/1000)/(homeward_distance/1000)


homing_id_plot <- ggplot(data = small_world)+
  geom_sf(fill = "grey40", colour = "grey40")+
  geom_path(data = example, aes(x = lon, y = lat, group = track_trip_homing_id), colour = "grey", linewidth = 0.75, alpha = 0.75)+
  geom_point(data = example[is.na(example$homing_id) | (example$bout_deflection < 75 | example$bout_max_dist_from_home_km > 50 | example$bout_proportional_movement_to_home > 0.5),], aes(x = lon, y = lat, group = track_trip_homing_id), colour = "skyblue3", size = 0.75, alpha = 0.1)+
  geom_point(data = example[!is.na(example$homing_id) & example$homing_id != id  & example$bout_deflection < 75 & example$bout_max_dist_from_home_km > 50 & example$bout_proportional_movement_to_home > 0.5,], aes(x = lon, y = lat, group = track_trip_homing_id), colour = "#f5ab0a", size = 0.75, alpha = 0.1)+
  geom_point(data = example[example$homing_id == id,], aes(x = lon, y = lat, group = track_trip_homing_id), colour = "#f5ab0a", size = 1, alpha = 0.75)+
  geom_point(data = home, aes(x = colony_lon, y = colony_lat), shape = 23, size = 3, fill = "#f4720b", colour = "#f4720b")+
  geom_segment(aes(x = start_homing$lon, xend = home$colony_lon, y = start_homing$lat, yend = home$colony_lat), linewidth = 1, linetype = "dashed")+
  geom_segment(aes(x = just_before_end[1], xend = home$colony_lon, y = just_before_end[2], yend = home$colony_lat), linewidth = 1, arrow = arrow(length = unit(0.25, "cm")))+
  geom_segment(aes(x = start_homing$lon, xend = end_homing$lon, y = start_homing$lat, yend = end_homing$lat), linewidth = 1, arrow = arrow(length = unit(0.25, "cm")))+
  coord_sf(xlim = c(-18.5, -5), ylim = c(52.2, 56.8), expand = F, default_crs = sf::st_crs(4326))+
  scale_x_continuous(breaks = seq(-20, 5, 5))+scale_y_continuous(breaks = seq(53, 57, 1))+
  labs(tag = "B")+
  annotation_scale(location = "bl", width_hint = 0.25)+
  annotation_north_arrow(location = "tl", which_north = "true", style = north_arrow_fancy_orienteering, pad_x = unit(0.1, "cm"))+#can add height and width to this to make sure it's big enough
  theme_light()+theme(panel.background = element_rect(fill = "white"),
                      legend.position = "none",
                      axis.title.x = element_blank(),
                      axis.title.y = element_blank(),
                      axis.text = element_text(size = 12))

#1b-inset
unique_analysis_sections <- unique(main_analysis_df$track_trip_analysis_subset_id)

median_deflections <- sapply(unique_analysis_sections, function(id){main_analysis_df$median_deflection_from_colony[main_analysis_df$track_trip_analysis_subset_id == id][1]})
mean_deflection <- mean.circular(circular(median_deflections, unit = "degrees"))
sd_deflection <- sd.circular(circular(median_deflections, unit = "degrees"))*180/pi

inset2 <- ggplot(data.frame(deflection = median_deflections), aes(x = deflection))+
  annotate("rect", xmin = mean_deflection-sd_deflection, xmax = mean_deflection+sd_deflection, ymin = 0, ymax = 50, fill = "#f5ab0a", colour = "transparent", alpha = 0.25)+
  geom_histogram(fill = "#f5ab0a")+labs(x = NULL, y = NULL)+
  scale_y_continuous(limits = c(0,50), breaks = c(0,50, 25), expand = c(0,0))+
  scale_x_continuous(limits = c(-90, 90), breaks = seq(-90, 90, 45), expand = c(0,0))+
  geom_vline(xintercept = mean_deflection)+
  coord_radial(start = 0, end = pi, r.axis.inside = T)+
  labs(tag = "C")+
  theme(panel.background = element_rect(fill = "white"),
        #plot.background = element_rect(fill = "transparent", colour = NA),
        panel.grid = element_line(colour = "lightgrey"),
        legend.position = "none",
        #plot.tag.position = c(0.01, 0.9),
        axis.title.x = element_blank(),
        axis.text.y = element_blank(),
        axis.ticks.y = element_blank(),
        axis.title.y = element_blank(),
        #axis.text.x = element_text(colour = c("black", "black", "black", "white", "white")),
        axis.text = element_text(size = 8),
        plot.margin = margin(t = 0.1, b = 0.5, l = 0.5, r = 0.1, unit = "cm"))

fig1 <- ggdraw()+draw_plot(all_tracks_plot, x=0, y = 0.3, height = 0.7)+
  draw_plot(inset, height = 0.385, x = -0.27, y = 0.342)+
  draw_plot(homing_id_plot, height = 0.3, x = -1/6+0.015, y = 0)+
  draw_plot(inset2, height = 0.3, x = 0.34, y = 0)




#### fig2 ####
example <- tracks$track_trip_id[which.min(tracks$lon)]

example <- tracks[tracks$track_trip_id == example,]

start_index <- min(which(example$homing & example$bout_deflection < 75 & example$bout_max_dist_from_home_km > 50 & example$bout_proportional_movement_to_home > 0.5))

day <- example$jday[start_index]

start_homing <- example[start_index,c("lon","lat")]
end_homing <- example[max(which(!is.na(example$homing_id) & example$bout_deflection < 75 & example$bout_max_dist_from_home_km > 50 & example$bout_proportional_movement_to_home > 0.5 & example$jday == day)),c("lon","lat")]
home <- example[1,c("colony_lon","colony_lat")]
homeward_bearing <- bearing(start_homing, home)+0.02
homeward_distance <- distHaversine(start_homing, home)

fifteen_degree_point <- destPoint(start_homing, homeward_bearing+4.4, 0.6*homeward_distance)
fifteen_degree_point2 <- destPoint(start_homing, homeward_bearing+4.4, 0.65*homeward_distance)
just_before_end <- destPoint(start_homing, homeward_bearing, homeward_distance-1000)

CS_schematic_map <- ggplot(data = world)+
  geom_sf(fill = "grey40", colour = "grey40")+
  geom_path(data = example[example$jday < 225], aes(x = lon, y = lat), linewidth = 1, alpha = 0.75, colour = "skyblue3")+
  geom_segment(aes(x = fifteen_degree_point2[1], xend = home$colony_lon, y = fifteen_degree_point2[2], yend = home$colony_lat), linewidth = 1, linetype = "dashed")+
  geom_segment(aes(x = start_homing$lon, xend = fifteen_degree_point[1], y = start_homing$lat, yend = fifteen_degree_point[2]), linewidth = 1, arrow = arrow(length = unit(0.25, "cm")))+
  geom_segment(aes(x = just_before_end[1], xend = home$colony_lon, y = just_before_end[2], yend = home$colony_lat), linewidth = 1, arrow = arrow(length = unit(0.25, "cm")))+
  coord_sf(xlim = c(-35, 0), ylim = c(50, 63), expand = F, default_crs = sf::st_crs(4326))+
  scale_x_continuous(breaks = seq(-35, 0, 5))+scale_y_continuous(breaks = seq(50, 60, 5))+
  annotation_scale(location = "bl", width_hint = 0.25)+
  annotation_north_arrow(location = "tr", which_north = "true", style = north_arrow_fancy_orienteering)+
  theme_light()+theme(legend.position = "none",
                      axis.title.x = element_blank(),
                      axis.title.y = element_blank(),
                      axis.text = element_text(size = 12))



#### fig3 ####
main_effect <- Effect("relative_sun", partial.residuals=T, main_model)

closest <- function(x, x0) apply(outer(x, x0, FUN=function(x, x0) abs(x - x0)), 1, which.min)
trans <- I
main.x <- unlist(main_effect$x.all)
main_fitted <- data.frame(lower = main_effect$lower, upper = main_effect$upper, fit = main_effect$fit, sun = main_effect$x$relative_sun)
main_points <- data.frame(sun = main.x, deflection = main_fitted$fit[closest(trans(main.x), main_fitted$sun)] + main_effect$residuals)


fig3 <- ggplot(main_fitted, aes(x = sun, y = fit)) +
  geom_point(data = main_points, aes(x = sun, y = deflection), col = "skyblue3", size = 3.5, alpha = 0.5) +
  geom_ribbon(aes(ymin = lower, ymax = upper), alpha = 0.5, fill = "grey")+
  geom_line(linewidth = 1)+
  labs(x = "Expected clockwise deflection (°)", y = "Observed clockwise deflection (°)")+
  theme_light()+theme(axis.text = element_text(size = 12), axis.title = element_text(size = 16))


#### fig4 ####
#4a: coast following S Ireland
ireland <- ne_countries(scale = "large", returnclass = "sf", country = "Ireland")
ireland <- st_transform(ireland, "+proj=ortho +lat_0=51.5 +lon_0=-9.5")

tracks2 <- arrange(tracks, sun_deflection)

land_following_closeup_S_ireland <- ggplot(data = ireland)+
  geom_sf(fill = "grey40", colour = "grey40")+
  geom_path(data = tracks[!is.na(tracks$homing_id) & tracks$diurnal & tracks$lat > 51 & tracks$lat < 52 & tracks$lon < -8 & tracks$lon > -11 & !is.na(tracks$sun_deflection) & tracks$perpendicular_land_anticlock == TRUE,],
            aes(x = lon, y = lat, group = track_trip_homing_id), colour = "grey", linewidth = 1, alpha = 0.25)+
  geom_point(data = tracks2[!is.na(tracks2$homing_id) & tracks2$diurnal & tracks2$lat > 51 & tracks2$lat < 52 & tracks2$lon < -8 & tracks2$lon > -11 & !is.na(tracks2$sun_deflection) & tracks2$perpendicular_land_anticlock == TRUE,],
             aes(x = lon, y = lat, colour = sun_deflection), size = 3, alpha = 0.75)+
  labs(tag = "A")+
  coord_sf(ylim = c(51, 52), xlim = c(-11, -8), expand = F, default_crs = sf::st_crs(4326))+#labs(legend = "Expected clockwise deflection")+
  scale_colour_gradient(low = "#005AFF", high = "orange", name = "Expected\nclockwise\ndeflection (°)")+
  annotation_scale(location = "bl", width_hint = 0.25)+
  annotation_north_arrow(location = "tl", which_north = "true", style = north_arrow_fancy_orienteering, pad_x = unit(0.1, "cm"))+
  theme_light()+theme(axis.title.x = element_blank(),
                      axis.title.y = element_blank(),
                      axis.text = element_text(size = 12),
                      legend.title = element_text(size = 12),
                      legend.text = element_text(size = 8))

#4b: land model effect
land_effect <- Effect(c("sun_deflection","perpendicular_land_anticlock"), partial.residuals=T, land_model)

closest <- function(x, x0) apply(outer(x, x0, FUN=function(x, x0) abs(x - x0)), 1, which.min)
trans <- I
sun.fit <- unlist(land_effect$x.all$sun_deflection)
land.fit <- unlist(land_effect$x.all$perpendicular_land_anticlock)
land_fit_labels <- ifelse(land.fit, "Land anticlockwise of direction of travel", "Land clockwise of direction of travel")
land_fitted <- data.frame(lower = land_effect$lower, upper = land_effect$upper, fit = land_effect$fit, sun = land_effect$x$sun_deflection, land = rep(c("Land clockwise of direction of travel", "Land anticlockwise of direction of travel"), each = 100))
land_points <- data.frame(sun = sun.fit, land = land_fit_labels, distance_from_land = ifelse(land.fit, land_fitted$fit[101:200][closest(trans(sun.fit), land_fitted$sun[101:200])],land_fitted$fit[1:100][closest(trans(sun.fit), land_fitted$sun[1:100])])  + land_effect$residuals)


land_marginal_effect <- ggplot(land_fitted, aes(x = sun, y = fit)) +
  geom_point(data = land_points, aes(x = sun, y = distance_from_land), col = "skyblue3", size = 2.5, alpha = 0.35) +
  geom_ribbon(aes(ymin = lower, ymax = upper), alpha = 0.5, fill = "grey")+
  geom_line(linewidth = 1)+
  labs(x = "Expected clockwise deflection (°)", y = "Distance from land (km)", tag = "B")+
  facet_wrap(~land)+
  theme_light()+theme(axis.text = element_text(size = 12), strip.text = element_text(size = 12),
                      strip.background =element_rect(fill="skyblue4"),
                      axis.title = element_text(size = 16),
                      plot.tag = element_text(size = 12))

land_following <- ggdraw()+draw_plot(land_following_closeup_S_ireland, x = 0, y = 0.5, height = 0.5, width = 1)+
  draw_plot(land_marginal_effect,x = 0, y = 0, height = 0.5, width = 1)



#### figS1 ####

previous_day_transits <- sapply(unique_analysis_sections, function(id){
  data <- tracks[tracks$track_id == main_analysis_df$track_id[main_analysis_df$track_trip_analysis_subset_id == id][1]]
  return(data$lon[data$jday == min(main_analysis_df$jday[main_analysis_df$track_trip_analysis_subset_id == id])][1] - data$lon[data$jday == min(main_analysis_df$jday[main_analysis_df$track_trip_analysis_subset_id == id])-1][1])
})

previous_day_transits[is.na(previous_day_transits)] <- 0
previous_day_transits <- previous_day_transits*4/60
max(previous_day_transits)

figS1 <- ggplot(data.frame(previous_day_transits), aes(x = previous_day_transits))+
  annotate("rect", xmin = -3, xmax = -2, ymin = 0, ymax = 200, fill = "#f5ab0a", colour = "transparent", alpha = 0.75)+
  annotate("rect", xmin = -2, xmax = -1, ymin = 0, ymax = 200, fill = "#f5ab0a", colour = "transparent", alpha = 0.5)+
  annotate("rect", xmin = 1, xmax = 2, ymin = 0, ymax = 200, fill = "#f5ab0a", colour = "transparent", alpha = 0.5)+
  annotate("rect", xmin = 2, xmax = 3, ymin = 0, ymax = 200, fill = "#f5ab0a", colour = "transparent", alpha = 0.75)+
  geom_histogram(fill = "skyblue3")+coord_cartesian(xlim = c(-2.5,2.5), ylim = c(-1,200), expand = F)+
  labs(x = "Time-shift from previous sunrise (h)")+theme_light()



#### figS2 ####

oos_sensitivity <- ggplot(sensitivity, aes(prop_threshold, deflection_threshold, fill = oos_p_val)) +
  geom_raster(interpolate = FALSE) +
  scale_fill_gradientn(
    colours=c(muted("red"), "yellow", "skyblue", muted("darkblue")),
    values = rescale(c(min(sensitivity$oos_p_val), 0.05, 0.050001, max(sensitivity$oos_p_val)))) +
  scale_x_continuous(breaks = seq(0,1,0.5), labels = c("0", "0.5", "1"))+
  facet_wrap(~dist_threshold, nrow = 2) +
  labs(tag = "A")+
  theme_minimal() +
  labs(fill = "P", x = "Proportion of homewards distance covered", y = "Deflection from homeward beeline")

land_sensitivity <- ggplot(sensitivity, aes(prop_threshold, deflection_threshold, fill = land_p_val)) +
  geom_raster(interpolate = FALSE) +
  scale_fill_gradientn(
    colours=c(muted("red"), "yellow", "skyblue", muted("darkblue")),
    values = rescale(c(min(sensitivity$land_p_val), 0.05, 0.050001, max(sensitivity$land_p_val)))) +
  scale_x_continuous(breaks = seq(0,1,0.5), labels = c("0", "0.5", "1"))+
  facet_wrap(~dist_threshold, nrow = 2) +
  labs(tag = "B")+
  theme_minimal() +
  labs(fill = "P", x = "Proportion of homewards distance covered", y = "Deflection from homeward beeline")

figS2 <- plot_grid(oos_sensitivity, land_sensitivity, ncol = 1)



#### figS3 ####

figS3 <- ggplot(randoms, aes(x = slope))+
  geom_histogram(fill = "skyblue3")+geom_vline(xintercept = oos_observed_slope, linetype = "dashed")+
  coord_cartesian(xlim= c(-2.2, 2.2), ylim = c(-1, 200), expand = F)+labs(x = "Slope between observed and expected deflection")+
  theme_light()



#### fig S6 - land effect between -2 and 2 ####
land_effect2 <- Effect(c("sun_deflection","perpendicular_land_anticlock"), partial.residuals=T, land_model2)

closest <- function(x, x0) apply(outer(x, x0, FUN=function(x, x0) abs(x - x0)), 1, which.min)
trans <- I
sun.fit2 <- unlist(land_effect2$x.all$sun_deflection)
land.fit2 <- unlist(land_effect2$x.all$perpendicular_land_anticlock)
land_fit_labels2 <- ifelse(land.fit2, "Land anticlockwise of direction of travel", "Land clockwise of direction of travel")
land_fitted2 <- data.frame(lower = land_effect2$lower, upper = land_effect2$upper, fit = land_effect2$fit, sun = land_effect2$x$sun_deflection, land = rep(c("Land clockwise of direction of travel", "Land anticlockwise of direction of travel"), each = 100))
land_points2 <- data.frame(sun = sun.fit2, land = land_fit_labels2, distance_from_land = ifelse(land.fit2, land_fitted2$fit[101:200][closest(trans(sun.fit2), land_fitted2$sun[101:200])],land_fitted2$fit[1:100][closest(trans(sun.fit2), land_fitted2$sun[1:100])])  + land_effect2$residuals)


figS6 <- ggplot(land_fitted2, aes(x = sun, y = fit)) +
  geom_point(data = land_points2, aes(x = sun, y = distance_from_land), col = "skyblue3", size = 2.5, alpha = 0.35) +
  geom_ribbon(aes(ymin = lower, ymax = upper), alpha = 0.5, fill = "grey")+
  geom_line(size = 1)+
  geom_line(data = land_fitted, aes(x = sun, y = fit), colour = "grey30", alpha = 0.5, lwd = 1)+
  geom_ribbon(data = land_fitted, aes(ymin = lower, ymax = upper), alpha = 0.25, fill = "grey80")+
  lims(x = c(-2,2))+
  labs(x = "Expected clockwise deflection (°)", y = "Distance from land (km)")+
  facet_wrap(~land)+
  theme_light()+theme(axis.text = element_text(size = 12), strip.text = element_text(size = 12),
                      strip.background =element_rect(fill="skyblue4"),
                      axis.title = element_text(size = 16),
                      plot.tag = element_text(size = 12))


