package jcgp.backend.modules.mutator; import jcgp.backend.function.Function; import jcgp.backend.population.Chromosome; import jcgp.backend.population.MutableElement; import jcgp.backend.population.Node; import jcgp.backend.population.Output; import jcgp.backend.resources.Resources; import jcgp.backend.resources.parameters.DoubleParameter; import jcgp.backend.resources.parameters.Parameter; import jcgp.backend.resources.parameters.ParameterStatus; public class PointMutator implements Mutator { private DoubleParameter mutationRate; public PointMutator(final Resources resources) { mutationRate = new DoubleParameter(50, "Percent mutation", false, false) { @Override public void validate(double newValue) { if (newValue <= 0 || newValue > 100) { status = ParameterStatus.INVALID; status.setDetails("Mutation rate must be > 0 and <= 100"); } else if ((int) ((newValue / 100) * resources.getDouble("nodes")) <= 0) { status = ParameterStatus.WARNING; status.setDetails("With mutation rate " + mutationRate.get() + ", 0 genes will be mutated."); } else { status = ParameterStatus.VALID; } } }; } @Override public void mutate(Chromosome chromosome, Resources resources) { int mutations = (int) ((mutationRate.get()) * ((((resources.getDouble("nodes")) + (resources.getDouble("outputs")))) / 100)); for (int i = 0; i < mutations; i++) { MutableElement m = chromosome.getRandomMutableElement(); if (m instanceof Output) { m.setConnection(0, chromosome.getRandomConnection()); } else if (m instanceof Node) { int geneType = resources.getRandomInt(1 + resources.getInt("arity")); if (geneType < 1) { Function f = resources.getRandomFunction(); ((Node) m).setFunction(f); } else { m.setConnection(resources.getRandomInt(resources.getInt("arity")), chromosome.getRandomConnection(((Node) m).getColumn())); } } } } @Override public Parameter[] getLocalParameters() { return new Parameter[] {mutationRate}; } @Override public String toString() { return "Point mutation"; } }