

##required packages
x <- c("units", "rgdal", "rgeos", "tmap","sf","wkb","raster", "ggplot2", "maptools",
       "yarrr", "tidyverse","dplyr","reshape2","cowplot","readxl","ggpubr", "spatstat" )

lapply(x, library, character.only = TRUE) 

###############################################################################################
###  Data preprocessing 
setwd("C:\\Users\\Administrator.GEOGDEPPGLAPTOP\\Documents\\New_SQL_R\\Mock_data")
####  importing required data
##   original data 
orgmock_data <- readRDS(file = 'orgmock_data.Rds')
##  union of all field parcels  in study area
orgmock_poly <- readRDS(file = 'orgmock_poly.Rds')
##  study area without field parcels (non-sensitive area)
orgmock_nonsen <- readRDS(file = 'orgmock_nonsen.Rds')

crs(orgmock_poly) <- CRS("+init=epsg:2157")
orgmock_poly_sf <- st_as_sf(orgmock_poly)

############################################################################
########    study area 
path1 = "C:\\Users\\Administrator.GEOGDEPPGLAPTOP\\Documents\\New_SQL_R\\Mock_data"
Cork <- readOGR(dsn= path1, layer= "Cork")
Corkt <- spTransform(Cork, CRSobj = CRS(proj4string(orgmock_poly)))
#####################################################################################

## function to find rmin or rmax for a given k in PDonut and PDensity methods
### 
################################################################
max_dist <- function(shape,mapflag,type){
  f_shape <- readWKB(shape)
  p <- coordinates(f_shape)
  w <- as.owin.SpatialPolygons(f_shape)
  v <- vertices(w) # Polygon vertices
  d <- crossdist(v$x, v$y, p[1,1], p[1,2]) 
  imax <- which.max(d) # Index of max dist fo
  imin <- which.min(d) # Index of max dist fo
  if (mapflag){
    plot(w)
    points(p, col = c("red"), cex = 1.5)
    points(v$x[imax], v$y[imax], col = "blue", cex = 1.5)
    points(v$x[imin], v$y[imin], col = "green", cex = 1.5)
  }
  if (type)
    return (c(max(d),min(d)))
  else
    return (c(v$x[imax], v$y[imax],max(d),min(d)))
}

st_find_Rmin_Rmax <- function(area,input_data,mdata,k1,k2,R2,rateR,nr,t,wflag,ktype){
  start <- Sys.time()
  pnt <- input_data
  coordinates(pnt) <- ~ cnt_x + cnt_y
  crs(pnt) <- CRS("+init=epsg:2157")
  pnt <- st_as_sf(pnt)
  if (wflag & ktype == 1)
    mdata$maxk_R1 <- 0 
  if (wflag & ktype == 2)
    mdata$maxk11_R2 <- 0 
  lsR1 <- c()
  lsR2 <- c()
  nrt <- nr + t-1
  tmpR2 <- R2
  for (center_p in nr:nrt)
  {
    print(center_p)
    max_min_edge <- max_dist(pnt$plot_shape[center_p],FALSE,TRUE)
    m_m <- st_point_Min_Max_krate(center_p,pnt,k1,k2,R2,max_min_edge,rateR,ktype)
    if (is.null(m_m))
       return()
    if (wflag ){
      if (ktype == 1){
        mdata$maxd_edge[center_p] <- max_min_edge[1]
        mdata$mind_edge[center_p] <- max_min_edge[2]
        mdata$maxk_R1[center_p] <- m_m
      }
      else
        mdata$maxk11_R2[center_p] <- m_m
    }
    lsR1 <- c(lsR1,m_m)
  }
  print(paste('r1' ,max(lsR1)))
  print(paste('r1 index', which.max(lsR1)))
  print(Sys.time() - start )
  if (wflag)
    return(mdata)
  else
    return(max(lsR1))
}

st_point_Min_Max_krate <- function(center_p,pnt,k1,k2,R2,max_min_edge,rateR,ktype){
  if(ktype == 2){
    if (is.null(pnt$maxk_R1[center_p]) ){
      print('please first run the program with wflag = TRUE and ktype = 1')
      return()
    }
    tmpR1 <- pnt$maxk_R1[center_p]
    k <- k1 +k2
  }
  else{
    tmpR1 <- as.integer(max_min_edge[2]) + 1
    k <- k1
  }
  minrate <- 0.5
  tmp_raterR <- rateR
  num_in_buf <- 0
  tagr1 <- FALSE
  cnt <- pnt$geometry[center_p]
  d_max_edge <- c()
  while (rateR > minrate){
    center_buf1 <- st_buffer(cnt,tmpR1)
    p_in_buf <- st_intersection(pnt,center_buf1)
    while (nrow(p_in_buf) <= k & tmpR1 < R2){
      tmpR1 <- tmpR1 + rateR
      center_buf1 <- st_buffer(cnt,tmpR1)
      p_in_buf <- st_intersection(pnt,center_buf1)
      tagr1 <- TRUE
    }
    if (tagr1){
      tmpR1 <- tmpR1 - rateR
      rateR <- rateR/2
      tmpR1 <- tmpR1 + rateR
    }
    else{
      rateR <- minrate
      tmpR1 <- tmpR1 + rateR
    }
  }
  if (tagr1)
    tmpR1 <- tmpR1 +rateR
  tmpR1 <- max(tmpR1,max_min_edge[1])
  center_buf1 <- st_buffer(cnt,tmpR1)
  p_in_buf <- st_intersection(pnt,center_buf1)
  t <- p_in_buf$geometry
  d <- as.numeric(st_distance(t,cnt))
  d_max_edge <- as.integer(d + p_in_buf$maxd_edge) +1
  tmpR1 <- max(tmpR1,sort(d_max_edge)[k])
  # step two
  center_buf1 <- st_buffer(cnt,tmpR1)
  num_of_poly <- st_intersection(pnt,center_buf1)
  if (nrow(num_of_poly) > nrow(p_in_buf) ){
    t <- num_of_poly$geometry
    d <- as.numeric(st_distance(t,cnt))
    d_max_edge <- as.integer(d + num_of_poly$maxd_edge) +1
    tmpR1 <- max(tmpR1,sort(d_max_edge)[k])
  }
  return(round(tmpR1))
}    

#############################################################

# run st_find_Rmin_Rmax for different values of k1 from 4 to 14 (k2 could be any number at this step)
#to find the rmin associated with the optimal value of k1 for example:
rmin4 <- st_find_Rmin_Rmax(cork,orgmock_data,orgmock_data,4,4,50000,1000,1,nrow(orgmock_data),FALSE,1)
##############################################################################

## after generating Figure 1a and identifying optimal value of k1 
## run the function with optimal value of k1 (here k1 = 5) and wflag = TRUE to generate updated orgmock_data
## and add 3 variables maxd_edge, mind_edge and maxk_R1 (estimate inner radius of donut shape)
orgmock_k1_5 <- st_find_Rmin_Rmax(cork,orgmock_data,orgmock_data,5,4,50000,1000,1,nrow(orgmock_data),TRUE,1)
########################################################################

## run st_find_Rmin_Rmax for different values of k2 from 4 to 14 when k1 is optimal value 
## from above process (here k1 = 5) to find the rmax associated with the optimal value of
## k2 (note use the updated file generated above) for example:
rmax4 <- st_find_Rmin_Rmax(cork,orgmock_k1_5,orgmock_k1_5,5,4,50000,1000,1,nrow(orgmock_k1_5),FALSE,2)
## after generating Figure 1b and identifying optimal value of k2 
## run the function with optimal value of k1 and k2 and wflag = TRUE to generate updated input_data
## and add variable maxk11_R2 (estimate outer radius of donut shape)
orgmock_k1_5_k2_12_tmp <- st_find_Rmin_Rmax(cork,orgmock_k1_5,orgmock_k1_5,5,12,50000,1000,1,nrow(orgmock_k1_5),TRUE,2)
########################################################################################




