genetic

genetic algorithm framework
git clone igris.git:dracuxan/genetic.git
Log | Files | Refs | README

commit dd4cd4b3e88d8fe9c3076aae51086e08ca87df16
parent 1334fb37eec2293ba065e1fc8e2009b2925a2ecb
Author: dracuxan <[email protected]>
Date:   Sat,  2 May 2026 22:39:23 +0530

fix: gnuplot

Diffstat:
Mlib/toolbox/crossover.ex | 16++--------------
Mscripts/sin.exs | 66++++++++++++++++--------------------------------------------------
2 files changed, 18 insertions(+), 64 deletions(-)

diff --git a/lib/toolbox/crossover.ex b/lib/toolbox/crossover.ex @@ -81,20 +81,8 @@ defmodule Toolbox.Crossover do end defp utils_constraints(p, min, max) do - p = - if p > max do - max - else - p - end - - p = - if p < min do - min - else - p - end - + p = if p > max, do: max, else: p + p = if p < min, do: min, else: p p end diff --git a/scripts/sin.exs b/scripts/sin.exs @@ -10,7 +10,7 @@ defmodule Sin do @impl true def fitness_function(chromosome) do - x = Enum.at(chromosome.genes, 0) + x = hd(chromosome.genes) Math.sin(x) - 0.2 * abs(x) end @@ -20,9 +20,10 @@ defmodule Sin do generation == 10 end - def plot_generation(population, generation) do + defp plot_generation(population, generation) do curve = - Enum.map(-10..10, fn x -> + Enum.map(-100..100, fn x -> + x = x / 10.0 [x, :math.sin(x) - 0.2 * abs(x)] end) @@ -34,54 +35,22 @@ defmodule Sin do best = hd(population) best_point = [[hd(best.genes), best.fitness]] - Gnuplot.plot( - [ - [:set, :title, "Generation #{generation}"], - [:set, :xrange, ~c"[-10:10]"], - [:set, :yrange, ~c"[-3:1]"], + {:ok, _} = + Gnuplot.plot( [ - :plot, - "-", - :with, - :lines, - :lt, - 2, - :title, - "sin(x) - 0.2|x|", - "-", - :with, - :points, - :pt, - 7, - :ps, - 1.5, - :lc, - "orange", - :title, - "Population", - "-", - :with, - :points, - :pt, - 5, - :ps, - 2, - :lc, - "green", - :title, - "Best" - ] - ], - [ - curve, - points, - best_point - ] - ) + [:set, :title, "Generation #{generation}"], + Gnuplot.plots([ + ["-", :with, :lines, :lt, 2, :title, "sin(x) - 0.2|x|"], + ["-", :with, :points, :pt, 7, :ps, 1.5, :lc, "orange", :title, "Population"], + ["-", :with, :points, :pt, 5, :ps, 2, :lc, "green", :title, "Best"] + ]) + ], + [curve, points, best_point] + ) end end -{soln, gen} = +{_soln, _gen} = Genetic.run( Sin, population_size: 10, @@ -94,6 +63,3 @@ end crossover_type: &Toolbox.Crossover.blend/3, mutation_type: &Toolbox.Mutation.gaussian/2 ) - -IO.puts("\nfinal answer: #{inspect(soln)}") -IO.puts("generations passed: #{gen}")