genetic

genetic algorithm framework
git clone [email protected]:dracuxan/genetic.git
Log | Files | Refs | README

one_max.exs (1236B)


      1 defmodule OneMax do
      2   alias Types.Chromosome
      3   @behaviour Problem
      4   @max_n 64
      5 
      6   @impl true
      7   def genotype do
      8     genes = Enum.map(1..@max_n, fn _ -> Enum.random(0..1) end)
      9     %Chromosome{genes: genes, size: @max_n}
     10   end
     11 
     12   @impl true
     13   def fitness_function(chromosome) do
     14     Enum.sum(chromosome.genes)
     15   end
     16 
     17   @impl true
     18   def terminate?(population, _generation) do
     19     best = Enum.max_by(population, &OneMax.fitness_function/1)
     20     best.fitness == @max_n
     21   end
     22 end
     23 
     24 {soln, generation} =
     25   Genetic.run(
     26     OneMax,
     27     population_size: 100,
     28     selection_rate: 0.8,
     29     mutation_rate: 0.01,
     30     survival_rate: 0.2,
     31     selection_type: &Toolbox.Selection.elite/2,
     32     crossover_type: &Toolbox.Crossover.uniform/3,
     33     mutation_type: &Toolbox.Mutation.scramble/2
     34   )
     35 
     36 IO.puts("\nfinal answer: #{inspect(soln)}")
     37 IO.puts("generations passed: #{generation}")
     38 
     39 # {_, tgs} = Utilities.Statistics.lookup(generation)
     40 # IO.inspect(tgs)
     41 
     42 stats =
     43   :ets.tab2list(:statistics)
     44   |> Enum.sort_by(fn {gen, _stat} -> gen end)
     45   |> Enum.map(fn {gen, stats} -> [gen, stats.mean_fitness] end)
     46 
     47 {:ok, _} =
     48   Gnuplot.plot(
     49     [
     50       [:set, :title, "mean fitness versus generation (one_max)"],
     51       [:plot, "-", :with, :line]
     52     ],
     53     [stats]
     54   )