library("fpc")

##' Angle feature
##'
##' @param x A TSP instance
feature_cluster <- function(x, epsilon) {
    d <- as.vector(dist(x))
    d <- d[d > 0] ## Really strip 0 distances?
    q <- quantile(d, epsilon)
    ## do the clustering
    fit <- dbscan(x, q, showplot=FALSE)
    ## Skip singleton clusters:
    real_clusters <- which(fit$cluster > 0)

    cm <- fit$cluster[real_clusters]
    coords <- x[real_clusters, , drop=FALSE]
    if (length(cm) > 0) {
      distances <- sapply(unique(cm), function(cluster) {
        cluster_coords <- coords[cm == cluster, , drop=FALSE]
        centroid <- colMeans(cluster_coords)
        apply(cluster_coords, 1, function(point) {
          v <- point - centroid
          sqrt(sum(v * v))
        })
      })
      distances <- unlist(distances)
      res <- list(number_of_clusters=length(unique(cm)),
                  mean_distance_to_centroid=mean(distances) 
                  )
    } else {
      res <- list(number_of_clusters=0,
                  mean_distance_to_centroid=NA
                  )
    }
    prefix <- sprintf("cluster_%02ipct", floor(epsilon * 100))
    names(res) <- paste(prefix, names(res), sep="_")
    res
}
