# The MIT License
# Copyright (c) 2007 The GGobi Foundation
# http://www.ggobi.org/book/code-license.txt


# Read data, and standardize before running SOM
d.music<-read.csv("music-sub.csv",row.names=1)
d.music.std<-cbind(d.music[,c(1,2)],apply(d.music[,-c(1,2)],2,f.std.data))

# Utility functions
f.std.data<-function(x) {
  return((x-mean(x,na.rm=T))/sd(x,na.rm=T))
}

# Load libraries
library(rggobi)
library(som)

# Run SOM
music.som<-som(d.music.std[,-c(1:2)],6,6,neigh="bubble",rlen=100)
music.som<-som(d.music.std[,-c(1:2)],6,6,neigh="bubble",rlen=1000)

# Set up data for ggobi - data needs to have any labels in the first few columns
f.ggobi.som<-function(x,x.som) {
  xmx<-jitter(x.som$visual$x,factor=2)
  xmy<-jitter(x.som$visual$y,factor=2)
  ncols<-ncol(x)
  x.ggobi<-cbind(x,xmx,xmy)
  dimnames(x.ggobi)[[2]][ncols+1]<-"Map 1"
  dimnames(x.ggobi)[[2]][ncols+2]<-"Map 2"
  x.grid<-cbind(x.som$code,x.som$code.sum[,1:2])
  dimnames(x.grid)[[2]]<-dimnames(x.ggobi)[[2]]
  x.clust<-rbind(x.ggobi,x.grid)
}
f.ggobi.som.net<-function(x.som) {
  x.net<-NULL
  for (i in 1:x.som$xdim) {
    for (j in 1:x.som$ydim) {
        if (j<x.som$ydim) x.net<-rbind(x.net,c((i-1)*x.som$xdim+j,(i-1)*x.som$xdim+j+1))
    if (i<x.som$xdim) x.net<-rbind(x.net,c((i-1)*x.som$xdim+j,i*x.som$xdim+j))
    }
  }
  return(x.net)
}

d.music.som<-f.ggobi.som(d.music.std[,-c(1,2)],music.som)
d.music.som<-list(Songs=factor(c(as.character(row.names(d.music)),rep("0",36))),
  Artist=factor(c(as.character(d.music[,1]),rep("0",36))),
  Type=factor(c(as.character(d.music[,2]),rep("0",36))),
  LVar=d.music.som[,1],LAve=d.music.som[,2],LMax=d.music.som[,3],
  LFEner=d.music.som[,4],LFreq=d.music.som[,5],Map.1=d.music.som[,6],
  Map.2=d.music.som[,7])
gg<-ggobi(d.music.som)
g<-gg[1]

#load edges 
d.music.som.net<-f.ggobi.som.net(music.som)
edges(g) <- d.music.som.net + 62

# Color points according to type of music, and som net
gcolor<- rep(8,98)
gcolor[d.music.som$Type=="Rock"]<-6
gcolor[d.music.som$Type=="Classical"]<-4
gcolor[d.music.som$Type=="New wave"]<-1
glyph_color(g)<-gcolor


# Write data
source("writeXML.R")
f.writeXML(d.music.som,
  "music-som.xml",
  data.num=2,dat1.id<-c(1:dim(d.music.som)[1]),
  dat2=cbind(c(1:60),c(1:60)),
  dat2.source=d.music.som.net[,1],
  dat2.destination=d.music.som.net[,2],
  dat2.name="SOM",dat2.id=paste(rep("l",60),c(1:60)))
