-
-
Save ruippeixotog/4049216 to your computer and use it in GitHub Desktop.
Genetic Algorithms in Scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import annotation.tailrec | |
import util.Random | |
object main extends App { | |
val target = "as armas e os baroes assinalados" | |
val genePool = Array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',' ') | |
def fitness(src: String): Double = src.zip(target).foldRight(0.0f) { (e, acc) => e match { | |
case (s, t) if s == t => acc + 1 | |
case _ => acc | |
} | |
} | |
val petri = new GeneticExploration[Char, String](0.01, 500, genePool, cs => new String(cs.toArray), fitness, _.exists(_ == target)) | |
println(petri.evolution(petri.randomPool(500, target))) | |
} | |
class GeneticExploration[Gene, Specimen <% Iterable[Gene]] | |
(val mutation: Double, val population: Int, genePool: Array[Gene], | |
specimenBuilder: Iterable[Gene] => Specimen, | |
fitnessF: Specimen => Double, | |
stopCondition: List[Specimen] => Boolean) { | |
type Pool = List[Specimen] | |
type MatePool = List[(Specimen, Double)] | |
def randomGenes: Stream[Gene] = genePool(Random.nextInt(genePool.length)) #:: randomGenes | |
def newSpecimen(len: Int): Specimen = specimenBuilder(randomGenes.take(len)) | |
def randomPool(size: Int, archetype: Specimen): Pool = (1 to size).map(_ => newSpecimen(archetype.size)).toList | |
def matePool(pool: Pool): MatePool = { | |
val fitnesses = pool.map(fitnessF).toArray | |
pool.zip(renormalize(fitnesses)) | |
} | |
private def renormalize(vector: Array[Double]): Array[Double] = { | |
val sum = vector.sum | |
vector.map(i => if (i == 0) 0 else i / sum) | |
} | |
@tailrec final def monteCarloSelection(matePool: MatePool): Specimen = { | |
val (specimen, fitness) = matePool(Random.nextInt(matePool.length)) | |
if (fitness > Random.nextFloat) specimen else monteCarloSelection(matePool) | |
} | |
def popReproduction(matePool: MatePool): Pool = (1 to population).par.map(_ => crossover(monteCarloSelection(matePool), monteCarloSelection(matePool))).toList | |
def crossover(a: Specimen, b: Specimen): Specimen = specimenBuilder(a.zip(b).map(gene => if (Random.nextFloat >= 0.5) gene._1 else gene._2)) | |
def mutate(s: Specimen) = specimenBuilder(s.map(gene => if (mutation > Random.nextFloat) randomGenes.head else gene)) | |
@tailrec final def evolution(pool: Pool, generation: Int = 0): (Pool, Int) = { | |
val newGeneration = popReproduction(matePool(pool)) | |
if (stopCondition(newGeneration)) (newGeneration, generation) else evolution(newGeneration, generation + 1) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment