You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

84 lines
2.1 KiB

3 years ago
  1. library(ggplot2)
  2. library(gganimate)
  3. linscale.initpopulation <- function(n) {
  4. return(runif(10))
  5. }
  6. linscale.scale <- function(population, a, b) {
  7. return(a * population + b)
  8. }
  9. linscale.relfitness <- function(population) {
  10. return(population / sum(population))
  11. }
  12. linscale.tracegens <- function(popul, a, b, n) {
  13. lenpopul <- length(popul)
  14. df <- data.frame( generation = 0
  15. ,individual = 1:lenpopul
  16. ,fitness = popul
  17. ,relfitness = linscale.relfitness(popul)
  18. )
  19. for(i in 1:n) {
  20. popul <- linscale.scale(popul, a, b)
  21. df <- rbind(df, data.frame( generation = i
  22. ,individual = 1:lenpopul
  23. ,fitness = popul
  24. ,relfitness = linscale.relfitness(popul)))
  25. }
  26. return(df)
  27. }
  28. linscale.experiment <- function(avals, bvals, n) {
  29. df <- data.frame( generation = integer()
  30. ,individual = integer()
  31. ,fitness = double()
  32. ,relfitness = double()
  33. ,a = double()
  34. ,b = double())
  35. initpopul <- linscale.initpopulation(10)
  36. for(a in avals) {
  37. for(b in bvals) {
  38. dftmp <- linscale.tracegens(initpopul, a, b, n)
  39. dftmp["a"] <- a
  40. dftmp["b"] <- b
  41. df <- rbind(df, dftmp)
  42. }
  43. }
  44. return(df)
  45. }
  46. linscale.plot <- function(df) {
  47. pdf(file="linscale.pdf", onefile=TRUE)
  48. for(g in unique(df$generation)) {
  49. p <- ggplot(data=df[df$generation == g, ]) +
  50. geom_col(aes(x=individual, y=relfitness)) +
  51. facet_grid(b ~ a, labeller = label_both) +
  52. labs(title=sprintf("generation: %i", g))
  53. print(p)
  54. }
  55. dev.off()
  56. }
  57. linscale.animate <- function(df) {
  58. anim <- ggplot(data=df) +
  59. geom_col(aes(x=individual, y=relfitness)) +
  60. facet_grid(b ~ a, labeller = label_both) +
  61. labs(title="generation: {closest_state}") +
  62. transition_states(generation)
  63. anim_save("linescale.gif", animation=anim)
  64. }