source("linear_scaling.R")
library(ggplot2)
library(RColorBrewer)

fittrans.id <- function(popul) {
    return(popul)
}

fittrans.linscale <- function(a, b) {
    return(function(popul) {
        popul[,2] = a * popul[,2] + b

        return(popul)
    })
}

select.fps <- function(popul) {
    relfit <- linscale.relfitness(popul[,2])
    
    filtr <- sample(popul[,1], length(popul[,1]), prob=relfit, replace=TRUE)
    return(popul[filtr,])
}

ev.run <- function(popul, gen, selection, fittrans=fittrans.id) {
    npopul <- length(popul)

    namedpopul <- matrix(c(1:npopul, popul), ncol=2)

    df = data.frame( gen = 0
                    ,fitness = namedpopul[,2]
                    ,ancestor = namedpopul[,1]
                    ,relfit = linscale.relfitness(namedpopul[,2]))

    for(g in 1:gen) {
        namedpopul <- selection(fittrans(namedpopul))

        df = rbind(df, data.frame( gen = g
                                  ,fitness = namedpopul[,2]
                                  ,ancestor = namedpopul[,1]
                                  ,relfit = linscale.relfitness(namedpopul[,2])))
    }

    return(df)
}

ev.plot <- function(df, filename) {
    pdf(file=filename, onefile=TRUE)
    

    for(g in unique(df$gen)) {
        p <- ggplot(data=df[df$gen == g,], aes(x="", y=relfit, fill=factor(ancestor))) +
            geom_bar(stat="identity", width=1) +
            coord_polar("y", start=0) +
            labs(x=NULL, y=NULL, fill="ancestor", title=sprintf("generation: %i", g))

        print(p)
    }

    dev.off()
}

ev.animate <- function(df, filename) {

    anim <- ggplot(data=df, aes(x="", y=relfit, fill=factor(ancestor))) +
        geom_bar(stat="identity", width=1) +
        coord_polar("y", start=0) +
        labs(x=NULL, y=NULL, fill="ancestor", title="generation: {closest_state}") +
        transition_states(gen)

    anim_save(filename, animation=anim)
}
