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.

89 lines
2.2 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
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, popul=c()) {
  29. df <- data.frame( generation = integer()
  30. ,individual = integer()
  31. ,fitness = double()
  32. ,relfitness = double()
  33. ,a = double()
  34. ,b = double())
  35. if(length(popul) == 0) {
  36. popul <- linscale.initpopulation(10)
  37. }
  38. for(a in avals) {
  39. for(b in bvals) {
  40. dftmp <- linscale.tracegens(popul, a, b, n)
  41. dftmp["a"] <- a
  42. dftmp["b"] <- b
  43. df <- rbind(df, dftmp)
  44. }
  45. }
  46. return(df)
  47. }
  48. linscale.plot <- function(df) {
  49. pdf(file="linscale.pdf", onefile=TRUE)
  50. for(g in unique(df$generation)) {
  51. p <- ggplot(data=df[df$generation == g, ]) +
  52. geom_col(aes(x=individual, y=relfitness)) +
  53. facet_grid(b ~ a, labeller = label_both) +
  54. labs(title=sprintf("generation: %i", g))
  55. print(p)
  56. }
  57. dev.off()
  58. }
  59. linscale.animate <- function(df) {
  60. anim <- ggplot(data=df) +
  61. geom_col(aes(x=individual, y=relfitness)) +
  62. facet_grid(b ~ a, labeller = label_both) +
  63. labs(title="generation: {closest_state}") +
  64. transition_states(generation)
  65. anim_save("linescale.gif", animation=anim)
  66. }
  67. data.population <- linscale.initpopulation(10)