require(entropy)
require(plyr)

roundSensors <- function(x) {
    cn <- colnames(x)
    rdf <- data.frame(x)
    for(i in c(1:ncol(x))) {
        rdf[,i] <- switch(cn[i], Temperature=round(x[,i],1), Light_level=round(x[,i],1), Sound_level=round(x[,i]), Humidity=round(x[,i]), CO2_concentration = round_any(x[,i], 10))
    }
    return(rdf)
}

removeHeaders <- function(x) {
    df <- data.frame(t=rep(0, nrow(x)))
    cols <- c("Temperature", "Light_level", "Humidity", "Sound_level", "CO2_concentration")
    for(i in c(1:ncol(x))) {
       if(colnames(x)[i] %in% cols) {
           df <- cbind(df, x[,i])
           colnames(df)[ncol(df)] <- colnames(x)[i]
       }
    }
    return(df[2:ncol(df)])
}

data <- read.csv(commandArgs(T)[1])
#data <- read.csv('trl_kitchen.csv')
#remove duff cols
#end <- grep("^Dig\\w", colnames(data))[1] - 1
#data <- data[,2:end]
#round sensor values to smooth out precision errors
data <- removeHeaders(data)
data <- roundSensors(data)
N <- ncol(data)
b <- rep("test", (N*(N-1))/2)
df <- data.frame(v1=b, v2=b, mi=0, uc1=0, uc2=0, stringsAsFactors=F)
k <- 1 
for(i in c(1:(ncol(data)-1))) {
    for (j in c((i+1):ncol(data))) {
        #create a mini data frame
        t <- data[,c(i,j)]
        t <- t[,order(names(t))]
        #he <- sort(c(colnames(data)[i], colnames(data)[j]))
        df$v1[k] <- names(t)[1]
        df$v2[k] <- names(t)[2]        
        df$mi[k] <- entropy(table(t[,1], t[,1]))
        df$uc1[k] <- df$mi[k]/entropy(t[,1])
        df$uc2[k] <- df$mi[k]/entropy(t[,2])
        k <- k + 1
    }
}

write.table(df, sep=",", file="mi.csv", append=T, quote=F, row.names=F, col.names=F)



