# ---
# author: "Antony Knights"
# date: "22/08/2022"
# ---

# Loading packages --------------------------------------------------------
# remotes::install_github("geocompr/geocompkg")
# remotes::install_github("Nowosad/spDataLarge")
library(dplyr); library(ggplot2); library(sf); library(raster); library(spData); library(spDataLarge); library(tmap); library(geocompkg); library(readxl);require(mapplots); require(plotrix); require(marmap)
# Allocating Memory to R --------------------------------------------------
ulimit::memory_limit(16000)
## DREAMS Systematic Map Data

# Set the working directory -----------------------------------------------
setwd("~/Desktop")

# Load the data -----------------------------------------------------------
geog.map <- read_excel("MapGeographicalData.xlsx")

# Create a geographical map of distribution -------------------------------
# Create a summary of the number of records grouped by country and --------
country.dat <- geog.map %>%
  group_by(Country, StructureType, StudyID) %>%
  summarise(count= n())
country.dat <- country.dat %>%
  group_by(name_long=Country, StructureType) %>%
  summarise(count=n()) %>%
  mutate(prob = count/sum(count))
country.dat$StructureType <- as.factor(country.dat$StructureType)
country.dat$name_long <- as.factor(country.dat$name_long)
country.dat$name_long <- plyr::mapvalues(country.dat$name_long, from="USA", to="United States")
country.dat$name_long <- plyr::mapvalues(country.dat$name_long, from="UK", to="United Kingdom")

# Merge world map polygons with summary data ------------------------------
data(world)
merge.dat <- left_join(world, country.dat)
## Drop the 'Seven seas' continental data
merge.dat <- subset(merge.dat, !continent == "Seven seas (open ocean)")
merge.dat$prob[is.na(merge.dat$prob)] <- 0

# Pie Charts on Maps ------------------------------------------------------
centroids <- sf::st_centroid(world) ## Generate centroids as lon-lat of country polygons
centroids <- tidyr::extract(centroids, geom, into=c('Lat','Lon'),'\\((.*),(.*)\\)', conv = T)
centroids <- as.data.frame(centroids); rownames(centroids) <- centroids$name_long
centroids <- centroids[,12:13] ## keep lon-lat only
latlon <- centroids[match(merge.dat$name_long, rownames(centroids)),]; latlon <- as.data.frame(latlon); colnames(latlon) <- c("Lon","Lat")
merge.dat <- cbind(merge.dat, latlon)
merge.dat$name_long <- as.factor(merge.dat$name_long)
#row.names(merge.dat) <- row.names(latlon)
merge.dat <- merge.dat[,c(2,11:16)]
merge.dat$StructureType <- as.factor(merge.dat$StructureType)
merge.dat <- merge.dat[!is.na(merge.dat$count),]
merge.dat$StructureType <- as.factor(merge.dat$StructureType)
rm(latlon)

# Set plot colours --------------------------------------------------------
#col=rainbow(length(levels(merge.dat$StructureType)))
color = c("#999999", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00")

# Plot the map ------------------------------------------------------------
map.dat <- mapplots::make.xyz(x=merge.dat$Lon, y=merge.dat$Lat, z=merge.dat$count, group = merge.dat$StructureType)
{
  maps::map(col=alpha('lightgrey', 0.5), fill=TRUE)
  box()
  legend("bottomleft", 
         legend = levels(merge.dat$StructureType),
         fill=color,
         cex=0.4)
  mapplots::draw.pie(z=map.dat$z, x=map.dat$x, y=map.dat$y, radius=sqrt(max(merge.dat$count)+100), scale=T, col=alpha(color,1))
}
dev.off()

# Sea area map ------------------------------------------------------------
oceans.shp <- rgdal::readOGR("goas_v01.shp", stringsAsFactors=FALSE, verbose=FALSE)
oceans <- st_as_sf(oceans.shp) ## Convert shapefile to a simple feature (sf)
oceans$name[7] <- "Mediterranean Sea"

# Load Database -----------------------------------------------------------
geog.map <- read_excel("MapGeographicalData.xlsx")

# Summarise the data ------------------------------------------------------
ocean.dat <- geog.map %>%
  group_by(name=GeographicalLocation_level2c, StructureType, StudyID) %>%
  summarise(count= n())
ocean.dat <- ocean.dat %>%
  group_by(name, StructureType) %>%
  summarise(count=n()) %>%
  mutate(prob = count/sum(count))
ocean.dat$StructureType <- as.factor(ocean.dat$StructureType)
ocean.dat$name <- as.factor(ocean.dat$name)

# Merge world map polygons with summary data ------------------------------
ocean.merge.dat <- left_join(oceans, ocean.dat) ## Merge the sf and data
ocean.merge.dat$prob[is.na(ocean.merge.dat$prob)] <- 0

# Pie Charts on Maps ------------------------------------------------------
require(mapplots); require(plotrix); require(dplyr); require(marmap)
centroids <- as.data.frame(getSpPPolygonsLabptSlots(oceans.shp)); colnames(centroids) <- c("longitude","latitude")
centroids$name <- oceans$name
centroids <- as.data.frame(centroids); rownames(centroids) <- centroids$name
latlon <- centroids[match(ocean.merge.dat$name, rownames(centroids)),]; latlon <- as.data.frame(latlon); colnames(latlon) <- c("longitude","latitude")

ocean.merge.dat <- cbind(ocean.merge.dat, latlon)
ocean.merge.dat$name <- as.factor(ocean.merge.dat$name)
ocean.merge.dat <- ocean.merge.dat[,c(1:3,9:11,15)]
ocean.merge.dat <- ocean.merge.dat[!is.na(ocean.merge.dat$count),]
rm(latlon)

color = c("#999999", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00")

map.dat <- mapplots::make.xyz(x=ocean.merge.dat$longitude, y=ocean.merge.dat$latitude, z=ocean.merge.dat$count, group = ocean.merge.dat$StructureType)

## Simplify shapefile for plotting purposes
oceans.shp <- rgeos::gSimplify(oceans.shp, tol=0.01, topologyPreserve=TRUE)

{
  plot(oceans.shp)
  maps::map(col=alpha('lightgrey', 0.5), fill=TRUE)
  box()
  legend("bottomleft", 
         legend = levels(ocean.merge.dat$StructureType),
         fill=color,
         cex=0.4)
  draw.pie(z=map.dat$z, x=map.dat$x, y=map.dat$y, radius=10, scale=F, col=alpha(color,1))
}

