Distance metrics

# distance functions
library(reshape2)
library(plotly)
## Loading required package: ggplot2
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
L_norm <- function(norm){
  function(x, y ){
    if (norm %in% 'Inf'){
      return(pmax(abs(x), abs(y)))
    }else{
      return((abs(x)**(norm) + abs(y)**(norm)) ** (1/norm))
    }
  }
}


# Generate a distance matrix
distance_metric <- function(x.val, y.val, dist.fun){
  #x.val <- seq(-5 , 5, length.out = 100)
  #y.val <- seq(-5 , 5, length.out = 100)
  # dist.fun <- L_norm('Inf')
  row <- length(x.val)
  col <- length(y.val)
  dist.matrix <- matrix(rnorm(row * col), ncol = col)

  rownames(dist.matrix) <- x.val
  colnames(dist.matrix) <- y.val
  for (x in x.val){
    for (y in y.val){
      dist.matrix[as.character(x), as.character(y)] <- dist.fun(x, y)
    }
  }


  dist.df <- expand.grid(x = x.val, y = y.val)
  dist.df$z <- dist.fun(dist.df$x, dist.df$y)

  return(list(matrix = dist.matrix, df = dist.df))
}





x.val <- seq(-5 , 5, length.out = 100)
y.val <- seq(-5 , 5, length.out = 100)

L0.5 <-  distance_metric(x.val, y.val, L_norm(0.5))
L0.5.df <- L0.5$df
L0.5.mtx <- L0.5$matrix


L1 <-  distance_metric(x.val, y.val, L_norm(1))
L1.df <- L1$df
L1.mtx <- L1$matrix

L2 <-  distance_metric(x.val, y.val, L_norm(2))
L2.df <- L2$df
L2.mtx <- L2$matrix

L.Inf <-  distance_metric(x.val, y.val, L_norm('Inf'))
L.Inf.df <- L.Inf$df
L.Inf.mtx <- L.Inf$matrix

plot_ly(x= L1.df$x, y = L1.df$y, z = L1.df$z,  type = "contour")
plot_ly(x= L2.df$x, y = L2.df$y, z = L2.df$z,  type = "contour")
plot_ly(x= L.Inf.df$x, y = L.Inf.df$y, z = L.Inf.df$z,  type = "contour")
plot_ly(x= L0.5.df$x, y = L0.5.df$y, z = L0.5.df$z,  type = "contour")

3D