# fastcluster package, the fastcluster::hclust() function 
# automatically replaces the slower stats::hclust() function
# whenever hclust() is called.
# install.packages("fastcluster") 
require(fastcluster) 

# The igraph package is necessary to view simplicial complexes
# (undirected graph) resulting from mapper1D().

library(igraph)



set.seed(43)
x <- rnorm(1000)
y <- rnorm(1000)
mydata <- data.frame(x,x)
d <- dist(mydata, method = 'euclidean')

pca <- prcomp(mydata) # pca as a fulter function
pca1 <- (as.matrix(mydata) %*% pca$rotation)[,1] #PCA 1
pca2 <- (as.matrix(mydata) %*% pca$rotation)[,2] #PCA 2
mydata.pca12 <- cbind(pca1,pca2)

m <- mapper1Dnew3(distance_matrix = d, 
                   filter_values = unlist(pca1), 
                   num_intervals = 5, 
                   percent_overlap = 49, 
                   hclustering = "single",
                   num_bins_when_clustering = 10)

# create and plot mapper graph
vertexLabel <- sapply(m$points_in_vertex,length)
vertexSize <- 50*vertexLabel/max(vertexLabel)

colnames(m$adjacency)<-vertexLabel
g <- graph_from_adjacency_matrix(m$adjacency,
                      add.colnames='label', 
                      mode="undirected",
                      weighted = TRUE)
width <- 10*E(g)$weight/max(E(g)$weight)
l <- layout.fruchterman.reingold(g, niter=5000)

plot.igraph(g,layout=l)

plot.igraph(g,layout=l,
        vertex.label=V(g)$name,
        vertex.size = vertexSize,
        edge.label=E(g)$weight,
        edge.width=width
         )

