
##  create a copy of  file for evaluation 
obf_mock_tmp <- orgmock_k1_5_k2_12_tmp
coordinates(obf_mock_tmp) <- ~ cnt_x + cnt_y
crs(obf_mock_tmp) <- CRS("+init=epsg:2157")
## create a excel file called summary_mockdata
## following  evaluation methods were applied for each obfuscation methods
## code indicating the obfuscation methods are:
## 2: PNRand
## 3: PNMix
## 4: PDonut
## 5: PDensity
## 6: PAHilb
## 7: PDonut_AHilb

#####  compare original point and obfuscated point generated by each methods on map
plot_point_map <- function(area,input_data,nr){
  coln <- c('blue',"purple", "green", "brown", "orange", "red", "black")
  cex = 0.8
  pnt <- input_data
  coordinates(pnt) <- ~ cnt_x + cnt_y
  crs(pnt) <- CRS("+init=epsg:2157")
  pnt <- spTransform(pnt, CRSobj = CRS(proj4string(area)))
  plot(area)
  points(pnt@coords[nr,1],pnt@coords[nr,2], pch = 19, col = coln[1], cex = 1.)
  points(pnt$omax_x5[nr],pnt$omax_y5[nr], pch = 19, col = coln[2], cex = cex)
  points(pnt$oave_x5[nr],pnt$oave_y5[nr], pch = 19, col = coln[3], cex = cex)
  points(pnt$dt_orand_x[nr],pnt$dt_orand_y[nr], pch = 19, col = coln[4], cex = cex)
  points(pnt$denorandk11k_x[nr],pnt$denorandk11k_y[nr], pch = 19, col = coln[5], cex = cex)
  points(pnt$hoave_x[nr],pnt$hoave_y[nr], pch = 19, col = coln[6], cex = cex)
  points(pnt$dt_hrand_x[nr],pnt$dt_hrand_y[nr], pch = 19, col = coln[7], cex = cex)
  legend("topleft", inset=.02, title="Methods",pch = c(19,19,19,19,19,19,19),
         legend =  c("Orignal","PNRand","PNMix","PDt","PD","PAH","Pdt_AH"),col = coln , cex=0.8)
  return()
}
##  for example point number 2000
plot_point_map(Corkt,orgmock_k1_5_k2_12_tmp,2000)

###############################################################################
##   Distribution preservation Analysis
##   2D KS-test using peacock.test package 
##   create a excel sheet (peacock) and add each of the following peacock output 
###############################################################################

library(Peacock.test)

peacock2(obf_mock_tmp@coords,obf_mock_tmp@data[,c(15,16)])   ##  PNRand  method
peacock2(obf_mock_tmp@coords,obf_mock_tmp@data[,c(17,18)])   ##  PNMix Method   
peacock2(obf_mock_tmp@coords,obf_mock_tmp@data[,c(19,20)])   ##  PDonut Method
peacock2(obf_mock_tmp@coords,obf_mock_tmp@data[,c(21,22)])   ##  PDensity Method
peacock2(obf_mock_tmp@coords,obf_mock_tmp@data[,c(23,24)])   ##  PAHilb  Method
peacock2(obf_mock_tmp@coords,obf_mock_tmp@data[,c(25,26)])   ##  PDonut_AHilb Method

#########################################################################################
##  1D KS_test  and correlation alteration 
##  add the output of each of the following 1D KS-test to a excel sheet (peacock)  
######################################################################################
ks.test(obf_mock_tmp@coords[,1],obf_mock_tmp@data[,c(15)])   ##  PNRand  method
ks.test(obf_mock_tmp@coords[,2],obf_mock_tmp@data[,c(16)])
abs(cor(obf_mock_tmp@coords[,1],obf_mock_tmp@coords[,2]) -
      cor(obf_mock_tmp@data[,c(15)], obf_mock_tmp@data[,c(16)]))

ks.test(obf_mock_tmp@coords[,1],obf_mock_tmp@data[,c(17)])   ##  PNMix  method
ks.test(obf_mock_tmp@coords[,2],obf_mock_tmp@data[,c(18)])
abs(cor(obf_mock_tmp@coords[,1],obf_mock_tmp@coords[,2]) -
      cor(obf_mock_tmp@data[,c(17)], obf_mock_tmp@data[,c(18)]))

ks.test(obf_mock_tmp@coords[,1],obf_mock_tmp@data[,c(19)])   ##  PDonut  method
ks.test(obf_mock_tmp@coords[,2],obf_mock_tmp@data[,c(20)])
abs(cor(obf_mock_tmp@coords[,1],obf_mock_tmp@coords[,2]) -
      cor(obf_mock_tmp@data[,c(19)], obf_mock_tmp@data[,c(20)]))

ks.test(obf_mock_tmp@coords[,1],obf_mock_tmp@data[,c(21)])   ##  PDensity  method
ks.test(obf_mock_tmp@coords[,2],obf_mock_tmp@data[,c(22)])
abs(cor(obf_mock_tmp@coords[,1],obf_mock_tmp@coords[,2]) -
      cor(obf_mock_tmp@data[,c(21)], obf_mock_tmp@data[,c(22)]))

ks.test(obf_mock_tmp@coords[,1],obf_mock_tmp@data[,c(23)])   ##  PAHilb  method
ks.test(obf_mock_tmp@coords[,2],obf_mock_tmp@data[,c(24)])
abs(cor(obf_mock_tmp@coords[,1],obf_mock_tmp@coords[,2]) -
      cor(obf_mock_tmp@data[,c(23)], obf_mock_tmp@data[,c(24)]))


ks.test(obf_mock_tmp@coords[,1],obf_mock_tmp@data[,c(25)])   ##  PDonut_AHilb  method
ks.test(obf_mock_tmp@coords[,2],obf_mock_tmp@data[,c(26)])
abs(cor(obf_mock_tmp@coords[,1],obf_mock_tmp@coords[,2]) -
      cor(obf_mock_tmp@data[,c(25)], obf_mock_tmp@data[,c(26)]))
####################################################################################

#################################################################
## Correlation Alteration Analysis
## total correlatione TCA
##################################################################
library(psych)
## correlation between Soil related attributes and original coordinates
pairs.panels(cbind(obf_mock_tmp@coords[,c(1,2)],obf_mock_tmp@data[,c(1,2,3,4)]), cex.labels = 1.7,
             method = "pearson", # correlation method
             hist.col = "#00AFBB",
             density = FALSE,  # show density plots
             ellipses = FALSE, # show correlation ellipses
             cex.cor = 2
)
## correlation between Heird related attributes and original coordinates
pairs.panels(cbind(obf_mock_tmp@coords[,c(1,2)],obf_mock_tmp@data[,c(5,6,7,8)]), cex.labels = 1.7,
             method = "pearson", # correlation method
             hist.col = "#00AFBB",
             density = FALSE,  # show density plots
             ellipses = FALSE, # show correlation ellipses
             cex.cor = 2
)
## correlation between Soil related attributes and obfuscated coordinates for each methods 
## for example here for Pdt_AH method
pairs.panels(obf_mock_tmp@data[,c(25,26,1,2,3,4)], cex.labels = 1.7,
             method = "pearson", # correlation method
             hist.col = "#00AFBB",
             density = FALSE,  # show density plots
             ellipses = FALSE, # show correlation ellipses
             cex.cor = 2
)
## correlation between herd related attributes and obfuscated coordinates for each methods 
## for example here for Pdt_AH method
pairs.panels(obf_mock_tmp@data[,c(25,26,5,6,7,8)], cex.labels = 1.7,
             method = "pearson", # correlation method
             hist.col = "#00AFBB",
             density = FALSE,  # show density plots
             ellipses = FALSE, # show correlation ellipses
             cex.cor = 2
)

#################################################################
## Displacement statistical summary & Displacement Distribution Analysis 
## apply following function for different methods, create a 
## excel sheet called 'Distance' and 'Summary', and  add the result 
## see 'summary_mockdata' excel file sheets 
###################################################################
##  returns percentage of obfuscated points in specific distance and statistical summary
##  for different values of distance in (500,1k,2k,3k,4k,5k,10k,15k,20k,25k) 
##  ## input : data, distance, method) 
poly_sec_test_near <- function(input_data, dist,m){
  start <- Sys.time()
  pnt <- input_data
  d <- list()
  d[[1]] <- 0
  d[[2]] <- pointDistance(pnt@coords,cbind(pnt$omax_x5,pnt$omax_y5), lonlat = FALSE)
  d[[3]] <- pointDistance(pnt@coords,cbind(pnt$oave_x5,pnt$oave_y5), lonlat = FALSE)
  
  d[[4]] <- pointDistance(pnt@coords,cbind(pnt$dt_orand_x,pnt$dt_orand_y), lonlat = FALSE)
  d[[5]] <- pointDistance(pnt@coords,cbind(pnt$denorandk11k_x,pnt$denorandk11k_y), lonlat = FALSE)
  
  d[[6]] <- pointDistance(pnt@coords,cbind(pnt$hoave_x,pnt$hoave_y), lonlat = FALSE)
  d[[7]] <- pointDistance(pnt@coords,cbind(pnt$dt_hrand_x,pnt$dt_hrand_y), lonlat = FALSE)
  
  p <- ggplot(as.data.frame(d[[m]]), aes(x= d[[m]])) + 
    geom_histogram(color="black", fill="white", bins = 200) 
  p <- p + geom_vline(aes(xintercept=median (d[[m]])),
                      color="red", linetype="dashed", size=1.5)
  p <-p + geom_vline(aes(xintercept= quantile(d[[m]])[2] ),
                     color="yellow", size=2)
  p <-p + geom_vline(aes(xintercept= quantile(d[[m]])[4] ),
                     color="yellow", size=2)
  p <- p + xlab("Distance between original and obfuscated point") + ylab("Frequency")
  p <- p + theme(axis.text=element_text(size= 24, face="bold"),
                 axis.title=element_text(size= 24,face="bold"))
  
  print(p)
  q <- quantile(d[[m]])
  print(paste('method' , i ,'Q0 ',round(q[1]),'Q1',round(q[2]),'median',
              round(q[3]), 'Q3', round(q[4]), 'max_Q4' ,round(q[5]), 'diff',round(q[4]- q[2]) ))
  
  print(paste('method' , m ,'min ',round(min(d[[m]])),'max',round(max(d[[m]])),'median' ,
              round(median(d[[m]])),
              'mean',round(mean(d[[m]])), 'sd',round(sd(d[[m]]))))
  dif <-  dist >= d[[m]]
  print(paste('num of point inside its plot', length(dif[dif == TRUE]),
              '% ' ,round(100 * length(dif[dif == TRUE])/ nrow(pnt),2 )))
  return(d)
}

#example
d2 <- poly_sec_test_near(obf_mock_tmp,500,7)

#################################################################
##  K-anonymity Satisfaction Analysis 
## apply following function for different methods, create a 
## excel sheet called 'PSatisfy_k' and add the result 
## see 'summary_mockdata' excel file sheet 'PSatisfy_k'
###################################################################
##  returns percentage of obfuscated points satisfied k-anonymity
##  for different values of k in (5,6,7,8,9,10,15,20,25) 
##  ## input : data, maximum k-anonymity (25), start from nr, number of rows, method) 
Poly_sec_test_k_list <- function(input_data,k,nr,t,m){
  start <- Sys.time()
  pnt <- input_data
  crs(pnt) <- CRS("+init=epsg:2157")
  pnt <- st_as_sf(pnt)
  kI <- c(5,6,7,8,9,10,15,20,25)
  num_not_k <- c(0,0,0,0,0,0,0,0,0)
  num_k <- c(0,0,0,0,0,0,0,0,0)
  nt <- nr + t -1
  for (p in nr:nt){
    print(p)
    d = case_when(
      m == 2 ~ pointDistance(input_data @coords[p,],cbind(input_data$omax_x5[p],input_data$omax_y5[p]), lonlat = FALSE),
      m == 3 ~ pointDistance(input_data@coords[p,],cbind(input_data$oave_x5[p],input_data$oave_y5[p]), lonlat = FALSE),
      m == 4 ~ pointDistance(input_data@coords[p,],cbind(input_data$dt_orand_x[p],input_data$dt_orand_y[p]), lonlat = FALSE),
      m == 5 ~ pointDistance(input_data@coords[p,],cbind(input_data$denorandk11k_x[p],input_data$denorandk11k_y[p]), lonlat = FALSE),
      m == 6 ~  pointDistance(input_data@coords[p,],cbind(input_data$hoave_x[p],input_data$hoave_y[p]), lonlat = FALSE),
      #   
      m == 7 ~ pointDistance(input_data@coords[p,],cbind(input_data$dt_hrand_x[p],input_data$dt_hrand_y[p]), lonlat = FALSE), 
    )
    if (d == 0)
      d <- 1
    d <- d + pnt$maxd_edge[p]
    center_buf1 <- st_buffer(pnt$geometry[p],d)
    count_buf1 <- st_intersection(pnt,center_buf1)
    if (nrow(count_buf1) < min(kI)){
      num_not_k[1:9] <- num_not_k[1:9] +1
    }
    else{
      if (nrow(count_buf1) > 50)
        ##be sure number of polygon is greater than k 
        num_poly <- k+1
      else
        num_poly <- 0
      i <- 1
      while(num_poly <= k & i <= nrow(count_buf1)){
        tmp_shape <- readWKB(count_buf1$plot_shape[i])
        g <- length( tmp_shape@polygons[[1]]@plotOrder)
        jj <- 1
        continuel <- TRUE
        while(continuel & jj <= g){
          tmp_shape1 <- SpatialPolygons(list(Polygons(list(tmp_shape@polygons[[1]]@Polygons[[jj]]),ID=1)))
          tmp_shape1 <- st_as_sf(tmp_shape1)
          st_crs(tmp_shape1) <- st_crs(pnt)
          tmp_ntersection <- st_intersection(center_buf1,tmp_shape1)
          if(length(tmp_ntersection) > 0 ){
            continuel <- FALSE
          }
          jj <- jj +1
        }
        i <- i + 1
        if (round(st_area(tmp_ntersection),2) == round(st_area(tmp_shape1),2))
          num_poly <- num_poly+1
      }
      for(j in 1:9){
        if (num_poly < kI[j] )
          num_not_k[j] <- num_not_k[j] +1
        else
          num_k[j] <- num_k[j] +1
      }
    }
  }
  print(paste('num of point satisfy K-anonymity', num_k,
              '% ' ,round(100 * num_k/ nrow(pnt),2) ))
  num_k <- round(100 * num_k/ nrow(pnt),2)
  print(Sys.time()-start)
  return(num_k)
}
## for example this takes around 6 hours to be completed 
## to check and see how it works you can apply it for part of input file or 
## small values of k  
##example for just 100 rows 
num_ktmp6 <- Poly_sec_test_k_list(obf_mock_tmp,25,1,100,6)
## or for all data
num_ktmp_7 <- Poly_sec_test_k_list(obf_mock_tmp,25,1,nrow(obf_mock_tmp),7)

##################################################################################
### kmeans clustering
##################################################################################
#### elbow method to select number of cluster

set.seed(123)
# Compute and plot wss for k = 2 to k = 15.
k.max <- 12
data <- obf_mock_tmp@coords[,c(1,2)]

wss <- sapply(1:k.max, 
              function(k){kmeans(data, k, nstart=50,iter.max = 12 )$tot.withinss})
wss
plot(1:k.max, wss,
     type="b", pch = 19, frame = FALSE, 
     xlab="Number of clusters K",
     ylab="Total within-clusters sum of squares")

png("Fig7_600.png", units="in", width=12, height=8, dpi =600)
tiff('Fig7_600.tiff', units="in", width=12, height=8, res=600, compression = 'lzw')
################################################################
###  kmeans clustering method for k(when number of cluster is 4)
##################################################################

mycol <- c('blue','red','green','purple','yellow','gray')
#####  clusters based on original coordinates

clxy <- kmeans(obf_mock_tmp@coords[,c(1,2)],4,nstart = 10)
obf_mock_tmp$clxy <- as.factor(clxy$cluster)

plot(Corkt)
for (i in 1: nrow(obf_mock_tmp))
  points(obf_mock_tmp@coords[i,1],obf_mock_tmp@coords[i,2],
         cex=.1, pch=19, col= mycol[obf_mock_tmp$clxy[i]])
###############################################################
#following process was applied for all methods

clrand <- kmeans(obf_mock_tmp@data[,c(15,16)],4,nstart = 10)
obf_mock_tmp$tclrand <- as.factor(clrand$cluster)
##  plot clustered obfuscated points 
plot(Corkt)
for (i in 1: nrow(obf_mock_tmp))
  points(obf_mock_tmp$omax_x5[i], obf_mock_tmp$omax_y5[i],
         cex=.1, pch=19, col= mycol[obf_mock_tmp$tclrand[i]])

#### compare the plot with clustered original points and  
#### change the cluster number to be the same as original by following code
## this can be different at any run due the randomness of process

obf_mock_tmp$clrand = case_when(
  obf_mock_tmp$tclrand   == 1 ~  3,
  obf_mock_tmp$tclrand   == 2 ~  1,
  obf_mock_tmp$tclrand   == 3 ~  4,
  obf_mock_tmp$tclrand   == 4 ~  2,
)
####  plot clustered obfuscated points after update and compare with original one and see 
#### the cluster number are the same
plot(Corkt)
for (i in 1: nrow(obf_mock_tmp))
  points(obf_mock_tmp$omax_x5[i], obf_mock_tmp$omax_y5[i],
         cex=.1, pch=19, col= mycol[obf_mock_tmp$clrand[i]])

####   find the number and percentage of misclustered points 
round(100 *  nrow(obf_mock_tmp[unique(obf_mock_tmp$plotUID),]
                  [obf_mock_tmp$clxy != obf_mock_tmp$clrand ,]) /
        nrow(obf_mock_tmp[unique(obf_mock_tmp$plotUID),]),2)
### delete column temporary cluster number (tclrand) first check the column number
obf_mock_tmp <- obf_mock_tmp[,-(28)]

########################################################################
## doing the same thing for all methods and for example the last method Pdt_AH
cldtAH <- kmeans(obf_mock_tmp@data[,c(25,26)],4,nstart = 10)
obf_mock_tmp$tcldtAH <- as.factor(cldtAH$cluster)
##  plot clustered obfuscated points 
plot(Corkt)
for (i in 1: nrow(obf_mock_tmp))
  points(obf_mock_tmp$dt_hrand_x[i], obf_mock_tmp$dt_hrand_y[i],
         cex=.1, pch=19, col= mycol[obf_mock_tmp$tcldtAH[i]])

obf_mock_tmp$cldtAH = case_when(
  obf_mock_tmp$tcldtAH  == 1 ~  3,
  obf_mock_tmp$tcldtAH  == 2 ~  2,
  obf_mock_tmp$tcldtAH  == 3 ~  4,
  obf_mock_tmp$tcldtAH  == 4 ~  1,
)

####   find the number and percentage of misclustered points 
round(100 *  nrow(obf_mock_tmp[unique(obf_mock_tmp$plotUID),]
                  [obf_mock_tmp$clxy != obf_mock_tmp$cldtAH ,]) /
        nrow(obf_mock_tmp[unique(obf_mock_tmp$plotUID),]),2)
### delete column temporary cluster number (tcldtAH) first check the column number
obf_mock_tmp <- obf_mock_tmp[,-(34)]
###################################################
