From 02fd2bc7059da416937beb1abe67e5ca60379030 Mon Sep 17 00:00:00 2001 From: Eduardo Pedroni Date: Tue, 1 Apr 2014 23:00:53 +0100 Subject: Settings pane now actually controls the parameters, not much left to do. --- src/jcgp/GUI.java | 169 ----------- src/jcgp/JCGP.java | 170 ++++++++--- .../InsufficientConnectionsException.java | 10 + .../exceptions/InvalidArgumentsException.java | 20 ++ .../backend/exceptions/ManagedModuleException.java | 10 + .../exceptions/ParameterMismatchException.java | 10 + src/jcgp/backend/function/Arithmetic.java | 139 +++++++++ src/jcgp/backend/function/BitwiseLogic.java | 215 +++++++++++++ src/jcgp/backend/function/BooleanLogic.java | 215 +++++++++++++ src/jcgp/backend/function/Function.java | 13 + src/jcgp/backend/function/FunctionSet.java | 74 +++++ src/jcgp/backend/modules/Module.java | 11 + src/jcgp/backend/modules/ModuleStatus.java | 16 + .../backend/modules/ea/EvolutionaryAlgorithm.java | 15 + src/jcgp/backend/modules/ea/MuPlusLambda.java | 80 +++++ .../backend/modules/ea/TournamentSelection.java | 55 ++++ .../backend/modules/fitness/FitnessFunction.java | 11 + src/jcgp/backend/modules/fitness/TestCase.java | 29 ++ .../backend/modules/fitness/TestCaseEvaluator.java | 45 +++ src/jcgp/backend/modules/mutator/Mutator.java | 11 + src/jcgp/backend/modules/mutator/PointMutator.java | 73 +++++ src/jcgp/backend/parameters/BooleanParameter.java | 32 ++ src/jcgp/backend/parameters/DoubleParameter.java | 33 ++ src/jcgp/backend/parameters/IntegerParameter.java | 33 ++ src/jcgp/backend/parameters/Parameter.java | 35 +++ src/jcgp/backend/population/Chromosome.java | 335 +++++++++++++++++++++ src/jcgp/backend/population/Connection.java | 9 + src/jcgp/backend/population/Gene.java | 5 + src/jcgp/backend/population/Input.java | 29 ++ src/jcgp/backend/population/MutableElement.java | 34 +++ src/jcgp/backend/population/Node.java | 112 +++++++ src/jcgp/backend/population/Output.java | 69 +++++ src/jcgp/backend/population/Population.java | 45 +++ src/jcgp/backend/tests/ChromosomeTests.java | 334 ++++++++++++++++++++ src/jcgp/backend/tests/InputTests.java | 47 +++ src/jcgp/backend/tests/NodeTests.java | 196 ++++++++++++ src/jcgp/backend/tests/OutputTests.java | 93 ++++++ src/jcgp/backend/tests/PopulationTests.java | 86 ++++++ .../InsufficientConnectionsException.java | 10 - src/jcgp/exceptions/InvalidArgumentsException.java | 20 -- src/jcgp/exceptions/ManagedModuleException.java | 10 - .../exceptions/ParameterMismatchException.java | 10 - src/jcgp/function/Arithmetic.java | 139 --------- src/jcgp/function/BitwiseLogic.java | 215 ------------- src/jcgp/function/BooleanLogic.java | 215 ------------- src/jcgp/function/Function.java | 13 - src/jcgp/function/FunctionSet.java | 74 ----- src/jcgp/gui/ChromosomePane.java | 28 +- src/jcgp/gui/GUI.java | 211 +++++++++++++ src/jcgp/gui/Messenger.java | 7 - src/jcgp/gui/console/Console.java | 11 + src/jcgp/gui/console/GUIConsole.java | 22 +- src/jcgp/gui/population/GUIGene.java | 6 +- src/jcgp/gui/population/GUIInput.java | 10 +- src/jcgp/gui/population/GUINode.java | 10 +- src/jcgp/gui/population/GUIOutput.java | 27 +- src/jcgp/gui/settings/SettingsPane.java | 116 ++++--- .../settings/parameters/GUIBooleanParameter.java | 34 ++- .../settings/parameters/GUIDoubleParameter.java | 39 +-- .../settings/parameters/GUIIntegerParameter.java | 36 +-- src/jcgp/gui/settings/parameters/GUIParameter.java | 56 +++- src/jcgp/modules/Module.java | 11 - src/jcgp/modules/ModuleStatus.java | 16 - src/jcgp/modules/ea/EvolutionaryAlgorithm.java | 15 - src/jcgp/modules/ea/MuPlusLambda.java | 80 ----- src/jcgp/modules/ea/TournamentSelection.java | 54 ---- src/jcgp/modules/fitness/FitnessFunction.java | 11 - src/jcgp/modules/fitness/TestCase.java | 29 -- src/jcgp/modules/fitness/TestCaseEvaluator.java | 45 --- src/jcgp/modules/mutator/Mutator.java | 11 - src/jcgp/modules/mutator/PointMutator.java | 71 ----- src/jcgp/parameters/BooleanParameter.java | 32 -- src/jcgp/parameters/DoubleParameter.java | 33 -- src/jcgp/parameters/IntegerParameter.java | 33 -- src/jcgp/parameters/Parameter.java | 30 -- src/jcgp/population/Chromosome.java | 335 --------------------- src/jcgp/population/Connection.java | 9 - src/jcgp/population/Gene.java | 5 - src/jcgp/population/Input.java | 29 -- src/jcgp/population/MutableElement.java | 34 --- src/jcgp/population/Node.java | 114 ------- src/jcgp/population/Output.java | 69 ----- src/jcgp/population/Population.java | 45 --- src/jcgp/tests/ChromosomeTests.java | 334 -------------------- src/jcgp/tests/InputTests.java | 47 --- src/jcgp/tests/NodeTests.java | 196 ------------ src/jcgp/tests/OutputTests.java | 94 ------ src/jcgp/tests/PopulationTests.java | 86 ------ 88 files changed, 3157 insertions(+), 2948 deletions(-) delete mode 100644 src/jcgp/GUI.java create mode 100644 src/jcgp/backend/exceptions/InsufficientConnectionsException.java create mode 100644 src/jcgp/backend/exceptions/InvalidArgumentsException.java create mode 100644 src/jcgp/backend/exceptions/ManagedModuleException.java create mode 100644 src/jcgp/backend/exceptions/ParameterMismatchException.java create mode 100644 src/jcgp/backend/function/Arithmetic.java create mode 100644 src/jcgp/backend/function/BitwiseLogic.java create mode 100644 src/jcgp/backend/function/BooleanLogic.java create mode 100644 src/jcgp/backend/function/Function.java create mode 100644 src/jcgp/backend/function/FunctionSet.java create mode 100644 src/jcgp/backend/modules/Module.java create mode 100644 src/jcgp/backend/modules/ModuleStatus.java create mode 100644 src/jcgp/backend/modules/ea/EvolutionaryAlgorithm.java create mode 100644 src/jcgp/backend/modules/ea/MuPlusLambda.java create mode 100644 src/jcgp/backend/modules/ea/TournamentSelection.java create mode 100644 src/jcgp/backend/modules/fitness/FitnessFunction.java create mode 100644 src/jcgp/backend/modules/fitness/TestCase.java create mode 100644 src/jcgp/backend/modules/fitness/TestCaseEvaluator.java create mode 100644 src/jcgp/backend/modules/mutator/Mutator.java create mode 100644 src/jcgp/backend/modules/mutator/PointMutator.java create mode 100644 src/jcgp/backend/parameters/BooleanParameter.java create mode 100644 src/jcgp/backend/parameters/DoubleParameter.java create mode 100644 src/jcgp/backend/parameters/IntegerParameter.java create mode 100644 src/jcgp/backend/parameters/Parameter.java create mode 100644 src/jcgp/backend/population/Chromosome.java create mode 100644 src/jcgp/backend/population/Connection.java create mode 100644 src/jcgp/backend/population/Gene.java create mode 100644 src/jcgp/backend/population/Input.java create mode 100644 src/jcgp/backend/population/MutableElement.java create mode 100644 src/jcgp/backend/population/Node.java create mode 100644 src/jcgp/backend/population/Output.java create mode 100644 src/jcgp/backend/population/Population.java create mode 100644 src/jcgp/backend/tests/ChromosomeTests.java create mode 100644 src/jcgp/backend/tests/InputTests.java create mode 100644 src/jcgp/backend/tests/NodeTests.java create mode 100644 src/jcgp/backend/tests/OutputTests.java create mode 100644 src/jcgp/backend/tests/PopulationTests.java delete mode 100644 src/jcgp/exceptions/InsufficientConnectionsException.java delete mode 100644 src/jcgp/exceptions/InvalidArgumentsException.java delete mode 100644 src/jcgp/exceptions/ManagedModuleException.java delete mode 100644 src/jcgp/exceptions/ParameterMismatchException.java delete mode 100644 src/jcgp/function/Arithmetic.java delete mode 100644 src/jcgp/function/BitwiseLogic.java delete mode 100644 src/jcgp/function/BooleanLogic.java delete mode 100644 src/jcgp/function/Function.java delete mode 100644 src/jcgp/function/FunctionSet.java create mode 100644 src/jcgp/gui/GUI.java delete mode 100644 src/jcgp/gui/Messenger.java create mode 100644 src/jcgp/gui/console/Console.java delete mode 100644 src/jcgp/modules/Module.java delete mode 100644 src/jcgp/modules/ModuleStatus.java delete mode 100644 src/jcgp/modules/ea/EvolutionaryAlgorithm.java delete mode 100644 src/jcgp/modules/ea/MuPlusLambda.java delete mode 100644 src/jcgp/modules/ea/TournamentSelection.java delete mode 100644 src/jcgp/modules/fitness/FitnessFunction.java delete mode 100644 src/jcgp/modules/fitness/TestCase.java delete mode 100644 src/jcgp/modules/fitness/TestCaseEvaluator.java delete mode 100644 src/jcgp/modules/mutator/Mutator.java delete mode 100644 src/jcgp/modules/mutator/PointMutator.java delete mode 100644 src/jcgp/parameters/BooleanParameter.java delete mode 100644 src/jcgp/parameters/DoubleParameter.java delete mode 100644 src/jcgp/parameters/IntegerParameter.java delete mode 100644 src/jcgp/parameters/Parameter.java delete mode 100644 src/jcgp/population/Chromosome.java delete mode 100644 src/jcgp/population/Connection.java delete mode 100644 src/jcgp/population/Gene.java delete mode 100644 src/jcgp/population/Input.java delete mode 100644 src/jcgp/population/MutableElement.java delete mode 100644 src/jcgp/population/Node.java delete mode 100644 src/jcgp/population/Output.java delete mode 100644 src/jcgp/population/Population.java delete mode 100644 src/jcgp/tests/ChromosomeTests.java delete mode 100644 src/jcgp/tests/InputTests.java delete mode 100644 src/jcgp/tests/NodeTests.java delete mode 100644 src/jcgp/tests/OutputTests.java delete mode 100644 src/jcgp/tests/PopulationTests.java (limited to 'src/jcgp') diff --git a/src/jcgp/GUI.java b/src/jcgp/GUI.java deleted file mode 100644 index d81e760..0000000 --- a/src/jcgp/GUI.java +++ /dev/null @@ -1,169 +0,0 @@ -package jcgp; - -import java.util.concurrent.ExecutionException; - -import javafx.application.Application; -import javafx.application.Platform; -import javafx.concurrent.Service; -import javafx.concurrent.Task; -import javafx.scene.Scene; -import javafx.scene.control.Tab; -import javafx.scene.control.TabPane; -import javafx.scene.control.TabPane.TabClosingPolicy; -import javafx.scene.layout.BorderPane; -import javafx.stage.Stage; -import jcgp.JCGP.Resources; -import jcgp.gui.ChromosomePane; -import jcgp.gui.console.GUIConsole; -import jcgp.gui.settings.SettingsPane; - -public class GUI extends Application { - - /* Colours */ - /** NEUTRAL_COLOUR is the colour elements should be when no interaction is occurring - * (no hovering, clicking, dragging or any other form of interaction). */ - public static final String NEUTRAL_COLOUR = "#FFFFFF"; - public static final String HARD_HIGHLIGHT_COLOUR = "#5496FF"; - // 89AAD6 - public static final String MEDIUM_HIGHLIGHT_COLOUR = "#75BAFF"; - public static final String SOFT_HIGHLIGHT_COLOUR = "#C7DFFF"; - // BDFFC2 - public static final String GOOD_SELECTION_COLOUR = "#38C25B"; - // FBFFB8 - public static final String NEUTRAL_SELECTION_COLOUR = "#EDEB72"; - // FF9C9C - public static final String BAD_SELECTION_COLOUR = "#F53D3D"; - - - /* Sizes and distances */ - public static final double RESIZE_MARGIN = 5.0; - - public static final double SETTINGS_WIDTH = 200; - public static final double CONSOLE_HEIGHT = 100; - - public static final double WRAP_WIDTH = 90; - - private static JCGP cgp; - public static Resources resources; - - private BorderPane leftPane; - private BorderPane window; - - private ChromosomePane[] chromosomes; - private TabPane mainPane; - - private GUIConsole console = new GUIConsole(); - private SettingsPane settings; - - private Service cgpService; - - private static boolean evolving = false; - - public static void main(String[] args) { - cgp = new JCGP(); - resources = cgp.getResources(); - - launch(); - } - - @Override - public void start(Stage primaryStage) throws Exception { - - cgpService = new Service () { - - @Override - protected Task createTask() { - - Task t = new Task() { - @Override - protected Integer call() throws Exception { - while (!isCancelled()) { - cgp.nextGeneration(); - } - return null; - } - }; - - return t; - } - }; - - /* - * Instantiate the various GUI elements here. - * - * - */ - - mainPane = new TabPane(); - mainPane.setTabClosingPolicy(TabClosingPolicy.UNAVAILABLE); - chromosomes = new ChromosomePane[cgp.getResources().getInt("popSize")]; - Tab tab; - for (int i = 0; i < chromosomes.length; i++) { - chromosomes[i] = new ChromosomePane(cgp.getPopulation().getChromosome(i), resources); - tab = new Tab("Chr " + i); - tab.setContent(chromosomes[i]); - mainPane.getTabs().add(tab); - } - - settings = new SettingsPane(cgp, this); - - //mainPane.setPrefHeight(500); - - leftPane = new BorderPane(); - leftPane.setCenter(mainPane); - leftPane.setBottom(console); - - window = new BorderPane(); - - window.setCenter(leftPane); - window.setRight(settings); - - //primaryStage.setMinHeight(600); - //primaryStage.setMinWidth(800); - - primaryStage.setTitle("JCGP"); - - primaryStage.setScene(new Scene(window)); - primaryStage.show(); - } - - public void updateNodeGrids() { - for (int i = 0; i < chromosomes.length; i++) { - chromosomes[i].update(); - } - } - - public void playPause() { - if (!evolving) { - evolving = true; - cgpService.restart(); - } else { - cgpService.cancel(); - evolving = false; - } - } - - public void step() { - if (!evolving) { - Thread t = new Thread(new Task() { - @Override - protected Object call() throws Exception { - cgp.nextGeneration(); - evolving = false; - return null; - } - }); - evolving = true; - t.start(); - } - } - - public boolean isEvolving() { - return evolving; - } - - public Service getCGPService() { - return cgpService; - } - -} diff --git a/src/jcgp/JCGP.java b/src/jcgp/JCGP.java index 807739f..7451d4f 100644 --- a/src/jcgp/JCGP.java +++ b/src/jcgp/JCGP.java @@ -6,24 +6,27 @@ import java.util.Map.Entry; import java.util.Random; import javafx.beans.property.SimpleIntegerProperty; -import jcgp.function.Arithmetic; -import jcgp.function.BitwiseLogic; -import jcgp.function.BooleanLogic; -import jcgp.function.Function; -import jcgp.function.FunctionSet; -import jcgp.modules.ea.EvolutionaryAlgorithm; -import jcgp.modules.ea.MuPlusLambda; -import jcgp.modules.ea.TournamentSelection; -import jcgp.modules.fitness.FitnessFunction; -import jcgp.modules.fitness.TestCase; -import jcgp.modules.fitness.TestCaseEvaluator; -import jcgp.modules.mutator.Mutator; -import jcgp.modules.mutator.PointMutator; -import jcgp.parameters.BooleanParameter; -import jcgp.parameters.DoubleParameter; -import jcgp.parameters.IntegerParameter; -import jcgp.parameters.Parameter; -import jcgp.population.Population; +import javafx.beans.value.ChangeListener; +import javafx.beans.value.ObservableValue; +import jcgp.backend.function.Arithmetic; +import jcgp.backend.function.BitwiseLogic; +import jcgp.backend.function.BooleanLogic; +import jcgp.backend.function.Function; +import jcgp.backend.function.FunctionSet; +import jcgp.backend.modules.ea.EvolutionaryAlgorithm; +import jcgp.backend.modules.ea.MuPlusLambda; +import jcgp.backend.modules.ea.TournamentSelection; +import jcgp.backend.modules.fitness.FitnessFunction; +import jcgp.backend.modules.fitness.TestCase; +import jcgp.backend.modules.fitness.TestCaseEvaluator; +import jcgp.backend.modules.mutator.Mutator; +import jcgp.backend.modules.mutator.PointMutator; +import jcgp.backend.parameters.BooleanParameter; +import jcgp.backend.parameters.DoubleParameter; +import jcgp.backend.parameters.IntegerParameter; +import jcgp.backend.parameters.Parameter; +import jcgp.backend.population.Population; +import jcgp.gui.console.Console; /** * @author Eduardo Pedroni @@ -33,6 +36,9 @@ public class JCGP { /** * + * The resources class encapsulates all of the resources based on which the program operates. + * Each instance of JCGP contains a single instance of Resources, which gets passed to the selected + * modules as the program executes. * * @author Eduardo Pedroni * @@ -51,8 +57,11 @@ public class JCGP { new BooleanLogic() }; private FunctionSet functionSet = functionSets[0]; + // GUI console + private Console console; + public Resources() { - createCoreParameters(); + createBaseParameters(); numberGenerator = new Random(getInt("seed")); set("arity", functionSet.getMaxArity()); @@ -104,7 +113,7 @@ public class JCGP { return parameters.containsKey(key); } - private void createCoreParameters() { + private void createBaseParameters() { parameters.put("rows", new IntegerParameter(8, "Rows")); parameters.put("columns", new IntegerParameter(9, "Columns")); parameters.put("inputs", new IntegerParameter(3, "Inputs")); @@ -112,21 +121,73 @@ public class JCGP { parameters.put("popSize", new IntegerParameter(5, "Population")); parameters.put("levelsBack", new IntegerParameter(2, "Levels back")); - IntegerParameter nodes = new IntegerParameter(1, "Nodes", false, true); + IntegerParameter nodes = new IntegerParameter(1, "Nodes", true, true, false); nodes.valueProperty().bind(((SimpleIntegerProperty) ((IntegerParameter) parameters.get("rows")).valueProperty()).multiply((SimpleIntegerProperty) ((IntegerParameter) parameters.get("columns")).valueProperty())); parameters.put("nodes", nodes); parameters.put("generations", new IntegerParameter(1000000, "Generations")); - parameters.put("currentGen", new IntegerParameter(1, "Generation", false, false)); + parameters.put("currentGen", new IntegerParameter(1, "Generation", true, false, false)); parameters.put("runs", new IntegerParameter(5, "Runs")); - parameters.put("currentRun", new IntegerParameter(1, "Run", false, false)); + parameters.put("currentRun", new IntegerParameter(1, "Run", true, false, false)); - parameters.put("arity", new IntegerParameter(0, "Max arity", true, true)); - parameters.put("seed", new IntegerParameter(123, "Seed")); + parameters.put("arity", new IntegerParameter(0, "Max arity", false, true, false)); + + IntegerParameter seed = new IntegerParameter(123, "Seed"); + seed.valueProperty().addListener(new ChangeListener() { + @Override + public void changed( + ObservableValue observable, + Number oldValue, Number newValue) { + numberGenerator.setSeed(newValue.longValue()); + } + }); + parameters.put("seed", seed); - parameters.put("verbose", new BooleanParameter(false, "Verbose")); - parameters.put("report", new IntegerParameter(1, "Report")); + parameters.put("report", new IntegerParameter(1, "Report", false, false, false)); + } + + private boolean validateBaseParameters() { + boolean valid = true; + + if (getInt("rows") <= 0) { + valid = false; + println("Error: number of rows must be greater than 0."); + } + if (getInt("columns") <= 0) { + valid = false; + println("Error: number of columns must be greater than 0."); + } + if (getInt("inputs") <= 0) { + valid = false; + println("Error: number of inputs must be greater than 0."); + } + if (getInt("outputs") <= 0) { + println("Error: number of outputs must be greater than 0."); + valid = false; + } + if (getInt("popSize") <= 0) { + println("Error: population size must be greater than 0."); + valid = false; + } + if (getInt("levelsBack") <= 0 || getInt("levelsBack") > getInt("columns")) { + println("Error: levels back must be greater than 0 and no greater than the number of columns."); + valid = false; + } + if (getInt("generations") <= 0) { + println("Error: number of generations must be greater than 0."); + valid = false; + } + if (getInt("runs") <= 0) { + println("Error: number of runs must be greater than 0."); + valid = false; + } + if (getInt("report") < 0) { + println("Error: report frequency must not be smaller than 0."); + valid = false; + } + + return valid; } /** @@ -157,7 +218,8 @@ public class JCGP { * FunctionSet functions */ public Function getRandomFunction() { - return functionSet.getAllowedFunction(numberGenerator.nextInt(functionSet.getAllowedFunctionCount())); + Function f = functionSet.getAllowedFunction(numberGenerator.nextInt(functionSet.getAllowedFunctionCount())); + return f; } public Function getFunction(int index) { @@ -196,7 +258,27 @@ public class JCGP { public int getTestCaseCount() { return testCases.length; } - + + /* + * Console functionality + */ + public void setConsole(Console console) { + this.console = console; + } + + public void println(String s) { + System.out.println(s); + if (console != null) { + console.println(s); + } + } + + public void print(String s) { + System.out.print(s); + if (console != null) { + console.print(s); + } + } } private Resources resources = new Resources(); @@ -242,21 +324,12 @@ public class JCGP { resources.setTestCases(new TestCase(new Integer[]{1, 2, 3}, new Integer[]{4, 5, 6}), new TestCase(new Integer[]{1, 12, 4}, new Integer[]{6, 21, 2})); -// for (int i = 0; i < (int) resources.get("generations"); i++) { -// -// resources.set("currentGen", ((int) resources.get("currentGen")) + 1); -// -// fitnessFunction.evaluate(population, resources); -// evolutionaryAlgorithm.evolve(population, mutator, resources); -// -// System.out.println("fitness: " + evolutionaryAlgorithm.getFittestChromosome().getFitness()); -// -// if (evolutionaryAlgorithm.getFittestChromosome().getFitness() >= 6) { -// System.out.println("solution found"); -// evolutionaryAlgorithm.getFittestChromosome().printNodes(); -// break; -// } -// } + + } + + + public void remakePopulation() { + population = new Population(resources); } @@ -342,23 +415,22 @@ public class JCGP { } public void nextGeneration() { - resources.set("currentGen", resources.getInt("currentGen") + 1); fitnessFunction.evaluate(population, resources); evolutionaryAlgorithm.evolve(population, mutator, resources); if (evolutionaryAlgorithm.getFittestChromosome().getFitness() >= 6) { - System.out.println("solution found"); + resources.println("solution found"); evolutionaryAlgorithm.getFittestChromosome().printNodes(); } else { - System.out.println("Generation: " + resources.getInt("currentGen") + ", fitness: " + evolutionaryAlgorithm.getFittestChromosome().getFitness()); + resources.println("Generation: " + resources.getInt("currentGen") + ", fitness: " + evolutionaryAlgorithm.getFittestChromosome().getFitness()); } + resources.set("currentGen", resources.getInt("currentGen") + 1); } public void start() { while (resources.getInt("currentGen") <= resources.getInt("generations")) { nextGeneration(); } - // TODO print something? - } + } } diff --git a/src/jcgp/backend/exceptions/InsufficientConnectionsException.java b/src/jcgp/backend/exceptions/InsufficientConnectionsException.java new file mode 100644 index 0000000..15ac845 --- /dev/null +++ b/src/jcgp/backend/exceptions/InsufficientConnectionsException.java @@ -0,0 +1,10 @@ +package jcgp.backend.exceptions; + +public class InsufficientConnectionsException extends RuntimeException { + + /** + * + */ + private static final long serialVersionUID = 660740514800883541L; + +} diff --git a/src/jcgp/backend/exceptions/InvalidArgumentsException.java b/src/jcgp/backend/exceptions/InvalidArgumentsException.java new file mode 100644 index 0000000..bbae976 --- /dev/null +++ b/src/jcgp/backend/exceptions/InvalidArgumentsException.java @@ -0,0 +1,20 @@ +package jcgp.backend.exceptions; + +public class InvalidArgumentsException extends RuntimeException { + + /** + * + */ + private static final long serialVersionUID = 2675108124600817777L; + private String reason; + + public InvalidArgumentsException(String reason) { + super(); + this.reason = reason; + } + + public String getReason() { + return reason; + } + +} diff --git a/src/jcgp/backend/exceptions/ManagedModuleException.java b/src/jcgp/backend/exceptions/ManagedModuleException.java new file mode 100644 index 0000000..3452d35 --- /dev/null +++ b/src/jcgp/backend/exceptions/ManagedModuleException.java @@ -0,0 +1,10 @@ +package jcgp.backend.exceptions; + +public class ManagedModuleException extends RuntimeException { + + /** + * + */ + private static final long serialVersionUID = -3450063156524494967L; + +} diff --git a/src/jcgp/backend/exceptions/ParameterMismatchException.java b/src/jcgp/backend/exceptions/ParameterMismatchException.java new file mode 100644 index 0000000..3ab9fa1 --- /dev/null +++ b/src/jcgp/backend/exceptions/ParameterMismatchException.java @@ -0,0 +1,10 @@ +package jcgp.backend.exceptions; + +public class ParameterMismatchException extends RuntimeException { + + /** + * + */ + private static final long serialVersionUID = -3161318886125868134L; + +} diff --git a/src/jcgp/backend/function/Arithmetic.java b/src/jcgp/backend/function/Arithmetic.java new file mode 100644 index 0000000..6971663 --- /dev/null +++ b/src/jcgp/backend/function/Arithmetic.java @@ -0,0 +1,139 @@ +package jcgp.backend.function; + +import java.util.ArrayList; +import java.util.Arrays; + +import jcgp.backend.exceptions.InvalidArgumentsException; +import jcgp.backend.population.Connection; + +public class Arithmetic extends FunctionSet { + + public Arithmetic() { + name = "Arithmetic"; + functionList = new Function[]{ + new Addition(), + new Subtraction(), + new Multiplication(), + new Division()}; + + allowedFunctions = new ArrayList(Arrays.asList(functionList)); + } + + public static class Addition extends Function { + + private int arity = 2; + + @Override + public Integer run(Connection... connections) { + if (connections.length < arity) { + throw new InvalidArgumentsException("Not enough connections were given."); + } else { + Integer arg1 = ((Integer) connections[0].getValue()); + Integer arg2 = ((Integer) connections[1].getValue()); + Integer result = arg1 + arg2; + + return result; + } + } + + @Override + public int getArity() { + return arity; + } + + @Override + public String getName() { + return "Addition"; + } + } + + public static class Subtraction extends Function { + + private int arity = 2; + + @Override + public Integer run(Connection... connections) { + if (connections.length < arity) { + throw new InvalidArgumentsException("Not enough connections were given."); + } else { + Integer arg1 = ((Integer) connections[0].getValue()); + Integer arg2 = ((Integer) connections[1].getValue()); + Integer result = arg1 - arg2; + + return result; + } + } + + @Override + public int getArity() { + return arity; + } + + @Override + public String getName() { + return "Subtraction"; + } + } + + public static class Multiplication extends Function { + + private int arity = 2; + + @Override + public Integer run(Connection... connections) { + if (connections.length < arity) { + throw new InvalidArgumentsException("Not enough connections were given."); + } else { + Integer arg1 = ((Integer) connections[0].getValue()); + Integer arg2 = ((Integer) connections[1].getValue()); + Integer result = arg1 * arg2; + + return result; + } + } + + @Override + public int getArity() { + return arity; + } + + @Override + public String getName() { + return "Multiplication"; + } + } + + public static class Division extends Function { + + private int arity = 2; + + @Override + public Integer run(Connection... connections) { + if (connections.length < arity) { + throw new InvalidArgumentsException("Not enough connections were given."); + } else { + Integer arg1 = ((Integer) connections[0].getValue()); + Integer arg2 = ((Integer) connections[1].getValue()); + Integer result; + if (arg2 == 0) { + result = 0; + } else { + result = arg1 / arg2; + } + + return result; + } + } + + @Override + public int getArity() { + return arity; + } + + @Override + public String getName() { + return "Division"; + } + } + +} diff --git a/src/jcgp/backend/function/BitwiseLogic.java b/src/jcgp/backend/function/BitwiseLogic.java new file mode 100644 index 0000000..bfe361f --- /dev/null +++ b/src/jcgp/backend/function/BitwiseLogic.java @@ -0,0 +1,215 @@ +package jcgp.backend.function; + +import java.util.ArrayList; +import java.util.Arrays; + +import jcgp.backend.exceptions.InvalidArgumentsException; +import jcgp.backend.population.Connection; + +public class BitwiseLogic extends FunctionSet { + + public BitwiseLogic() { + name = "32-bit Logic"; + functionList = new Function[]{ + new And(), + new Or(), + new Not(), + new Xor(), + new Nand(), + new Nor(), + new Xnor()}; + + allowedFunctions = new ArrayList(Arrays.asList(functionList)); + } + + public static class And extends Function { + private int arity = 2; + + @Override + public Object run(Connection... connections) { + if (connections.length < arity) { + throw new InvalidArgumentsException("Not enough connections were given."); + } else { + int arg1 = ((int) connections[0].getValue()); + int arg2 = ((int) connections[1].getValue()); + int result = arg1 & arg2; + + return result; + } + } + + @Override + public int getArity() { + return arity; + } + + @Override + public String getName() { + return "AND"; + } + } + + public static class Or extends Function { + private int arity = 2; + + @Override + public Object run(Connection... connections) { + if (connections.length < arity) { + throw new InvalidArgumentsException("Not enough connections were given."); + } else { + int arg1 = ((int) connections[0].getValue()); + int arg2 = ((int) connections[1].getValue()); + int result = arg1 | arg2; + + return result; + } + } + + @Override + public int getArity() { + return arity; + } + + @Override + public String getName() { + return "OR"; + } + } + + public static class Not extends Function { + private int arity = 1; + + @Override + public Object run(Connection... connections) { + if (connections.length < arity) { + throw new InvalidArgumentsException("Not enough connections were given."); + } else { + int arg1 = ((int) connections[0].getValue()); + int result = ~arg1; + + return result; + } + } + + @Override + public int getArity() { + return arity; + } + + @Override + public String getName() { + return "NOT"; + } + } + + public static class Xor extends Function { + private int arity = 2; + + @Override + public Object run(Connection... connections) { + if (connections.length < arity) { + throw new InvalidArgumentsException("Not enough connections were given."); + } else { + int arg1 = ((int) connections[0].getValue()); + int arg2 = ((int) connections[1].getValue()); + int result = arg1 ^ arg2; + + return result; + } + } + + @Override + public int getArity() { + return arity; + } + + @Override + public String getName() { + return "XOR"; + } + } + + public static class Nand extends Function { + private int arity = 2; + + @Override + public Object run(Connection... connections) { + if (connections.length < arity) { + throw new InvalidArgumentsException("Not enough connections were given."); + } else { + int arg1 = ((int) connections[0].getValue()); + int arg2 = ((int) connections[1].getValue()); + int result = arg1 & arg2; + + return ~result; + } + } + + @Override + public int getArity() { + return arity; + } + + @Override + public String getName() { + return "NAND"; + } + } + + public static class Nor extends Function { + private int arity = 2; + + @Override + public Object run(Connection... connections) { + if (connections.length < arity) { + throw new InvalidArgumentsException("Not enough connections were given."); + } else { + int arg1 = ((int) connections[0].getValue()); + int arg2 = ((int) connections[1].getValue()); + int result = arg1 | arg2; + + return ~result; + } + } + + @Override + public int getArity() { + return arity; + } + + @Override + public String getName() { + return "NOR"; + } + } + + public static class Xnor extends Function { + private int arity = 2; + + @Override + public Object run(Connection... connections) { + if (connections.length < arity) { + throw new InvalidArgumentsException("Not enough connections were given."); + } else { + int arg1 = ((int) connections[0].getValue()); + int arg2 = ((int) connections[1].getValue()); + int result = arg1 ^ arg2; + + return ~result; + } + } + + @Override + public int getArity() { + return arity; + } + + @Override + public String getName() { + return "XNOR"; + } + } + + + +} diff --git a/src/jcgp/backend/function/BooleanLogic.java b/src/jcgp/backend/function/BooleanLogic.java new file mode 100644 index 0000000..e0b5c9c --- /dev/null +++ b/src/jcgp/backend/function/BooleanLogic.java @@ -0,0 +1,215 @@ +package jcgp.backend.function; + +import java.util.ArrayList; +import java.util.Arrays; + +import jcgp.backend.exceptions.InvalidArgumentsException; +import jcgp.backend.population.Connection; + +public class BooleanLogic extends FunctionSet { + + public BooleanLogic() { + name = "1-bit Logic"; + functionList = new Function[]{ + new And(), + new Or(), + new Not(), + new Xor(), + new Nand(), + new Nor(), + new Xnor()}; + + allowedFunctions = new ArrayList(Arrays.asList(functionList)); + } + + public static class And extends Function { + private int arity = 2; + + @Override + public Boolean run(Connection... connections) { + if (connections.length < arity) { + throw new InvalidArgumentsException("Not enough connections were given."); + } else { + Boolean arg1 = ((Boolean) connections[0].getValue()); + Boolean arg2 = ((Boolean) connections[1].getValue()); + Boolean result = arg1 && arg2; + + return result; + } + } + + @Override + public int getArity() { + return arity; + } + + @Override + public String getName() { + return "AND"; + } + } + + public static class Or extends Function { + private int arity = 2; + + @Override + public Boolean run(Connection... connections) { + if (connections.length < arity) { + throw new InvalidArgumentsException("Not enough connections were given."); + } else { + Boolean arg1 = ((Boolean) connections[0].getValue()); + Boolean arg2 = ((Boolean) connections[1].getValue()); + Boolean result = arg1 || arg2; + + return result; + } + } + + @Override + public int getArity() { + return arity; + } + + @Override + public String getName() { + return "OR"; + } + } + + public static class Not extends Function { + private int arity = 1; + + @Override + public Boolean run(Connection... connections) { + if (connections.length < arity) { + throw new InvalidArgumentsException("Not enough connections were given."); + } else { + Boolean arg1 = ((Boolean) connections[0].getValue()); + Boolean result = !arg1; + + return result; + } + } + + @Override + public int getArity() { + return arity; + } + + @Override + public String getName() { + return "NOT"; + } + } + + public static class Xor extends Function { + private int arity = 2; + + @Override + public Boolean run(Connection... connections) { + if (connections.length < arity) { + throw new InvalidArgumentsException("Not enough connections were given."); + } else { + Boolean arg1 = ((Boolean) connections[0].getValue()); + Boolean arg2 = ((Boolean) connections[1].getValue()); + Boolean result = arg1 ^ arg2; + + return result; + } + } + + @Override + public int getArity() { + return arity; + } + + @Override + public String getName() { + return "XOR"; + } + } + + public static class Nand extends Function { + private int arity = 2; + + @Override + public Boolean run(Connection... connections) { + if (connections.length < arity) { + throw new InvalidArgumentsException("Not enough connections were given."); + } else { + Boolean arg1 = ((Boolean) connections[0].getValue()); + Boolean arg2 = ((Boolean) connections[1].getValue()); + Boolean result = arg1 && arg2; + + return !result; + } + } + + @Override + public int getArity() { + return arity; + } + + @Override + public String getName() { + return "NAND"; + } + } + + public static class Nor extends Function { + private int arity = 2; + + @Override + public Boolean run(Connection... connections) { + if (connections.length < arity) { + throw new InvalidArgumentsException("Not enough connections were given."); + } else { + Boolean arg1 = ((Boolean) connections[0].getValue()); + Boolean arg2 = ((Boolean) connections[1].getValue()); + Boolean result = arg1 || arg2; + + return !result; + } + } + + @Override + public int getArity() { + return arity; + } + + @Override + public String getName() { + return "NOR"; + } + } + + public static class Xnor extends Function { + private int arity = 2; + + @Override + public Boolean run(Connection... connections) { + if (connections.length < arity) { + throw new InvalidArgumentsException("Not enough connections were given."); + } else { + Boolean arg1 = ((Boolean) connections[0].getValue()); + Boolean arg2 = ((Boolean) connections[1].getValue()); + Boolean result = arg1 ^ arg2; + + return !result; + } + } + + @Override + public int getArity() { + return arity; + } + + @Override + public String getName() { + return "XNOR"; + } + } + + + +} diff --git a/src/jcgp/backend/function/Function.java b/src/jcgp/backend/function/Function.java new file mode 100644 index 0000000..30bbcf0 --- /dev/null +++ b/src/jcgp/backend/function/Function.java @@ -0,0 +1,13 @@ +package jcgp.backend.function; + +import jcgp.backend.exceptions.InvalidArgumentsException; +import jcgp.backend.population.Connection; + +public abstract class Function { + + public abstract Object run(Connection ... connections) throws InvalidArgumentsException; + + public abstract int getArity(); + + public abstract String getName(); +} diff --git a/src/jcgp/backend/function/FunctionSet.java b/src/jcgp/backend/function/FunctionSet.java new file mode 100644 index 0000000..4470ac8 --- /dev/null +++ b/src/jcgp/backend/function/FunctionSet.java @@ -0,0 +1,74 @@ +package jcgp.backend.function; + +import java.util.ArrayList; +import java.util.Iterator; + + +/** + * + * @author Eduardo Pedroni + * + */ +public abstract class FunctionSet { + protected Function[] functionList; + protected ArrayList allowedFunctions; + protected String name; + + public int getAllowedFunctionCount() { + return allowedFunctions.size(); + } + + public int getTotalFunctionCount() { + return functionList.length; + } + + public Function getAllowedFunction(int index) { + return allowedFunctions.get(index); + } + + public Function getFunction(int index) { + return functionList[index]; + } + + public int getMaxArity(){ + int arity = 0; + for (Function function : allowedFunctions) { + if (function.getArity() > arity) { + arity = function.getArity(); + } + } + return arity; + } + + public String getName() { + return name; + } + + public void disableFunction(int index) { + if (index < functionList.length) { + for (Iterator iterator = allowedFunctions.iterator(); iterator.hasNext();) { + Function function = (Function) iterator.next(); + if (function == functionList[index]) { + iterator.remove(); + } + } + } else { + throw new IndexOutOfBoundsException("Function " + index + " does not exist, the set only has " + functionList.length + " functions."); + } + } + + public void enableFunction(int index) { + if (!allowedFunctions.contains(functionList[index])) { + allowedFunctions.add(functionList[index]); + } + } + + @Override + public String toString() { + return name; + } + + public boolean isEnabled(Function f) { + return allowedFunctions.contains(f); + } + } \ No newline at end of file diff --git a/src/jcgp/backend/modules/Module.java b/src/jcgp/backend/modules/Module.java new file mode 100644 index 0000000..f9114de --- /dev/null +++ b/src/jcgp/backend/modules/Module.java @@ -0,0 +1,11 @@ +package jcgp.backend.modules; + +import java.util.HashMap; + +import jcgp.JCGP.Resources; +import jcgp.backend.parameters.Parameter; + +public interface Module { + public HashMap getLocalParameters(); + public ModuleStatus getStatus(Resources resources); +} diff --git a/src/jcgp/backend/modules/ModuleStatus.java b/src/jcgp/backend/modules/ModuleStatus.java new file mode 100644 index 0000000..fec8490 --- /dev/null +++ b/src/jcgp/backend/modules/ModuleStatus.java @@ -0,0 +1,16 @@ +package jcgp.backend.modules; + +public enum ModuleStatus { + ERROR, WARNING, READY; + + private String details; + + public void setDetails(String details) { + this.details = details; + } + + public String getDetails() { + return details; + } + +} diff --git a/src/jcgp/backend/modules/ea/EvolutionaryAlgorithm.java b/src/jcgp/backend/modules/ea/EvolutionaryAlgorithm.java new file mode 100644 index 0000000..ce457ef --- /dev/null +++ b/src/jcgp/backend/modules/ea/EvolutionaryAlgorithm.java @@ -0,0 +1,15 @@ +package jcgp.backend.modules.ea; + +import jcgp.JCGP.Resources; +import jcgp.backend.modules.Module; +import jcgp.backend.modules.mutator.Mutator; +import jcgp.backend.population.Chromosome; +import jcgp.backend.population.Population; + +public interface EvolutionaryAlgorithm extends Module { + + public abstract void evolve(Population population, Mutator mutator, Resources parameters); + + public abstract Chromosome getFittestChromosome(); + +} diff --git a/src/jcgp/backend/modules/ea/MuPlusLambda.java b/src/jcgp/backend/modules/ea/MuPlusLambda.java new file mode 100644 index 0000000..fcfba05 --- /dev/null +++ b/src/jcgp/backend/modules/ea/MuPlusLambda.java @@ -0,0 +1,80 @@ +package jcgp.backend.modules.ea; + +import java.util.HashMap; + +import jcgp.JCGP.Resources; +import jcgp.backend.modules.ModuleStatus; +import jcgp.backend.modules.mutator.Mutator; +import jcgp.backend.parameters.IntegerParameter; +import jcgp.backend.parameters.Parameter; +import jcgp.backend.population.Chromosome; +import jcgp.backend.population.Population; + +/** + * (μ + λ) EA. + * + * + * @author Eduardo Pedroni + * + */ +public class MuPlusLambda implements EvolutionaryAlgorithm { + + private Chromosome fittestChromosome; + + private IntegerParameter parents, offspring; + + private HashMap localParameters; + + public MuPlusLambda() { + parents = new IntegerParameter(1, "Parents"); + offspring = new IntegerParameter(4, "Offspring"); + + localParameters = new HashMap(); + + localParameters.put("mu", parents); + localParameters.put("lambda", offspring); + } + + @Override + public void evolve(Population population, Mutator mutator, Resources parameters) { + // select fittest chromosome + int fittest = 0; + + for (int i = 1; i < parameters.getInt("popSize"); i++) { + if (population.getChromosome(i).getFitness() >= population.getChromosome(fittest).getFitness()) { + fittest = i; + } + } + fittestChromosome = population.getChromosome(fittest); + population.setBestIndividual(fittest); + // create copies of fittest chromosome, mutate them + Chromosome fc = population.getChromosome(fittest); + for (int i = 0; i < parameters.getInt("popSize"); i++) { + if (i != fittest) { + population.getChromosome(i).copyConnections(fc); + mutator.mutate(population.getChromosome(i), parameters); + } + } + } + + @Override + public Chromosome getFittestChromosome() { + return fittestChromosome; + } + + @Override + public HashMap getLocalParameters() { + return localParameters; + } + + @Override + public String toString() { + return "(μ + λ)"; + } + + @Override + public ModuleStatus getStatus(Resources resources) { + return ModuleStatus.READY; + } + +} diff --git a/src/jcgp/backend/modules/ea/TournamentSelection.java b/src/jcgp/backend/modules/ea/TournamentSelection.java new file mode 100644 index 0000000..6cbaa45 --- /dev/null +++ b/src/jcgp/backend/modules/ea/TournamentSelection.java @@ -0,0 +1,55 @@ +package jcgp.backend.modules.ea; + +import java.util.HashMap; + +import jcgp.JCGP.Resources; +import jcgp.backend.modules.ModuleStatus; +import jcgp.backend.modules.mutator.Mutator; +import jcgp.backend.parameters.IntegerParameter; +import jcgp.backend.parameters.Parameter; +import jcgp.backend.population.Chromosome; +import jcgp.backend.population.Population; + +public class TournamentSelection implements EvolutionaryAlgorithm { + + private Chromosome fittestChromosome; + + private IntegerParameter tournament; + private HashMap localParameters; + + public TournamentSelection() { + tournament = new IntegerParameter(1, "Tournament size"); + + localParameters = new HashMap(); + localParameters.put("tournament", tournament); + } + + @Override + public HashMap getLocalParameters() { + return localParameters; + } + + @Override + public void evolve(Population population, Mutator mutator, + Resources parameters) { + tournament.set(tournament.get() + 1); + fittestChromosome = population.getChromosome(0); + // TODO implement this + + } + + @Override + public Chromosome getFittestChromosome() { + return fittestChromosome; + } + + @Override + public String toString() { + return "Tournament"; + } + + @Override + public ModuleStatus getStatus(Resources resources) { + return null; + } +} diff --git a/src/jcgp/backend/modules/fitness/FitnessFunction.java b/src/jcgp/backend/modules/fitness/FitnessFunction.java new file mode 100644 index 0000000..ffce9b7 --- /dev/null +++ b/src/jcgp/backend/modules/fitness/FitnessFunction.java @@ -0,0 +1,11 @@ +package jcgp.backend.modules.fitness; + +import jcgp.JCGP.Resources; +import jcgp.backend.modules.Module; +import jcgp.backend.population.Population; + +public interface FitnessFunction extends Module { + + public void evaluate(Population population, Resources resources); + +} diff --git a/src/jcgp/backend/modules/fitness/TestCase.java b/src/jcgp/backend/modules/fitness/TestCase.java new file mode 100644 index 0000000..23f7ecf --- /dev/null +++ b/src/jcgp/backend/modules/fitness/TestCase.java @@ -0,0 +1,29 @@ +package jcgp.backend.modules.fitness; + +public class TestCase { + + private Object[] inputs; + private Object[] outputs; + + public TestCase(Object[] inputs, Object[] outputs) { + this.inputs = inputs; + this.outputs = outputs; + } + + public Object getInput(int index) { + return inputs[index]; + } + + public Object getOutput(int index) { + return outputs[index]; + } + + public Object[] getInputs() { + return inputs; + } + + public Object[] getOutputs() { + return outputs; + } + +} diff --git a/src/jcgp/backend/modules/fitness/TestCaseEvaluator.java b/src/jcgp/backend/modules/fitness/TestCaseEvaluator.java new file mode 100644 index 0000000..3b67f28 --- /dev/null +++ b/src/jcgp/backend/modules/fitness/TestCaseEvaluator.java @@ -0,0 +1,45 @@ +package jcgp.backend.modules.fitness; + +import java.util.HashMap; + +import jcgp.JCGP.Resources; +import jcgp.backend.modules.ModuleStatus; +import jcgp.backend.parameters.Parameter; +import jcgp.backend.population.Population; + +public class TestCaseEvaluator implements FitnessFunction { + + @Override + public void evaluate(Population population, Resources resources) { + // for every chromosome in the population + for (int i = 0; i < resources.getInt("popSize"); i++) { + int fitness = 0; + // for every test case + for (int t = 0; t < resources.getTestCaseCount(); t++) { + population.getChromosome(i).setInputs(resources.getTestCase(t).getInputs()); + // check every output + for (int o = 0; o < resources.getInt("outputs"); o++) { + if (population.getChromosome(i).getOutput(o).calculate() == resources.getTestCase(t).getOutput(o)) { + fitness++; + } + } + } + population.getChromosome(i).setFitness(fitness); + } + } + + @Override + public HashMap getLocalParameters() { + return null; + } + + @Override + public String toString() { + return "Test case"; + } + + @Override + public ModuleStatus getStatus(Resources resources) { + return null; + } +} diff --git a/src/jcgp/backend/modules/mutator/Mutator.java b/src/jcgp/backend/modules/mutator/Mutator.java new file mode 100644 index 0000000..fd7cd27 --- /dev/null +++ b/src/jcgp/backend/modules/mutator/Mutator.java @@ -0,0 +1,11 @@ +package jcgp.backend.modules.mutator; + +import jcgp.JCGP.Resources; +import jcgp.backend.modules.Module; +import jcgp.backend.population.Chromosome; + +public interface Mutator extends Module { + + void mutate(Chromosome chromosome, Resources parameters); + +} diff --git a/src/jcgp/backend/modules/mutator/PointMutator.java b/src/jcgp/backend/modules/mutator/PointMutator.java new file mode 100644 index 0000000..62d827d --- /dev/null +++ b/src/jcgp/backend/modules/mutator/PointMutator.java @@ -0,0 +1,73 @@ +package jcgp.backend.modules.mutator; + +import java.util.HashMap; + +import jcgp.backend.function.Function; +import jcgp.backend.modules.ModuleStatus; +import jcgp.backend.parameters.DoubleParameter; +import jcgp.backend.parameters.Parameter; +import jcgp.backend.population.Chromosome; +import jcgp.backend.population.MutableElement; +import jcgp.backend.population.Node; +import jcgp.backend.population.Output; +import jcgp.JCGP.Resources; + +public class PointMutator implements Mutator { + + private DoubleParameter mutationRate; + private HashMap localParameters; + + private ModuleStatus status = ModuleStatus.READY; + + public PointMutator() { + mutationRate = new DoubleParameter(0.5, "Percent mutation", false, false, false); + + localParameters = new HashMap(); + localParameters.put("mutRate", mutationRate); + } + + @Override + public void mutate(Chromosome chromosome, Resources resources) { + int mutations = (int) Math.ceil(((mutationRate.get()) * ((((resources.getDouble("nodes")) + (resources.getDouble("outputs")))) / (double) 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 HashMap getLocalParameters() { + return localParameters; + } + + @Override + public String toString() { + return "Point mutation"; + } + + @Override + public ModuleStatus getStatus(Resources resources) { + if (mutationRate.get() <= 0 || mutationRate.get() > 100) { + status = ModuleStatus.ERROR; + status.setDetails("Mutation rate must be > 0 and <= 100"); + } else if ((int) ((mutationRate.get() / 100) * resources.getDouble("nodes")) > 0) { + status = ModuleStatus.WARNING; + status.setDetails("With mutation rate " + mutationRate.get() + ", no mutations will occur."); + } else { + status = ModuleStatus.READY; + status.setDetails(""); + } + return status; + } +} diff --git a/src/jcgp/backend/parameters/BooleanParameter.java b/src/jcgp/backend/parameters/BooleanParameter.java new file mode 100644 index 0000000..d5904cd --- /dev/null +++ b/src/jcgp/backend/parameters/BooleanParameter.java @@ -0,0 +1,32 @@ +package jcgp.backend.parameters; + +import javafx.beans.property.SimpleBooleanProperty; + +public class BooleanParameter extends Parameter { + + private SimpleBooleanProperty value; + + public BooleanParameter(boolean value, String name, boolean monitor, boolean hidden, boolean critical) { + super(name, monitor, hidden, critical); + this.value = new SimpleBooleanProperty(value); + } + + public BooleanParameter(boolean value, String name) { + super(name, false, false, true); + this.value = new SimpleBooleanProperty(value); + } + + public boolean get() { + return value.get(); + } + + public void set(boolean newValue) { + if (!value.isBound()) { + value.set(newValue); + } + } + + public SimpleBooleanProperty valueProperty() { + return value; + } +} diff --git a/src/jcgp/backend/parameters/DoubleParameter.java b/src/jcgp/backend/parameters/DoubleParameter.java new file mode 100644 index 0000000..26031be --- /dev/null +++ b/src/jcgp/backend/parameters/DoubleParameter.java @@ -0,0 +1,33 @@ +package jcgp.backend.parameters; + +import javafx.beans.property.SimpleDoubleProperty; + +public class DoubleParameter extends Parameter { + + protected SimpleDoubleProperty value; + + public DoubleParameter(double value, String name, boolean monitor, boolean hidden, boolean critical) { + super(name, monitor, hidden, critical); + this.value = new SimpleDoubleProperty(value); + } + + public DoubleParameter(double value, String name) { + super(name, false, false, true); + this.value = new SimpleDoubleProperty(value); + } + + public double get() { + return value.get(); + } + + public void set(double newValue) { + if (!value.isBound()) { + value.set(newValue); + } + } + + public SimpleDoubleProperty valueProperty() { + return value; + } + +} diff --git a/src/jcgp/backend/parameters/IntegerParameter.java b/src/jcgp/backend/parameters/IntegerParameter.java new file mode 100644 index 0000000..dbfa5c5 --- /dev/null +++ b/src/jcgp/backend/parameters/IntegerParameter.java @@ -0,0 +1,33 @@ +package jcgp.backend.parameters; + +import javafx.beans.property.SimpleIntegerProperty; + +public class IntegerParameter extends Parameter { + + protected SimpleIntegerProperty value; + + public IntegerParameter(int value, String name, boolean monitor, boolean hidden, boolean critical) { + super(name, monitor, hidden, critical); + this.value = new SimpleIntegerProperty(value); + } + + public IntegerParameter(int value, String name) { + super(name, false, false, true); + this.value = new SimpleIntegerProperty(value); + } + + public int get() { + return value.get(); + } + + public void set(int newValue) { + if (!value.isBound()) { + value.set(newValue); + } + } + + public SimpleIntegerProperty valueProperty() { + return value; + } + +} diff --git a/src/jcgp/backend/parameters/Parameter.java b/src/jcgp/backend/parameters/Parameter.java new file mode 100644 index 0000000..2f584a4 --- /dev/null +++ b/src/jcgp/backend/parameters/Parameter.java @@ -0,0 +1,35 @@ +package jcgp.backend.parameters; + +import javafx.beans.property.Property; + +public abstract class Parameter { + + protected boolean hidden, monitor, critical; + + protected String name; + + public Parameter(String name, boolean monitor, boolean hidden, boolean critical) { + this.name = name; + this.hidden = hidden; + this.monitor = monitor; + this.critical = critical; + } + + public boolean isHidden() { + return hidden; + } + + public boolean isMonitor() { + return monitor; + } + + public boolean isCritical() { + return critical; + } + + public String getName() { + return name; + } + + public abstract Property valueProperty(); +} diff --git a/src/jcgp/backend/population/Chromosome.java b/src/jcgp/backend/population/Chromosome.java new file mode 100644 index 0000000..18ae9bb --- /dev/null +++ b/src/jcgp/backend/population/Chromosome.java @@ -0,0 +1,335 @@ +package jcgp.backend.population; + +import java.util.ArrayList; + +import jcgp.JCGP.Resources; +import jcgp.backend.exceptions.ParameterMismatchException; + +public class Chromosome { + + private Resources resources; + + private Input[] inputs; + private Node[][] nodes; + private Output[] outputs; + + private ArrayList activeNodes; + + private int fitness = 0; + private boolean recomputeActiveNodes = true; + + /** + * Initialise a chromosome with the specified parameters. Random valid connections + * are created. + * + * + */ + public Chromosome(Resources resources) { + // store a reference to the parameters + this.resources = resources; + + // allocate memory for all elements of the chromosome + instantiateElements(); + // set random connections so that the chromosome can be evaluated + initialiseConnections(); + } + + /** + * Copy constructor. + * + * Initialise a new chromosome with the exact same connections as a given instance of Chromosome. + * + * @param clone the chromosome to be copied + */ + public Chromosome(Chromosome clone) { + // store a reference to the parameters + this.resources = clone.getParameters(); + + // allocate memory for all elements of the chromosome + instantiateElements(); + // initialise all connections based on argument + copyConnections(clone); + } + + /** + * + */ + private void instantiateElements() { + inputs = new Input[(resources.getInt("inputs"))]; + for (int i = 0; i < (resources.getInt("inputs")); i++) { + inputs[i] = new Input(i); + } + + int arity = resources.getInt("arity"); + + // rows first + nodes = new Node[(resources.getInt("rows"))][(resources.getInt("columns"))]; + for (int r = 0; r < (resources.getInt("rows")); r++) { + for (int c = 0; c < (resources.getInt("columns")); c++) { + nodes[r][c] = new Node(this, r, c, arity); + } + } + outputs = new Output[(resources.getInt("outputs"))]; + for (int o = 0; o < (resources.getInt("outputs")); o++) { + outputs[o] = new Output(this, o); + } + } + + /** + * + */ + private void initialiseConnections() { + + int arity = resources.getInt("arity"); + + // initialise nodes - [rows][columns] + for (int r = 0; r < nodes.length; r++) { + for (int c = 0; c < nodes[r].length; c++) { + Connection[] connections = new Connection[arity]; + for (int i = 0; i < connections.length; i++) { + connections[i] = getRandomConnection(c); + } + nodes[r][c].initialise(resources.getRandomFunction(), connections); + } + } + + for (Output output : outputs) { + output.setConnection(0, getRandomConnection()); + } + + } + + /** + * @param clone + */ + public void copyConnections(Chromosome clone) { + int arity = resources.getInt("arity"); + + // copy nodes - [rows][columns] + for (int r = 0; r < nodes.length; r++) { + for (int c = 0; c < nodes[r].length; c++) { + // make array of connections to initialise with + Connection[] connections = new Connection[arity]; + // populate with connections equivalent to clone + Connection copyConnection; + for (int i = 0; i < connections.length; i++) { + copyConnection = clone.getNode(r, c).getConnection(i); + if (copyConnection instanceof Input) { + connections[i] = inputs[((Input) copyConnection).getIndex()]; + } else if (copyConnection instanceof Node) { + connections[i] = nodes[((Node) copyConnection).getRow()][((Node) copyConnection).getColumn()]; + } else { + System.out.println("Warning: Connection of subtype " + copyConnection.getClass().toString() + " is not explicitly handled by copy constructor."); + } + } + // initialise with copied arguments + nodes[r][c].initialise(clone.getNode(r, c).getFunction(), connections); + } + } + + // do the same to outputs + Connection copyOutput; + for (int o = 0; o < outputs.length; o++) { + copyOutput = clone.getOutput(o).getSource(); + if (copyOutput instanceof Input) { + outputs[o].setConnection(0, inputs[((Input) copyOutput).getIndex()]); + } else if (copyOutput instanceof Node) { + outputs[o].setConnection(0, nodes[((Node) copyOutput).getRow()][((Node) copyOutput).getColumn()]); + } else { + // something bad happened + System.out.println("Warning: Connection of subtype " + copyOutput.getClass().toString() + " is not explicitly handled by copy constructor."); + } + } + } + + public Node getNode(int row, int column) { + return nodes[row][column]; + } + + public Output getOutput(int index) { + return outputs[index]; + } + + public Input getInput(int index) { + return inputs[index]; + } + + public int getFitness() { + return fitness; + } + + public void setFitness(int newFitness) { + fitness = newFitness; + } + + /** + * + * @param values + * @throws ParameterMismatchException + */ + public void setInputs(Object ... values) throws ParameterMismatchException { + // if the values provided don't match the specified number of inputs, the user should be warned + if (values.length == inputs.length) { + // set inputs for evaluation + for (int i = 0; i < values.length; i++) { + inputs[i].setValue(values[i]); + } + } else { + throw new ParameterMismatchException(); + } + } + + /** + * This method is useful for mutating chromosomes. + * + * @return a random element that can be mutated - Node or Output + */ + public MutableElement getRandomMutableElement() { + // choose output or node + int index = resources.getRandomInt(outputs.length + (resources.getInt("rows")) * (resources.getInt("columns"))); + + if (index < outputs.length) { + // outputs + return outputs[index]; + } else { + // node + index -= outputs.length; + return nodes[index / (resources.getInt("columns"))][index % (resources.getInt("columns"))]; + } + } + + /** + * Returns a random allowed connection respecting levels back.
+ * This method may always pick inputs, as they can be picked + * regardless of the column. + * + * @param column the column to use as reference + * @return a random connection + */ + public Connection getRandomConnection(int column) { + // work out the allowed range obeying levels back + int allowedColumns = ((column >= (resources.getInt("levelsBack"))) ? (resources.getInt("levelsBack")) : column); + int offset = ((column - allowedColumns) * nodes.length) - inputs.length; + + // choose input or allowed node + int index = resources.getRandomInt(inputs.length + (nodes.length * allowedColumns)); + if (index < inputs.length) { + // input + return inputs[index]; + } else { + // node + // offset it to address the right columns + index += offset; + return nodes[index % nodes.length][index / nodes.length]; + } + } + + /** + * This method will pick a completely random connection, independently + * of levels back, including inputs. + * + * Useful for setting outputs. + * + * + * @return a random connection + */ + public Connection getRandomConnection() { + // choose output or node + int index = resources.getRandomInt(inputs.length + (resources.getInt("columns")) * (resources.getInt("rows"))); + if (index < inputs.length) { + // outputs + return inputs[index]; + } else { + // node + index -= inputs.length; + return nodes[index / (resources.getInt("columns"))][index % (resources.getInt("columns"))]; + } + } + + /** + * This causes the list of active nodes to be recomputed lazily (once it is actually requested). + */ + public void recomputeActiveNodes() { + recomputeActiveNodes = true; + } + + /** + * This method computes a list of active connections (if necessary) and returns it. + * + * @return + */ + public ArrayList getActiveNodes() { + computeActiveNodes(); + return activeNodes; + } + + private void computeActiveNodes() { + // lazy recomputation has been triggered, do it + if (recomputeActiveNodes) { + recomputeActiveNodes = false; + activeNodes = new ArrayList(); + + for (Output output : outputs) { + output.getActiveNodes(activeNodes); + } + } + + } + + public boolean compareTo(Chromosome chromosome) { + for (int r = 0; r < (resources.getInt("rows")); r++) { + for (int c = 0; c < (resources.getInt("columns")); c++) { + if (!(nodes[r][c].copyOf(chromosome.getNode(r, c)))) { + return false; + } + } + } + + for (int o = 0; o < (resources.getInt("outputs")); o++) { + if (!(outputs[o].copyOf(chromosome.getOutput(o)))) { + return false; + } + } + + return true; + } + + public boolean compareActiveTo(Chromosome chromosome) { + // update list if it is out of date + computeActiveNodes(); + + if (activeNodes.size() == chromosome.getActiveNodes().size()) { + for (int i = 0; i < activeNodes.size(); i++) { + if (!(activeNodes.get(i).copyOf(chromosome.getActiveNodes().get(i)))){ + return false; + } + } + return true; + } + return false; + } + + public void printNodes() { + int arity = resources.getInt("arity"); + + for (int r = 0; r < (resources.getInt("rows")); r++) { + System.out.print("r: " + r + "\t"); + for (int c = 0; c < (resources.getInt("columns")); c++) { + System.out.print("N: (" + r + ", " + c + ") "); + for (int i = 0; i < arity; i++) { + System.out.print("C" + i + ": (" + nodes[r][c].getConnection(i).getDescription() + ") "); + } + System.out.print("F: " + nodes[r][c].getFunction().getName() + "\t"); + } + System.out.print("\n"); + } + + for (int o = 0; o < (resources.getInt("outputs")); o++) { + System.out.print("o: " + o + " (" + outputs[o].getSource().getDescription() + ")\t"); + } + } + + public Resources getParameters() { + return resources; + } +} diff --git a/src/jcgp/backend/population/Connection.java b/src/jcgp/backend/population/Connection.java new file mode 100644 index 0000000..ea4f10f --- /dev/null +++ b/src/jcgp/backend/population/Connection.java @@ -0,0 +1,9 @@ +package jcgp.backend.population; + +public interface Connection { + + public Object getValue(); + + public String getDescription(); + +} diff --git a/src/jcgp/backend/population/Gene.java b/src/jcgp/backend/population/Gene.java new file mode 100644 index 0000000..6b90949 --- /dev/null +++ b/src/jcgp/backend/population/Gene.java @@ -0,0 +1,5 @@ +package jcgp.backend.population; + +public abstract class Gene { + +} diff --git a/src/jcgp/backend/population/Input.java b/src/jcgp/backend/population/Input.java new file mode 100644 index 0000000..83fba07 --- /dev/null +++ b/src/jcgp/backend/population/Input.java @@ -0,0 +1,29 @@ +package jcgp.backend.population; + +public class Input extends Gene implements Connection { + + private Object value = 0; + private int index; + + public Input(int index) { + this.index = index; + } + + public void setValue(Object newValue) { + value = newValue; + } + + @Override + public Object getValue() { + return value; + } + + public int getIndex() { + return index; + } + + @Override + public String getDescription() { + return "i: " + index; + } +} diff --git a/src/jcgp/backend/population/MutableElement.java b/src/jcgp/backend/population/MutableElement.java new file mode 100644 index 0000000..8548e63 --- /dev/null +++ b/src/jcgp/backend/population/MutableElement.java @@ -0,0 +1,34 @@ +package jcgp.backend.population; + +public interface MutableElement { + + /** + * This method sets the indexed connection to the specified new connection. + * Implementing classes may choose to ignore the given index (such as in the + * case of outputs, which only have one connection). + * + * @param index + * @param newConnection + */ + public void setConnection(int index, Connection newConnection); + + /** + * This method returns true if and only if:
+ * - the elements being compared are not the same instance;
+ * - the connections of the compared elements are not the same instance;
+ * - the elements have the same function (in the case of Node);
+ * - the grid position of the elements themselves are the same;
+ * - the grid position of all equivalent connections are the same;

+ * + * The relationship computed by this method is:
+ * - symmetric: a.copyOf(b) == b.copyOf(a);
+ * - not reflexive: a.copyOf(a) returns false;
+ * - not transitive: if a.copyOf(b) is true and b.copyOf(c) is true, a.copyOf(c) is + * not necessarily true since it is possible that a == c.
+ * + * @param m + * @return + */ + boolean copyOf(MutableElement m); + +} diff --git a/src/jcgp/backend/population/Node.java b/src/jcgp/backend/population/Node.java new file mode 100644 index 0000000..f1d37a1 --- /dev/null +++ b/src/jcgp/backend/population/Node.java @@ -0,0 +1,112 @@ +package jcgp.backend.population; + +import java.util.ArrayList; +import java.util.Arrays; + +import jcgp.backend.exceptions.InsufficientConnectionsException; +import jcgp.backend.function.Function; + + +public class Node extends Gene implements MutableElement, Connection { + + private Function function; + private Connection[] connections; + private int column, row; + private Chromosome chromosome; + + public Node(Chromosome chromosome, int row, int column, int arity) { + this.chromosome = chromosome; + this.column = column; + this.row = row; + } + + @Override + public Object getValue() { + return function.run(Arrays.copyOfRange(connections, 0, function.getArity())); + } + + public void setFunction(Function newFunction) { + function = newFunction; + } + + @Override + public void setConnection(int index, Connection newConnection) { + connections[index] = newConnection; + chromosome.recomputeActiveNodes(); + } + + public void initialise(Function newFunction, Connection ... newConnections) throws InsufficientConnectionsException { + function = newFunction; + if (newConnections.length == function.getArity()) { + connections = newConnections; + } else { + throw new InsufficientConnectionsException(); + } + } + + public int getColumn() { + return column; + } + + public int getRow() { + return row; + } + + public Function getFunction() { + return function; + } + + public Connection getConnection(int index) { + return connections[index]; + } + + public void getActive(ArrayList activeNodes) { + if (!activeNodes.contains(this)) { + activeNodes.add(this); + } + for (int i = 0; i < function.getArity(); i++) { + if (connections[i] instanceof Node) { + ((Node) connections[i]).getActive(activeNodes); + } + + } + } + + @Override + public boolean copyOf(MutableElement m) { + if (this != m) { + if (m instanceof Node) { + Node n = (Node) m; + if (function == n.getFunction()) { + if (column == n.getColumn() && row == n.getRow()) { + for (int i = 0; i < connections.length; i++) { + if (connections[i] != n.getConnection(i)) { + if (connections[i] instanceof Input && n.getConnection(i) instanceof Input) { + if (((Input) connections[i]).getIndex() != ((Input) n.getConnection(i)).getIndex()) { + return false; + } + } else if (connections[i] instanceof Node && n.getConnection(i) instanceof Node) { + if (((Node) connections[i]).getRow() != ((Node) n.getConnection(i)).getRow() && + ((Node) connections[i]).getColumn() != ((Node) n.getConnection(i)).getColumn()) { + return false; + } + } else { + return false; + } + } else { + return false; + } + } + return true; + } + } + } + } + return false; + } + + @Override + public String getDescription() { + return "n: " + row + ", " + column; + } +} diff --git a/src/jcgp/backend/population/Output.java b/src/jcgp/backend/population/Output.java new file mode 100644 index 0000000..aa94ab6 --- /dev/null +++ b/src/jcgp/backend/population/Output.java @@ -0,0 +1,69 @@ +package jcgp.backend.population; + +import java.util.ArrayList; + +public class Output extends Gene implements MutableElement { + + private Connection source; + private Chromosome chromosome; + private int index; + + public Output(Chromosome chromosome, int index) { + this.chromosome = chromosome; + this.index = index; + //this.source = new SimpleObjectProperty(); + } + + public Object calculate() { + Object result = source.getValue(); + return result; + } + + @Override + public void setConnection(int index, Connection newConnection) { + source = newConnection; + chromosome.recomputeActiveNodes(); + } + + public int getIndex() { + return index; + } + + public Connection getSource() { + return source; + } + +// public SimpleObjectProperty sourceProperty() { +// return source; +// } + + public void getActiveNodes(ArrayList activeNodes) { + if (source instanceof Node) { + ((Node) source).getActive(activeNodes); + } + } + + @Override + public boolean copyOf(MutableElement m) { + if (this != m) { + if (m instanceof Output) { + Output o = (Output) m; + if (index == o.getIndex()) { + if (source != o.getSource()) { + if (source instanceof Input && o.getSource() instanceof Input) { + if (((Input) source).getIndex() == ((Input) o.getSource()).getIndex()) { + return true; + } + } else if (source instanceof Node && o.getSource() instanceof Node) { + if (((Node) source).getRow() == ((Node) o.getSource()).getRow() && + ((Node) source).getColumn() == ((Node) o.getSource()).getColumn()) { + return true; + } + } + } + } + } + } + return false; + } +} diff --git a/src/jcgp/backend/population/Population.java b/src/jcgp/backend/population/Population.java new file mode 100644 index 0000000..7049d79 --- /dev/null +++ b/src/jcgp/backend/population/Population.java @@ -0,0 +1,45 @@ +package jcgp.backend.population; + +import jcgp.JCGP.Resources; + + +public class Population { + + private Chromosome[] chromosomes; + private int fittest; + + public Population(Resources resources) { + chromosomes = new Chromosome[(resources.getInt("popSize"))]; + for (int c = 0; c < chromosomes.length; c++) { + chromosomes[c] = new Chromosome(resources); + } + } + + public Population(Chromosome parent, Resources resources) { + chromosomes = new Chromosome[(resources.getInt("popSize"))]; + // make a clone for safety + this.chromosomes[0] = new Chromosome(parent); + // generate the rest of the individuals + for (int c = 1; c < chromosomes.length; c++) { + chromosomes[c] = new Chromosome(chromosomes[0]); + } + } + + /** + * Returns all chromosomes, parents first, then offspring. + * + * @param index + * @return + */ + public Chromosome getChromosome(int index) { + return chromosomes[index]; + } + + public void setBestIndividual(int index) { + fittest = index; + } + + public Chromosome getBestIndividual() { + return chromosomes[fittest]; + } +} diff --git a/src/jcgp/backend/tests/ChromosomeTests.java b/src/jcgp/backend/tests/ChromosomeTests.java new file mode 100644 index 0000000..1cd067e --- /dev/null +++ b/src/jcgp/backend/tests/ChromosomeTests.java @@ -0,0 +1,334 @@ +package jcgp.backend.tests; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import jcgp.JCGP.Resources; +import jcgp.backend.population.Chromosome; +import jcgp.backend.population.Connection; +import jcgp.backend.population.Input; +import jcgp.backend.population.MutableElement; +import jcgp.backend.population.Node; +import jcgp.backend.population.Output; + +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * + * Tests which cover the behaviour specified for a chromosome. + * + * - The chromosome should be able to return a specified node, input or output. + * - It should be able to return a random MutableElement. + * - It should be able to return a random allowed connection given a column. + * - It should be able to return a random connection. + * - It should contain a freely modifiable fitness value. + * - For truth table evaluations, it should be able to have its inputs set. + * - For truth table evaluations, the output should return a value according to the inputs. + * - It should feature a copy method, which creates a deep copy of a specified Chromosome object. + * - It should be able to return a list of active nodes. + * - It should contain a method to evaluate whether a given chromosome is identical + * to it. + * - Same as above, but only looking at the active portion of a chromosome. + * + * + * WARNING: changing parameters may cause the tests to incorrectly fail! + * + * @author Eduardo Pedroni + * + */ +public class ChromosomeTests { + + private Chromosome chromosome; + private static Resources resources; + + @BeforeClass + public static void setUpBeforeClass() { + resources = new Resources(); + } + + @Before + public void setUp() throws Exception { + chromosome = new Chromosome(resources); + } + + /** + * + */ + @Test + public void cloneTest() { + // create a clone, check to see if it really is a clone + Chromosome clone = new Chromosome(chromosome); + + // compare all elements, one by one + // check outputs + for (int o = 0; o < resources.getInt("outputs"); o++) { + // check that no cross-references exist between chromosomes + assertTrue("Cloned chromosome contains a reference to a member of the original chromosome.", + clone.getOutput(o) != chromosome.getOutput(o) && + clone.getOutput(o).getSource() != chromosome.getOutput(o).getSource()); + // check that the connections are equivalent + if (clone.getOutput(o).getSource() instanceof Input && chromosome.getOutput(o).getSource() instanceof Input) { + assertTrue("Outputs did not connect to equivalent inputs.", + ((Input) clone.getOutput(o).getSource()).getIndex() == ((Input) chromosome.getOutput(o).getSource()).getIndex()); + } else if (clone.getOutput(o).getSource() instanceof Node && chromosome.getOutput(o).getSource() instanceof Node) { + assertTrue("Outputs did not connect to equivalent nodes.", + ((Node) clone.getOutput(o).getSource()).getRow() == ((Node) chromosome.getOutput(o).getSource()).getRow() && + ((Node) clone.getOutput(o).getSource()).getColumn() == ((Node) chromosome.getOutput(o).getSource()).getColumn()); + } else { + fail("Output source types did not match."); + } + } + // check nodes, rows first + for (int row = 0; row < resources.getInt("rows"); row++) { + for (int column = 0; column < resources.getInt("columns"); column++) { + // check that nodes are not pointers to the same instance + assertTrue("Both chromosomes contain a reference to the same node.", clone.getNode(row, column) != chromosome.getNode(row, column)); + // check that both nodes reference their own position in the grid correctly + assertTrue("Equivalent nodes self-reference differently.", clone.getNode(row, column).getRow() == chromosome.getNode(row, column).getRow() && + clone.getNode(row, column).getColumn() == chromosome.getNode(row, column).getColumn()); + // check that the two nodes have the same function + assertTrue("Equivalent nodes have different functions.", clone.getNode(row, column).getFunction() == chromosome.getNode(row, column).getFunction()); + + // compare each connection + for (int connection = 0; connection < resources.getInt("arity"); connection++) { + // first look at whether they are actually the same instance + assertTrue("Nodes are connected to the same connection instance.", + clone.getNode(row, column).getConnection(connection) != chromosome.getNode(row, column).getConnection(connection)); + + // if the connections aren't the same instance, check that their addresses are the same + if (clone.getNode(row, column).getConnection(connection) instanceof Input && + chromosome.getNode(row, column).getConnection(connection) instanceof Input) { + + assertTrue("Nodes did not connect to equivalent inputs.", + ((Input) clone.getNode(row, column).getConnection(connection)).getIndex() == + ((Input) chromosome.getNode(row, column).getConnection(connection)).getIndex()); + + } else if (clone.getNode(row, column).getConnection(connection) instanceof Node && + chromosome.getNode(row, column).getConnection(connection) instanceof Node) { + + assertTrue("Nodes did not connect to equivalent nodes.", + ((Node) clone.getNode(row, column).getConnection(connection)).getRow() == + ((Node) chromosome.getNode(row, column).getConnection(connection)).getRow() && + + ((Node) clone.getNode(row, column).getConnection(connection)).getColumn() == + ((Node) chromosome.getNode(row, column).getConnection(connection)).getColumn()); + + } else { + fail("Connection types did not match."); + } + } + } + } + + // check cloning given a known topology + chromosome = createKnownConfiguration(); + clone = new Chromosome(chromosome); + + Integer[] testInputs = new Integer[] {5, 8, 4}; + chromosome.setInputs((Object[]) testInputs); + clone.setInputs((Object[]) testInputs); + + // check that both chromosomes have the same outputs + for (int i = 0; i < resources.getInt("outputs"); i++) { + assertTrue("Incorrect output returned", ((Integer) chromosome.getOutput(i).calculate()) == ((Integer) clone.getOutput(i).calculate())); + } + + // mutate an output in clone, check that the same node in chromosome produces a different output + clone.getOutput(1).setConnection(resources.getRandomInt(resources.getInt("arity")), clone.getInput(2)); + + assertTrue("Mutation affected nodes in both chromosomes.", + clone.getOutput(1).calculate() != chromosome.getOutput(1).calculate()); + + } + /** + * + */ + @Test + public void fitnessTest() { + // set a fitness value, check if returned value is the same + chromosome.setFitness(10); + assertTrue("Incorrect fitness returned.", chromosome.getFitness() == 10); + } + + /** + * + */ + @Test + public void randomConnectionTest() { + // get random connections with column 0, check that they are all inputs + for (int i = 0; i < 10000; i++) { + boolean connectionReturn = chromosome.getRandomConnection(0) instanceof Input; + assertTrue("Connection is not an input.", connectionReturn); + } + + // get random connections with the last column as reference, check that they're all within range + int connectionNodes = 0, connectionOutOfRange = 0, connectionInputs = 0, connectionPicks = 100000; + int chosenColumn = resources.getInt("columns") - 1; + for (int i = 0; i < connectionPicks; i++) { + Connection c = chromosome.getRandomConnection(chosenColumn); + if (c instanceof Node) { + connectionNodes++; + if (((Node) c).getColumn() >= chosenColumn) { + connectionOutOfRange++; + } + assertTrue("Connection is not allowed : " + ((Node) c).getColumn(), ((Node) c).getColumn() < chosenColumn && ((Node) c).getColumn() < chosenColumn); + } else if (c instanceof Input) { + connectionInputs++; + } else { + fail("Return is neither Node nor Input."); + + } + } + System.out.println("Out of " + connectionPicks + " connections picked from " + ((chosenColumn >= resources.getInt("levelsBack")) ? resources.getInt("levelsBack") : chosenColumn) * resources.getInt("rows") + + " allowed nodes and " + resources.getInt("inputs") + " inputs, " + connectionNodes + " were nodes and " + connectionInputs + " were inputs."); + + System.out.println("Node/input ratio: " + (chosenColumn >= resources.getInt("levelsBack") ? resources.getInt("levelsBack") : chosenColumn) * resources.getDouble("rows") / resources.getDouble("inputs") + + ", picked ratio: " + (double) connectionNodes / (double) connectionInputs); + + System.out.println(connectionOutOfRange + " nodes that disrespected levels back were picked."); + } + /** + * + */ + @Test + public void randomMutableTest() { + // get mutable elements, check Node to Output ratio + int mutablePicks = 100000; + int mutableNodes = 0, mutableOutputs = 0; + for (int i = 0; i < mutablePicks; i++) { + MutableElement m = chromosome.getRandomMutableElement(); + + if (m instanceof Node) { + mutableNodes++; + } else if (m instanceof Output) { + mutableOutputs++; + } else { + fail("Return is neither Node nor Output."); + } + } + System.out.println("Out of " + mutablePicks + " mutable elements picked from " + resources.getInt("nodes") + + " nodes and " + resources.getInt("outputs") + " outputs, " + mutableNodes + " were nodes and " + + mutableOutputs + " were outputs."); + System.out.println("Node/output ratio: " + resources.getDouble("nodes") / resources.getDouble("outputs") + + ", picked ratio: " + (double) mutableNodes / (double) mutableOutputs + "\n"); + } + + /** + * + */ + @Test + public void getOutputsTest() { + chromosome = createKnownConfiguration(); + + chromosome.setInputs(5, 8, 4); + + // with this configuration, the outputs should be 13 and 25. + assertTrue("Incorrect output returned.", (Integer) chromosome.getOutput(0).calculate() == 13); + assertTrue("Incorrect output returned.", (Integer) chromosome.getOutput(1).calculate() == 25); + } + + /** + * + */ + @Test + public void setInputTest() { + // set input values, check that acquired values are correct + Integer[] testInputs = new Integer[resources.getInt("inputs")]; + for (int i = 0; i < resources.getInt("inputs"); i++) { + testInputs[i] = i * 2 - 3; + } + chromosome.setInputs((Object[]) testInputs); + for (int i = 0; i < resources.getInt("inputs"); i++) { + assertTrue("Incorrect input returned.", ((Integer) chromosome.getInput(i).getValue()) == i * 2 - 3); + } + } + + /** + * + */ + @Test + public void getNodeTest() { + // get all nodes one by one, check that they are all correct + for (int r = 0; r < resources.getInt("rows"); r++) { + for (int c = 0; c < resources.getInt("columns"); c++) { + assertTrue("Incorrect node returned.", chromosome.getNode(r, c).getColumn() == c && + chromosome.getNode(r, c).getRow() == r); + } + } + } + + /** + * + */ + @Test + public void activeNodeTest() { + // active node detection happens recursively, the user only calls a single method + // set connections to a known configuration + chromosome = createKnownConfiguration(); + + assertTrue("Active node missing from list.", chromosome.getActiveNodes().contains(chromosome.getNode(0, 0))); + assertTrue("Active node missing from list.", chromosome.getActiveNodes().contains(chromosome.getNode(1, 1))); + assertTrue("Active node missing from list.", chromosome.getActiveNodes().contains(chromosome.getNode(1, 2))); + + assertTrue("List has the wrong number of nodes.", chromosome.getActiveNodes().size() == 3); + } + + /** + * + */ + @Test + public void compareActiveTest() { + // create a clone of the chromosome, compare active nodes - should return true + Chromosome c = new Chromosome(chromosome); + assertTrue("Active nodes did not match.", chromosome.compareActiveTo(c)); + assertTrue("Symmetry not obeyed.", c.compareActiveTo(chromosome)); + + // create a new random chromosome, this time they should not match + c = new Chromosome(resources); + assertTrue("Active nodes did match.", !chromosome.compareActiveTo(c)); + } + + /** + * + */ + @Test + public void compareTest() { + // create a clone of the chromosome, compare - should return true + Chromosome c = new Chromosome(chromosome); + assertTrue("Chromosomes did not match.", chromosome.compareTo(c)); + assertTrue("Symmetry not obeyed.", c.compareTo(chromosome)); + + // create a new random chromosome, this time they should not match + c = new Chromosome(resources); + assertTrue("Chromosomes did match.", !chromosome.compareTo(c)); + } + /** + * Utility for creating a chromosome of known configuration. + * Topology is 3x3, with 3 inputs and 2 outputs. + * Given inputs 5, 8 and 4 outputs should be 13 and 25. + * + * Active nodes (r, c): [0, 0], [1, 1], [1, 2] + * + * @return the configured chromosome + */ + private Chromosome createKnownConfiguration() { + // with a small topology, build a chromosome of known connections and check outputs + resources.set("columns", 3); + resources.set("rows", 3); + resources.set("inputs", 3); + resources.set("outputs", 2); + resources.set("levelsBack", 3); + + Chromosome c = new Chromosome(resources); + + c.getNode(0, 0).initialise(resources.getFunction(0), c.getInput(0), c.getInput(1)); + c.getNode(1, 1).initialise(resources.getFunction(0), c.getNode(0, 0), c.getInput(1)); + c.getNode(1, 2).initialise(resources.getFunction(0), c.getNode(1, 1), c.getInput(2)); + + c.getOutput(0).setConnection(0, c.getNode(0, 0)); + c.getOutput(1).setConnection(0, c.getNode(1, 2)); + + return c; + } +} diff --git a/src/jcgp/backend/tests/InputTests.java b/src/jcgp/backend/tests/InputTests.java new file mode 100644 index 0000000..4d15667 --- /dev/null +++ b/src/jcgp/backend/tests/InputTests.java @@ -0,0 +1,47 @@ +package jcgp.backend.tests; + +import static org.junit.Assert.assertTrue; +import jcgp.backend.population.Input; + +import org.junit.Before; +import org.junit.Test; + +/** + * + * Tests which cover the behaviour specified for an input. + * + * - An input contains a single set value. This value can be freely set for + * fitness evaluation purposes. + * - It must be addressable by an index set upon construction only. + * + * + * @author Eduardo Pedroni + * + */ +public class InputTests { + + private Input input; + // these are the test values + private final int inputValue = 19; + private final int inputIndex = 12; + + @Before + public void setUp() throws Exception { + input = new Input(inputIndex); + } + + @Test + public void valueTest() { + // assign a value to input, check that the returned value is correct + input.setValue(inputValue); + + assertTrue("Incorrect value returned.", ((Integer) input.getValue()) == inputValue); + } + + @Test + public void indexTest() { + // check that the index returned is the one passed to the constructor + assertTrue("Incorrect index returned.", input.getIndex() == inputIndex); + } + +} diff --git a/src/jcgp/backend/tests/NodeTests.java b/src/jcgp/backend/tests/NodeTests.java new file mode 100644 index 0000000..7121e81 --- /dev/null +++ b/src/jcgp/backend/tests/NodeTests.java @@ -0,0 +1,196 @@ +package jcgp.backend.tests; + +import static org.junit.Assert.assertTrue; +import jcgp.JCGP.Resources; +import jcgp.backend.function.Arithmetic; +import jcgp.backend.function.Function; +import jcgp.backend.population.Chromosome; +import jcgp.backend.population.Connection; +import jcgp.backend.population.Node; + +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * + * Tests which cover the behaviour specified for a node. + * + * - A node should contain read-only row and column values which are set upon construction. + * - It should contain a fully accessible Function object. + * - It should contain a set of connections which can be initialised and randomly + * modified. It should be able to return an addressed connection. + * - It should be able to compute a value using its function with its connections as arguments. + * + * WARNING: changing parameters may cause the tests to incorrectly fail! + * + * @author Eduardo Pedroni + * + */ +public class NodeTests { + + private Node node; + private static Chromosome chromosome; + private static Resources resources; + // these numbers will be used by the node under test + private final int arg1 = 2; + private final int arg2 = 5; + + @BeforeClass + public static void setUpBeforeClass() { + + resources = new Resources(); + + chromosome = new Chromosome(resources); + } + + @Before + public void setUp() throws Exception { + node = new Node(chromosome, 0, 0, resources.getInt("arity")); + // make node with anonymous addition function and hard-coded value connections + node.initialise(new Arithmetic.Addition(), + new Connection[]{new Connection() { + + @Override + public Object getValue() { + // hardcode a value + return arg1; + } + + @Override + public String getDescription() { + // blank + return null; + } + + }, + new Connection() { + + @Override + public Object getValue() { + // hardcode a value + return arg2; + } + + @Override + public String getDescription() { + // blank + return null; + } + + }}); + } + + @Test + public void rowAndColumnTest() { + assertTrue("Incorrect row.", node.getRow() == 0); + assertTrue("Incorrect column.", node.getColumn() == 0); + } + + @Test + public void functionTest() { + // make a new function and assign to node + Function f = new Function() { + + @Override + public Object run(Connection... connections) { + // blank + return 0; + } + + @Override + public int getArity() { + // blank + return 0; + } + + @Override + public String getName() { + // blank + return null; + } + }; + + node.setFunction(f); + + // check that the function returned by the node is f + assertTrue("Incorrect function returned.", node.getFunction() == f); + // check that it outputs 0 as it should + assertTrue("Incorrect function output.", ((Integer) node.getValue()) == 0); + } + + @Test + public void evaluationTest() { + // check that addition is working + assertTrue("Node did not return expected value (sum of arguments). Output was: " + ((int) node.getValue()), + ((int) node.getValue()) == arg1 + arg2); + + // put in a different function, check the output has changed appropriately + node.setFunction(new Arithmetic.Subtraction()); + + assertTrue("Node did not return expected value (difference of arguments).", ((Integer) node.getValue()) == arg1 - arg2); + + } + + @Test + public void connectionsTest() { + // make new blank connections, check that they are returned correctly when addressed + Connection conn0, conn1, conn2; + conn0 = new Connection() { + + @Override + public Object getValue() { + // blank + return 0; + } + + @Override + public String getDescription() { + // blank + return null; + } + + }; + conn1 = new Connection() { + + @Override + public Object getValue() { + // blank + return 0; + } + + @Override + public String getDescription() { + // blank + return null; + } + + }; + node.initialise(null, conn0, conn1); + + assertTrue("Connection 0 is incorrect.", node.getConnection(0) == conn0); + assertTrue("Connection 1 is incorrect.", node.getConnection(1) == conn1); + + // make yet another connection, set it randomly, check that it is one of the node's connections + conn2 = new Connection() { + + @Override + public Object getValue() { + // blank + return 0; + } + + @Override + public String getDescription() { + // blank + return null; + } + }; + node.setConnection(resources.getRandomInt(resources.getInt("arity")), conn2); + + assertTrue("Connection was not found in node.", node.getConnection(0) == conn2 || node.getConnection(1) == conn2); + + } + + +} diff --git a/src/jcgp/backend/tests/OutputTests.java b/src/jcgp/backend/tests/OutputTests.java new file mode 100644 index 0000000..7ff8a4a --- /dev/null +++ b/src/jcgp/backend/tests/OutputTests.java @@ -0,0 +1,93 @@ +package jcgp.backend.tests; + +import static org.junit.Assert.assertTrue; +import jcgp.JCGP.Resources; +import jcgp.backend.population.Chromosome; +import jcgp.backend.population.Connection; +import jcgp.backend.population.Output; + +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * + * Tests which cover the behaviour specified for an output. + * + * - An output contains a single source Connection, which can be set and got. + * - It should return the value of its source connection. + * - It must be addressable by an index set upon construction only. + * + * + * @author Eduardo Pedroni + * + */ +public class OutputTests { + + private Output output; + private static Chromosome chromosome; + private static Resources resources; + // these are the test values + private final int outputValue = 10; + private final int outputIndex = 2; + + @BeforeClass + public static void setUpBeforeClass() { + resources = new Resources(); + chromosome = new Chromosome(resources); + } + + @Before + public void setUp() throws Exception { + output = new Output(chromosome, outputIndex); + } + + @Test + public void evaluationsTest() { + // set source connection, check that the appropriate value is returned + output.setConnection(0, new Connection() { + + @Override + public Object getValue() { + // test value + return outputValue; + } + + @Override + public String getDescription() { + // blank + return null; + } + }); + + assertTrue("Incorrect evaluation.", ((Integer) output.calculate()) == outputValue); + } + + @Test + public void connectionTest() { + // set a new connection, check that it is correctly returned + Connection newConn = new Connection() { + + @Override + public Object getValue() { + // blank + return 0; + } + + @Override + public String getDescription() { + // blank + return null; + } + }; + output.setConnection(0, newConn); + + assertTrue("Incorrect connection returned.", output.getSource() == newConn); + } + + @Test + public void indexTest() { + // check that the index returned is the one passed to the constructor + assertTrue("Incorrect index returned.", output.getIndex() == outputIndex); + } +} diff --git a/src/jcgp/backend/tests/PopulationTests.java b/src/jcgp/backend/tests/PopulationTests.java new file mode 100644 index 0000000..51b5168 --- /dev/null +++ b/src/jcgp/backend/tests/PopulationTests.java @@ -0,0 +1,86 @@ +package jcgp.backend.tests; + +import static org.junit.Assert.assertTrue; +import jcgp.JCGP.Resources; +import jcgp.backend.population.Chromosome; +import jcgp.backend.population.Population; + +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * + * Tests which cover the behaviour specified for a population. + * + * - It should be possible to iterate through all the chromosomes in a population. + * - When constructed with no arguments, it should generate populationSize + * random chromosomes, distributed according to the EA parameters. + * - If one or more chromosomes are passed into the constructor, it should use them + * as parents to create the rest of the population. + * + * + * @author Eduardo Pedroni + * + */ +public class PopulationTests { + + private Population population; + private static Resources resources; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + resources = new Resources(); + + +// // initialise function set +// FunctionSet functionSet = new FunctionSet(new Arithmetic.Addition(), new Arithmetic.Subtraction()); +// +// // initialise utilities +// Utilities.setResources(new Random(1234), functionSet); +// +// // initialise parameters +// Resources.setColumns(20); +// Resources.setRows(20); +// Resources.setInputs(2); +// Resources.setOutputs(4); +// Resources.setLevelsBack(1); +// Resources.setMutationRate(10); +// Resources.setTotalGenerations(100); +// Resources.setTotalRuns(5); +// Resources.setPopulationSize(1, 4); +// Resources.setMaxArity(functionSet.getMaxArity()); + } + + @Before + public void setUp() throws Exception { + population = new Population(resources); + } + + @Test + public void defaultPopulationTest() { + // check that the constructor really generates populationSize chromosomes when none is given + int chromosomes = 0; + while (true) { + try { + population.getChromosome(chromosomes); + } catch (IndexOutOfBoundsException e) { + break; + } + chromosomes++; + } + + assertTrue("Incorrect number of chromosomes generated.", chromosomes == resources.getInt("popSize")); + } + + @Test + public void preinitialisedChromosomeTest() { + // the original chromosome that will be cloned + Chromosome oc = new Chromosome(resources); + + // initialise a population with a copy of it + population = new Population(oc, resources); + // check that the first parent chromosome is identical to, but not the same instance as, the one given + assertTrue("Incorrect chromosome in population.", population.getChromosome(0).compareTo(oc) && population.getChromosome(0) != oc); + } +} diff --git a/src/jcgp/exceptions/InsufficientConnectionsException.java b/src/jcgp/exceptions/InsufficientConnectionsException.java deleted file mode 100644 index 2ffc10f..0000000 --- a/src/jcgp/exceptions/InsufficientConnectionsException.java +++ /dev/null @@ -1,10 +0,0 @@ -package jcgp.exceptions; - -public class InsufficientConnectionsException extends RuntimeException { - - /** - * - */ - private static final long serialVersionUID = 660740514800883541L; - -} diff --git a/src/jcgp/exceptions/InvalidArgumentsException.java b/src/jcgp/exceptions/InvalidArgumentsException.java deleted file mode 100644 index 537018d..0000000 --- a/src/jcgp/exceptions/InvalidArgumentsException.java +++ /dev/null @@ -1,20 +0,0 @@ -package jcgp.exceptions; - -public class InvalidArgumentsException extends RuntimeException { - - /** - * - */ - private static final long serialVersionUID = 2675108124600817777L; - private String reason; - - public InvalidArgumentsException(String reason) { - super(); - this.reason = reason; - } - - public String getReason() { - return reason; - } - -} diff --git a/src/jcgp/exceptions/ManagedModuleException.java b/src/jcgp/exceptions/ManagedModuleException.java deleted file mode 100644 index a327dfb..0000000 --- a/src/jcgp/exceptions/ManagedModuleException.java +++ /dev/null @@ -1,10 +0,0 @@ -package jcgp.exceptions; - -public class ManagedModuleException extends RuntimeException { - - /** - * - */ - private static final long serialVersionUID = -3450063156524494967L; - -} diff --git a/src/jcgp/exceptions/ParameterMismatchException.java b/src/jcgp/exceptions/ParameterMismatchException.java deleted file mode 100644 index 93a8f10..0000000 --- a/src/jcgp/exceptions/ParameterMismatchException.java +++ /dev/null @@ -1,10 +0,0 @@ -package jcgp.exceptions; - -public class ParameterMismatchException extends RuntimeException { - - /** - * - */ - private static final long serialVersionUID = -3161318886125868134L; - -} diff --git a/src/jcgp/function/Arithmetic.java b/src/jcgp/function/Arithmetic.java deleted file mode 100644 index b61ee65..0000000 --- a/src/jcgp/function/Arithmetic.java +++ /dev/null @@ -1,139 +0,0 @@ -package jcgp.function; - -import java.util.ArrayList; -import java.util.Arrays; - -import jcgp.exceptions.InvalidArgumentsException; -import jcgp.population.Connection; - -public class Arithmetic extends FunctionSet { - - public Arithmetic() { - name = "Arithmetic"; - functionList = new Function[]{ - new Addition(), - new Subtraction(), - new Multiplication(), - new Division()}; - - allowedFunctions = new ArrayList(Arrays.asList(functionList)); - } - - public static class Addition extends Function { - - private int arity = 2; - - @Override - public Integer run(Connection... connections) { - if (connections.length < arity) { - throw new InvalidArgumentsException("Not enough connections were given."); - } else { - Integer arg1 = ((Integer) connections[0].getValue()); - Integer arg2 = ((Integer) connections[1].getValue()); - Integer result = arg1 + arg2; - - return result; - } - } - - @Override - public int getArity() { - return arity; - } - - @Override - public String getName() { - return "Addition"; - } - } - - public static class Subtraction extends Function { - - private int arity = 2; - - @Override - public Integer run(Connection... connections) { - if (connections.length < arity) { - throw new InvalidArgumentsException("Not enough connections were given."); - } else { - Integer arg1 = ((Integer) connections[0].getValue()); - Integer arg2 = ((Integer) connections[1].getValue()); - Integer result = arg1 - arg2; - - return result; - } - } - - @Override - public int getArity() { - return arity; - } - - @Override - public String getName() { - return "Subtraction"; - } - } - - public static class Multiplication extends Function { - - private int arity = 2; - - @Override - public Integer run(Connection... connections) { - if (connections.length < arity) { - throw new InvalidArgumentsException("Not enough connections were given."); - } else { - Integer arg1 = ((Integer) connections[0].getValue()); - Integer arg2 = ((Integer) connections[1].getValue()); - Integer result = arg1 * arg2; - - return result; - } - } - - @Override - public int getArity() { - return arity; - } - - @Override - public String getName() { - return "Multiplication"; - } - } - - public static class Division extends Function { - - private int arity = 2; - - @Override - public Integer run(Connection... connections) { - if (connections.length < arity) { - throw new InvalidArgumentsException("Not enough connections were given."); - } else { - Integer arg1 = ((Integer) connections[0].getValue()); - Integer arg2 = ((Integer) connections[1].getValue()); - Integer result; - if (arg2 == 0) { - result = 0; - } else { - result = arg1 / arg2; - } - - return result; - } - } - - @Override - public int getArity() { - return arity; - } - - @Override - public String getName() { - return "Division"; - } - } - -} diff --git a/src/jcgp/function/BitwiseLogic.java b/src/jcgp/function/BitwiseLogic.java deleted file mode 100644 index 7ced8e8..0000000 --- a/src/jcgp/function/BitwiseLogic.java +++ /dev/null @@ -1,215 +0,0 @@ -package jcgp.function; - -import java.util.ArrayList; -import java.util.Arrays; - -import jcgp.exceptions.InvalidArgumentsException; -import jcgp.population.Connection; - -public class BitwiseLogic extends FunctionSet { - - public BitwiseLogic() { - name = "32-bit Logic"; - functionList = new Function[]{ - new And(), - new Or(), - new Not(), - new Xor(), - new Nand(), - new Nor(), - new Xnor()}; - - allowedFunctions = new ArrayList(Arrays.asList(functionList)); - } - - public static class And extends Function { - private int arity = 2; - - @Override - public Object run(Connection... connections) { - if (connections.length < arity) { - throw new InvalidArgumentsException("Not enough connections were given."); - } else { - int arg1 = ((int) connections[0].getValue()); - int arg2 = ((int) connections[1].getValue()); - int result = arg1 & arg2; - - return result; - } - } - - @Override - public int getArity() { - return arity; - } - - @Override - public String getName() { - return "AND"; - } - } - - public static class Or extends Function { - private int arity = 2; - - @Override - public Object run(Connection... connections) { - if (connections.length < arity) { - throw new InvalidArgumentsException("Not enough connections were given."); - } else { - int arg1 = ((int) connections[0].getValue()); - int arg2 = ((int) connections[1].getValue()); - int result = arg1 | arg2; - - return result; - } - } - - @Override - public int getArity() { - return arity; - } - - @Override - public String getName() { - return "OR"; - } - } - - public static class Not extends Function { - private int arity = 1; - - @Override - public Object run(Connection... connections) { - if (connections.length < arity) { - throw new InvalidArgumentsException("Not enough connections were given."); - } else { - int arg1 = ((int) connections[0].getValue()); - int result = ~arg1; - - return result; - } - } - - @Override - public int getArity() { - return arity; - } - - @Override - public String getName() { - return "NOT"; - } - } - - public static class Xor extends Function { - private int arity = 2; - - @Override - public Object run(Connection... connections) { - if (connections.length < arity) { - throw new InvalidArgumentsException("Not enough connections were given."); - } else { - int arg1 = ((int) connections[0].getValue()); - int arg2 = ((int) connections[1].getValue()); - int result = arg1 ^ arg2; - - return result; - } - } - - @Override - public int getArity() { - return arity; - } - - @Override - public String getName() { - return "XOR"; - } - } - - public static class Nand extends Function { - private int arity = 2; - - @Override - public Object run(Connection... connections) { - if (connections.length < arity) { - throw new InvalidArgumentsException("Not enough connections were given."); - } else { - int arg1 = ((int) connections[0].getValue()); - int arg2 = ((int) connections[1].getValue()); - int result = arg1 & arg2; - - return ~result; - } - } - - @Override - public int getArity() { - return arity; - } - - @Override - public String getName() { - return "NAND"; - } - } - - public static class Nor extends Function { - private int arity = 2; - - @Override - public Object run(Connection... connections) { - if (connections.length < arity) { - throw new InvalidArgumentsException("Not enough connections were given."); - } else { - int arg1 = ((int) connections[0].getValue()); - int arg2 = ((int) connections[1].getValue()); - int result = arg1 | arg2; - - return ~result; - } - } - - @Override - public int getArity() { - return arity; - } - - @Override - public String getName() { - return "NOR"; - } - } - - public static class Xnor extends Function { - private int arity = 2; - - @Override - public Object run(Connection... connections) { - if (connections.length < arity) { - throw new InvalidArgumentsException("Not enough connections were given."); - } else { - int arg1 = ((int) connections[0].getValue()); - int arg2 = ((int) connections[1].getValue()); - int result = arg1 ^ arg2; - - return ~result; - } - } - - @Override - public int getArity() { - return arity; - } - - @Override - public String getName() { - return "XNOR"; - } - } - - - -} diff --git a/src/jcgp/function/BooleanLogic.java b/src/jcgp/function/BooleanLogic.java deleted file mode 100644 index 7e441f2..0000000 --- a/src/jcgp/function/BooleanLogic.java +++ /dev/null @@ -1,215 +0,0 @@ -package jcgp.function; - -import java.util.ArrayList; -import java.util.Arrays; - -import jcgp.exceptions.InvalidArgumentsException; -import jcgp.population.Connection; - -public class BooleanLogic extends FunctionSet { - - public BooleanLogic() { - name = "1-bit Logic"; - functionList = new Function[]{ - new And(), - new Or(), - new Not(), - new Xor(), - new Nand(), - new Nor(), - new Xnor()}; - - allowedFunctions = new ArrayList(Arrays.asList(functionList)); - } - - public static class And extends Function { - private int arity = 2; - - @Override - public Boolean run(Connection... connections) { - if (connections.length < arity) { - throw new InvalidArgumentsException("Not enough connections were given."); - } else { - Boolean arg1 = ((Boolean) connections[0].getValue()); - Boolean arg2 = ((Boolean) connections[1].getValue()); - Boolean result = arg1 && arg2; - - return result; - } - } - - @Override - public int getArity() { - return arity; - } - - @Override - public String getName() { - return "AND"; - } - } - - public static class Or extends Function { - private int arity = 2; - - @Override - public Boolean run(Connection... connections) { - if (connections.length < arity) { - throw new InvalidArgumentsException("Not enough connections were given."); - } else { - Boolean arg1 = ((Boolean) connections[0].getValue()); - Boolean arg2 = ((Boolean) connections[1].getValue()); - Boolean result = arg1 || arg2; - - return result; - } - } - - @Override - public int getArity() { - return arity; - } - - @Override - public String getName() { - return "OR"; - } - } - - public static class Not extends Function { - private int arity = 1; - - @Override - public Boolean run(Connection... connections) { - if (connections.length < arity) { - throw new InvalidArgumentsException("Not enough connections were given."); - } else { - Boolean arg1 = ((Boolean) connections[0].getValue()); - Boolean result = !arg1; - - return result; - } - } - - @Override - public int getArity() { - return arity; - } - - @Override - public String getName() { - return "NOT"; - } - } - - public static class Xor extends Function { - private int arity = 2; - - @Override - public Boolean run(Connection... connections) { - if (connections.length < arity) { - throw new InvalidArgumentsException("Not enough connections were given."); - } else { - Boolean arg1 = ((Boolean) connections[0].getValue()); - Boolean arg2 = ((Boolean) connections[1].getValue()); - Boolean result = arg1 ^ arg2; - - return result; - } - } - - @Override - public int getArity() { - return arity; - } - - @Override - public String getName() { - return "XOR"; - } - } - - public static class Nand extends Function { - private int arity = 2; - - @Override - public Boolean run(Connection... connections) { - if (connections.length < arity) { - throw new InvalidArgumentsException("Not enough connections were given."); - } else { - Boolean arg1 = ((Boolean) connections[0].getValue()); - Boolean arg2 = ((Boolean) connections[1].getValue()); - Boolean result = arg1 && arg2; - - return !result; - } - } - - @Override - public int getArity() { - return arity; - } - - @Override - public String getName() { - return "NAND"; - } - } - - public static class Nor extends Function { - private int arity = 2; - - @Override - public Boolean run(Connection... connections) { - if (connections.length < arity) { - throw new InvalidArgumentsException("Not enough connections were given."); - } else { - Boolean arg1 = ((Boolean) connections[0].getValue()); - Boolean arg2 = ((Boolean) connections[1].getValue()); - Boolean result = arg1 || arg2; - - return !result; - } - } - - @Override - public int getArity() { - return arity; - } - - @Override - public String getName() { - return "NOR"; - } - } - - public static class Xnor extends Function { - private int arity = 2; - - @Override - public Boolean run(Connection... connections) { - if (connections.length < arity) { - throw new InvalidArgumentsException("Not enough connections were given."); - } else { - Boolean arg1 = ((Boolean) connections[0].getValue()); - Boolean arg2 = ((Boolean) connections[1].getValue()); - Boolean result = arg1 ^ arg2; - - return !result; - } - } - - @Override - public int getArity() { - return arity; - } - - @Override - public String getName() { - return "XNOR"; - } - } - - - -} diff --git a/src/jcgp/function/Function.java b/src/jcgp/function/Function.java deleted file mode 100644 index 64dd206..0000000 --- a/src/jcgp/function/Function.java +++ /dev/null @@ -1,13 +0,0 @@ -package jcgp.function; - -import jcgp.exceptions.InvalidArgumentsException; -import jcgp.population.Connection; - -public abstract class Function { - - public abstract Object run(Connection ... connections) throws InvalidArgumentsException; - - public abstract int getArity(); - - public abstract String getName(); -} diff --git a/src/jcgp/function/FunctionSet.java b/src/jcgp/function/FunctionSet.java deleted file mode 100644 index fef8f88..0000000 --- a/src/jcgp/function/FunctionSet.java +++ /dev/null @@ -1,74 +0,0 @@ -package jcgp.function; - -import java.util.ArrayList; -import java.util.Iterator; - - -/** - * - * @author Eduardo Pedroni - * - */ -public abstract class FunctionSet { - protected Function[] functionList; - protected ArrayList allowedFunctions; - protected String name; - - public int getAllowedFunctionCount() { - return allowedFunctions.size(); - } - - public int getTotalFunctionCount() { - return functionList.length; - } - - public Function getAllowedFunction(int index) { - return allowedFunctions.get(index); - } - - public Function getFunction(int index) { - return functionList[index]; - } - - public int getMaxArity(){ - int arity = 0; - for (Function function : allowedFunctions) { - if (function.getArity() > arity) { - arity = function.getArity(); - } - } - return arity; - } - - public String getName() { - return name; - } - - public void disableFunction(int index) { - if (index < functionList.length) { - for (Iterator iterator = allowedFunctions.iterator(); iterator.hasNext();) { - Function function = (Function) iterator.next(); - if (function == functionList[index]) { - iterator.remove(); - } - } - } else { - throw new IndexOutOfBoundsException("Function " + index + " does not exist, the set only has " + functionList.length + " functions."); - } - } - - public void enableFunction(int index) { - if (!allowedFunctions.contains(functionList[index])) { - allowedFunctions.add(functionList[index]); - } - } - - @Override - public String toString() { - return name; - } - - public boolean isEnabled(Function f) { - return allowedFunctions.contains(f); - } - } \ No newline at end of file diff --git a/src/jcgp/gui/ChromosomePane.java b/src/jcgp/gui/ChromosomePane.java index b4a628f..b1f4bf0 100644 --- a/src/jcgp/gui/ChromosomePane.java +++ b/src/jcgp/gui/ChromosomePane.java @@ -6,14 +6,14 @@ import javafx.scene.control.ScrollPane; import javafx.scene.layout.Pane; import javafx.scene.shape.Line; import jcgp.JCGP.Resources; +import jcgp.backend.population.Chromosome; +import jcgp.backend.population.Connection; +import jcgp.backend.population.Input; +import jcgp.backend.population.Node; import jcgp.gui.population.GUIGene; import jcgp.gui.population.GUIInput; import jcgp.gui.population.GUINode; import jcgp.gui.population.GUIOutput; -import jcgp.population.Chromosome; -import jcgp.population.Connection; -import jcgp.population.Input; -import jcgp.population.Node; public class ChromosomePane extends ScrollPane { @@ -26,14 +26,14 @@ public class ChromosomePane extends ScrollPane { private ArrayList connectionLines; + private ArrayList relock = new ArrayList(); + private boolean target = false; public ChromosomePane(Chromosome chromosome, Resources resources) { super(); connectionLines = new ArrayList(); - //setMouseTransparent(true); - content = new Pane(); content.setId("content pane for genes"); @@ -119,4 +119,20 @@ public class ChromosomePane extends ScrollPane { guiOutputs[i].updateLines(); } } + + public void unlockOutputs() { + relock.clear(); + for (int i = 0; i < guiOutputs.length; i++) { + if (guiOutputs[i].isLocked()) { + guiOutputs[i].unlock(); + relock.add(guiOutputs[i]); + } + } + } + + public void relockOutputs() { + for (int i = 0; i < relock.size(); i++) { + relock.get(i).lock(); + } + } } diff --git a/src/jcgp/gui/GUI.java b/src/jcgp/gui/GUI.java new file mode 100644 index 0000000..7e7f385 --- /dev/null +++ b/src/jcgp/gui/GUI.java @@ -0,0 +1,211 @@ +package jcgp.gui; + +import javafx.application.Application; +import javafx.application.Platform; +import javafx.concurrent.Service; +import javafx.concurrent.Task; +import javafx.scene.Scene; +import javafx.scene.control.Tab; +import javafx.scene.control.TabPane; +import javafx.scene.control.TabPane.TabClosingPolicy; +import javafx.scene.layout.BorderPane; +import javafx.stage.Stage; +import jcgp.JCGP; +import jcgp.JCGP.Resources; +import jcgp.gui.console.GUIConsole; +import jcgp.gui.settings.SettingsPane; + +public class GUI extends Application { + + /* Colours */ + /** NEUTRAL_COLOUR is the colour elements should be when no interaction is occurring + * (no hovering, clicking, dragging or any other form of interaction). */ + public static final String NEUTRAL_COLOUR = "#FFFFFF"; + public static final String HARD_HIGHLIGHT_COLOUR = "#5496FF"; + // 89AAD6 + public static final String MEDIUM_HIGHLIGHT_COLOUR = "#75BAFF"; + public static final String SOFT_HIGHLIGHT_COLOUR = "#C7DFFF"; + // BDFFC2 + public static final String GOOD_SELECTION_COLOUR = "#38C25B"; + // FBFFB8 + public static final String NEUTRAL_SELECTION_COLOUR = "#EDEB72"; + // FF9C9C + public static final String BAD_SELECTION_COLOUR = "#F53D3D"; + + + /* Sizes and distances */ + public static final double RESIZE_MARGIN = 5.0; + + public static final double SETTINGS_WIDTH = 200; + public static final double CONSOLE_HEIGHT = 100; + + public static final double WRAP_WIDTH = 90; + + private static JCGP cgp; + public static Resources resources; + + private BorderPane leftPane; + private BorderPane window; + + private ChromosomePane[] chromosomes; + private TabPane chromosomeTabs; + + private GUIConsole console = new GUIConsole(); + private SettingsPane settings; + + private Service cgpService; + + private boolean evolving = false; + + private Object printLock = new Object(); + + private Runnable consoleFlush = new Runnable() { + @Override + public void run() { + synchronized(printLock) { + console.flush(); + printLock.notifyAll(); + } + } + }; + + public static void main(String[] args) { + cgp = new JCGP(); + resources = cgp.getResources(); + + launch(); + } + + @Override + public void start(Stage primaryStage) throws Exception { + resources.setConsole(console); + + cgpService = new Service () { + @Override + protected Task createTask() { + + Task t = new Task() { + @Override + protected Void call() throws Exception { + while (!isCancelled()) { + Platform.runLater(consoleFlush); + synchronized (printLock) { + cgp.nextGeneration(); + printLock.wait(); + } + } + return null; + } + }; + return t; + } + }; + + /* + * Instantiate the various GUI elements here. + * + * + */ + + leftPane = new BorderPane(); + + chromosomeTabs = new TabPane(); + chromosomeTabs.setTabClosingPolicy(TabClosingPolicy.UNAVAILABLE); + makeChromosomeTabPane(); + + settings = new SettingsPane(cgp, this); + + leftPane.setCenter(chromosomeTabs); + leftPane.setBottom(console); + + window = new BorderPane(); + + window.setCenter(leftPane); + window.setRight(settings); + + primaryStage.setTitle("JCGP"); + + primaryStage.setScene(new Scene(window)); + primaryStage.show(); + } + + /** + * + */ + private void makeChromosomeTabPane() { + chromosomeTabs.getTabs().clear(); + + chromosomes = new ChromosomePane[cgp.getResources().getInt("popSize")]; + Tab tab; + for (int i = 0; i < chromosomes.length; i++) { + chromosomes[i] = new ChromosomePane(cgp.getPopulation().getChromosome(i), resources); + tab = new Tab("Chr " + i); + tab.setContent(chromosomes[i]); + chromosomeTabs.getTabs().add(tab); + } + } + + private void updateNodeGrids() { + for (int i = 0; i < chromosomes.length; i++) { + chromosomes[i].update(); + } + } + + private void unlockOutputs() { + for (int i = 0; i < chromosomes.length; i++) { + chromosomes[i].unlockOutputs(); + } + } + + private void relockOutputs() { + for (int i = 0; i < chromosomes.length; i++) { + chromosomes[i].relockOutputs(); + } + } + + public void disableChromosomePanes(boolean value) { + chromosomeTabs.setDisable(value); + } + + public void playPause() { + if (!evolving) { + settings.disableSettings(true); + disableChromosomePanes(true); + unlockOutputs(); + evolving = true; + cgpService.restart(); + } else { + settings.disableSettings(false); + disableChromosomePanes(false); + updateNodeGrids(); + evolving = false; + cgpService.cancel(); + relockOutputs(); + } + } + + public void step() { + if (!evolving) { + Thread t = new Thread(new Task() { + @Override + protected Void call() throws Exception { + unlockOutputs(); + cgp.nextGeneration(); + console.flush(); + updateNodeGrids(); + relockOutputs(); + return null; + } + }); + t.start(); + } + } + + public void resetCGP() { + cgp.remakePopulation(); + makeChromosomeTabPane(); + + resources.set("currentGen", 1); + resources.set("currentRun", 1); + } +} diff --git a/src/jcgp/gui/Messenger.java b/src/jcgp/gui/Messenger.java deleted file mode 100644 index becf47c..0000000 --- a/src/jcgp/gui/Messenger.java +++ /dev/null @@ -1,7 +0,0 @@ -package jcgp.gui; - -public class Messenger { - - - -} diff --git a/src/jcgp/gui/console/Console.java b/src/jcgp/gui/console/Console.java new file mode 100644 index 0000000..63c7f5b --- /dev/null +++ b/src/jcgp/gui/console/Console.java @@ -0,0 +1,11 @@ +package jcgp.gui.console; + +public interface Console { + + public void println(String s); + + public void print(String s); + + public void flush(); + +} diff --git a/src/jcgp/gui/console/GUIConsole.java b/src/jcgp/gui/console/GUIConsole.java index 0ef2be3..8fdb1a5 100644 --- a/src/jcgp/gui/console/GUIConsole.java +++ b/src/jcgp/gui/console/GUIConsole.java @@ -5,13 +5,15 @@ import javafx.scene.Cursor; import javafx.scene.control.TextArea; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; -import jcgp.GUI; +import jcgp.gui.GUI; -public class GUIConsole extends AnchorPane { +public class GUIConsole extends AnchorPane implements Console { private boolean dragging; private TextArea textArea = new TextArea("Welcome to JCGP!\n"); + private StringBuffer printBuffer = new StringBuffer(); + public GUIConsole() { super(); textArea.setEditable(false); @@ -87,8 +89,20 @@ public class GUIConsole extends AnchorPane { return event.getY() < (GUI.RESIZE_MARGIN); } - public TextArea getTextArea() { - return textArea; + @Override + public void println(String s) { + printBuffer.append(s + "\n"); + } + + @Override + public void print(String s) { + printBuffer.append(s); + } + + @Override + public void flush() { + textArea.appendText(printBuffer.toString()); + printBuffer = new StringBuffer(); } } diff --git a/src/jcgp/gui/population/GUIGene.java b/src/jcgp/gui/population/GUIGene.java index a37eb19..26be2a5 100644 --- a/src/jcgp/gui/population/GUIGene.java +++ b/src/jcgp/gui/population/GUIGene.java @@ -4,9 +4,9 @@ import javafx.beans.property.SimpleObjectProperty; import javafx.scene.Group; import javafx.scene.shape.Circle; import javafx.scene.text.Text; +import jcgp.backend.population.Connection; +import jcgp.backend.population.Gene; import jcgp.gui.ChromosomePane; -import jcgp.population.Connection; -import jcgp.population.Gene; enum GUIGeneState { NEUTRAL, @@ -59,7 +59,7 @@ public abstract class GUIGene extends Group { return locked; } - public abstract void setLocked(boolean value); + abstract void setLocked(boolean value); public abstract void addLocks(int value); diff --git a/src/jcgp/gui/population/GUIInput.java b/src/jcgp/gui/population/GUIInput.java index 30ce4ac..f47186c 100644 --- a/src/jcgp/gui/population/GUIInput.java +++ b/src/jcgp/gui/population/GUIInput.java @@ -11,11 +11,11 @@ import javafx.scene.shape.Circle; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.scene.text.TextAlignment; -import jcgp.GUI; +import jcgp.backend.population.Connection; +import jcgp.backend.population.Input; +import jcgp.backend.population.Output; import jcgp.gui.ChromosomePane; -import jcgp.population.Connection; -import jcgp.population.Input; -import jcgp.population.Output; +import jcgp.gui.GUI; public class GUIInput extends GUIGene { @@ -212,7 +212,7 @@ public class GUIInput extends GUIGene { } @Override - public void setLocked(boolean value) { + void setLocked(boolean value) { locked += value ? 1 : -1; stateProperty.set(locked > 0 ? GUIGeneState.HOVER : GUIGeneState.ACTIVE_HOVER); } diff --git a/src/jcgp/gui/population/GUINode.java b/src/jcgp/gui/population/GUINode.java index 6fc84da..450647f 100644 --- a/src/jcgp/gui/population/GUINode.java +++ b/src/jcgp/gui/population/GUINode.java @@ -13,11 +13,11 @@ import javafx.scene.shape.Line; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.scene.text.TextAlignment; -import jcgp.GUI; +import jcgp.backend.population.Connection; +import jcgp.backend.population.Input; +import jcgp.backend.population.Node; import jcgp.gui.ChromosomePane; -import jcgp.population.Connection; -import jcgp.population.Input; -import jcgp.population.Node; +import jcgp.gui.GUI; public class GUINode extends GUIGene { @@ -429,7 +429,7 @@ public class GUINode extends GUIGene { } @Override - public void setLocked(boolean value) { + void setLocked(boolean value) { locked += value ? 1 : -1; stateProperty.set(locked > 0 ? GUIGeneState.HOVER : GUIGeneState.ACTIVE_HOVER); diff --git a/src/jcgp/gui/population/GUIOutput.java b/src/jcgp/gui/population/GUIOutput.java index 16d95f0..9c5dfa5 100644 --- a/src/jcgp/gui/population/GUIOutput.java +++ b/src/jcgp/gui/population/GUIOutput.java @@ -13,12 +13,12 @@ import javafx.scene.shape.Line; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.scene.text.TextAlignment; -import jcgp.GUI; +import jcgp.backend.population.Connection; +import jcgp.backend.population.Input; +import jcgp.backend.population.Node; +import jcgp.backend.population.Output; import jcgp.gui.ChromosomePane; -import jcgp.population.Connection; -import jcgp.population.Input; -import jcgp.population.Node; -import jcgp.population.Output; +import jcgp.gui.GUI; public class GUIOutput extends GUIGene { @@ -281,7 +281,7 @@ public class GUIOutput extends GUIGene { } @Override - public void setLocked(boolean value) { + void setLocked(boolean value) { locked += value ? 1 : -1; setConnections(value ? GUIGeneState.HOVER : GUIGeneState.ACTIVE_HOVER); @@ -314,5 +314,20 @@ public class GUIOutput extends GUIGene { sourceLine.setEndX(gene.getLayoutX() + NODE_RADIUS); sourceLine.setEndY(gene.getLayoutY()); } + + public void unlock() { + if (isLocked()) { + setLocked(false); + stateProperty.set(GUIGeneState.NEUTRAL); + setConnections(GUIGeneState.NEUTRAL); + } + } + + public void lock() { + if (!isLocked()) { + stateProperty.set(GUIGeneState.HOVER); + setLocked(true); + } + } } diff --git a/src/jcgp/gui/settings/SettingsPane.java b/src/jcgp/gui/settings/SettingsPane.java index 9edcbdb..61011aa 100644 --- a/src/jcgp/gui/settings/SettingsPane.java +++ b/src/jcgp/gui/settings/SettingsPane.java @@ -5,7 +5,6 @@ import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; -import javafx.beans.property.SimpleIntegerProperty; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; @@ -22,14 +21,15 @@ import javafx.scene.layout.VBox; import javafx.scene.text.Font; import javafx.scene.text.FontSmoothingType; import javafx.scene.text.Text; -import jcgp.GUI; import jcgp.JCGP; -import jcgp.function.FunctionSet; +import jcgp.backend.function.FunctionSet; +import jcgp.backend.modules.ea.EvolutionaryAlgorithm; +import jcgp.backend.modules.fitness.FitnessFunction; +import jcgp.backend.modules.mutator.Mutator; +import jcgp.backend.parameters.IntegerParameter; +import jcgp.backend.parameters.Parameter; +import jcgp.gui.GUI; import jcgp.gui.settings.parameters.*; -import jcgp.modules.ea.EvolutionaryAlgorithm; -import jcgp.modules.fitness.FitnessFunction; -import jcgp.modules.mutator.Mutator; -import jcgp.parameters.*; public class SettingsPane extends AnchorPane { @@ -84,31 +84,28 @@ public class SettingsPane extends AnchorPane { bpPane.getChildren().add(header); - final GUIIntegerParameter generation = new GUIIntegerParameter((IntegerParameter) cgp.getResources().getParameter("currentGen")); - final GUIIntegerParameter run = new GUIIntegerParameter((IntegerParameter) cgp.getResources().getParameter("currentRun")); + GUIParameter rows = GUIParameter.create((IntegerParameter) cgp.getResources().getParameter("rows")); + parameters.add(rows); + parameters.add(GUIParameter.create((IntegerParameter) cgp.getResources().getParameter("columns"))); + parameters.add(GUIParameter.create((IntegerParameter) cgp.getResources().getParameter("inputs"))); + parameters.add(GUIParameter.create((IntegerParameter) cgp.getResources().getParameter("outputs"))); + parameters.add(GUIParameter.create((IntegerParameter) cgp.getResources().getParameter("levelsBack"))); - parameters.add(new GUIIntegerParameter((IntegerParameter) cgp.getResources().getParameter("rows"))); - parameters.add(new GUIIntegerParameter((IntegerParameter) cgp.getResources().getParameter("columns"))); - parameters.add(new GUIIntegerParameter((IntegerParameter) cgp.getResources().getParameter("inputs"))); - parameters.add(new GUIIntegerParameter((IntegerParameter) cgp.getResources().getParameter("outputs"))); - parameters.add(new GUIIntegerParameter((IntegerParameter) cgp.getResources().getParameter("levelsBack"))); + parameters.add(GUIParameter.create((IntegerParameter) cgp.getResources().getParameter("popSize"))); + parameters.add(GUIParameter.create((IntegerParameter) cgp.getResources().getParameter("generations"))); + parameters.add(GUIParameter.create((IntegerParameter) cgp.getResources().getParameter("runs"))); - parameters.add(new GUIIntegerParameter((IntegerParameter) cgp.getResources().getParameter("popSize"))); - parameters.add(new GUIIntegerParameter((IntegerParameter) cgp.getResources().getParameter("generations"))); - parameters.add(new GUIIntegerParameter((IntegerParameter) cgp.getResources().getParameter("runs"))); + parameters.add(GUIParameter.create((IntegerParameter) cgp.getResources().getParameter("currentGen"))); + parameters.add(GUIParameter.create((IntegerParameter) cgp.getResources().getParameter("currentRun"))); - parameters.add(generation); - parameters.add(run); - - parameters.add(new GUIIntegerParameter((IntegerParameter) cgp.getResources().getParameter("seed"))); - parameters.add(new GUIIntegerParameter((IntegerParameter) cgp.getResources().getParameter("report"))); - parameters.add(new GUIBooleanParameter((BooleanParameter) cgp.getResources().getParameter("verbose"))); + parameters.add(GUIParameter.create((IntegerParameter) cgp.getResources().getParameter("seed"))); + parameters.add(GUIParameter.create((IntegerParameter) cgp.getResources().getParameter("report"))); bpPane.getChildren().addAll(parameters); mainContainer.getChildren().add(bpPane); - generation.getTextField().textProperty().bind(((SimpleIntegerProperty) cgp.getResources().getParameter("currentGen").valueProperty()).asString()); + } private void initialiseEAParameters(final JCGP cgp) { @@ -245,13 +242,16 @@ public class SettingsPane extends AnchorPane { play.setOnAction(new EventHandler() { @Override - public void handle(ActionEvent event) { - gui.playPause(); - if (gui.isEvolving()) { + public void handle(ActionEvent event) { + if (play.getText() == "Run") { + if (applyChanges()) { + gui.resetCGP(); + } play.setText("Pause"); } else { play.setText("Run"); } + gui.playPause(); } }); @@ -260,6 +260,9 @@ public class SettingsPane extends AnchorPane { step.setOnAction(new EventHandler() { @Override public void handle(ActionEvent event) { + if (applyChanges()) { + gui.resetCGP(); + } gui.step(); } }); @@ -274,8 +277,7 @@ public class SettingsPane extends AnchorPane { controls.getChildren().add(flowButtons); - mainContainer.getChildren().add(controls); - + mainContainer.getChildren().add(controls); } /** @@ -287,19 +289,10 @@ public class SettingsPane extends AnchorPane { vb.getChildren().clear(); while (it.hasNext()) { Parameter parameter = ((Map.Entry) it.next()).getValue(); - if (parameter instanceof IntegerParameter) { - GUIIntegerParameter gip = new GUIIntegerParameter((IntegerParameter) parameter); - parameters.add(gip); - vb.getChildren().add(gip); - } else if (parameter instanceof DoubleParameter) { - GUIDoubleParameter gdp = new GUIDoubleParameter((DoubleParameter) parameter); - parameters.add(gdp); - vb.getChildren().add(gdp); - } else if (parameter instanceof BooleanParameter) { - GUIBooleanParameter gbp = new GUIBooleanParameter((BooleanParameter) parameter); - parameters.add(gbp); - vb.getChildren().add(gbp); - } + GUIParameter gp = GUIParameter.create(parameter); + + parameters.add(gp); + vb.getChildren().add(gp); } } @@ -371,30 +364,29 @@ public class SettingsPane extends AnchorPane { return event.getX() < (GUI.RESIZE_MARGIN); } - public void refreshValues() { - for (GUIParameter parameter : parameters) { - parameter.refreshValue(); - } - //parent.updateNodeGrids(); - } - -// public void bindParameters() { -// for (GUIParameter parameter : parameters) { -// parameter.doBindings(); -// } -// } -// -// public void unbindParameters() { -// for (GUIParameter parameter : parameters) { -// parameter.undoBindings(); -// } -// } - - public void toggleSettings(boolean value) { + public void disableSettings(boolean value) { bpPane.setDisable(value); eaPane.setDisable(value); mutatorPane.setDisable(value); ffPane.setDisable(value); nfPane.setDisable(value); } + + /** + * Writes the GUI parameter value back to the resources parameter, + * if any changes were made. + * + * @return true if the experiment needs to be reset, false otherwise. + */ + private boolean applyChanges() { + boolean reset = false; + + for (GUIParameter parameter : parameters) { + reset |= parameter.applyChange(); + } + + return reset; + } + + } diff --git a/src/jcgp/gui/settings/parameters/GUIBooleanParameter.java b/src/jcgp/gui/settings/parameters/GUIBooleanParameter.java index a9f6753..8acd6dd 100644 --- a/src/jcgp/gui/settings/parameters/GUIBooleanParameter.java +++ b/src/jcgp/gui/settings/parameters/GUIBooleanParameter.java @@ -1,11 +1,11 @@ package jcgp.gui.settings.parameters; import javafx.scene.control.CheckBox; -import jcgp.parameters.BooleanParameter; +import jcgp.backend.parameters.BooleanParameter; public class GUIBooleanParameter extends GUIParameter { - public GUIBooleanParameter(BooleanParameter parameter) { + GUIBooleanParameter(BooleanParameter parameter) { super(); this.parameter = parameter; @@ -13,22 +13,16 @@ public class GUIBooleanParameter extends GUIParameter { value = new CheckBox(parameter.getName()); ((CheckBox) value).setSelected(parameter.get()); - value.setDisable(!parameter.isEditable()); + value.setDisable(parameter.isMonitor()); - getChildren().add(value); + if (parameter.isMonitor()) { + makeLightBinding(); + System.out.println("light binding made for " + name); + } + getChildren().add(value); } -// @Override -// public void doBindings() { -// ((CheckBox) value).selectedProperty().bind(((BooleanParameter) parameter).valueProperty()); -// } -// -// @Override -// public void undoBindings() { -// ((CheckBox) value).selectedProperty().unbind(); -// } - @Override public void refreshValue() { if (!((CheckBox) value).selectedProperty().isBound()) { @@ -36,5 +30,17 @@ public class GUIBooleanParameter extends GUIParameter { } } + + @Override + public boolean applyChange() { + if (((CheckBox) value).isSelected() != ((BooleanParameter) parameter).get() && (!parameter.isMonitor())) { + // apply value + ((BooleanParameter) parameter).set(((CheckBox) value).isSelected()); + if (parameter.isCritical()) { + return true; + } + } + return false; + } } diff --git a/src/jcgp/gui/settings/parameters/GUIDoubleParameter.java b/src/jcgp/gui/settings/parameters/GUIDoubleParameter.java index 25d5b9f..4b74c6e 100644 --- a/src/jcgp/gui/settings/parameters/GUIDoubleParameter.java +++ b/src/jcgp/gui/settings/parameters/GUIDoubleParameter.java @@ -4,12 +4,12 @@ import javafx.geometry.Pos; import javafx.scene.control.TextField; import javafx.scene.layout.Priority; import javafx.scene.text.Text; -import jcgp.GUI; -import jcgp.parameters.DoubleParameter; +import jcgp.backend.parameters.DoubleParameter; +import jcgp.gui.GUI; public class GUIDoubleParameter extends GUIParameter { - public GUIDoubleParameter(DoubleParameter parameter) { + GUIDoubleParameter(DoubleParameter parameter) { super(); this.parameter = parameter; @@ -23,26 +23,29 @@ public class GUIDoubleParameter extends GUIParameter { name.setWrappingWidth(GUI.WRAP_WIDTH); - ((TextField) value).setEditable(parameter.isEditable()); + ((TextField) value).setEditable(!parameter.isMonitor()); + + if (parameter.isMonitor()) { + makeLightBinding(); + } getChildren().addAll(name, value); } -// @Override -// public void doBindings() { -// ((TextField) value).textProperty().bind(((DoubleParameter) parameter).valueProperty().asString()); -// } -// -// @Override -// public void undoBindings() { -// ((TextField) value).textProperty().unbind(); -// } - @Override public void refreshValue() { - if (!((TextField) value).textProperty().isBound()) { - ((TextField) value).setText(String.valueOf(((DoubleParameter) parameter).get())); - } + ((TextField) value).setText(String.valueOf(((DoubleParameter) parameter).get())); } - + + @Override + public boolean applyChange() { + if (Double.valueOf(((TextField) value).getText()) != ((DoubleParameter) parameter).get() && (!parameter.isMonitor())) { + // apply value + ((DoubleParameter) parameter).set(Double.valueOf(((TextField) value).getText())); + if (parameter.isCritical()) { + return true; + } + } + return false; + } } diff --git a/src/jcgp/gui/settings/parameters/GUIIntegerParameter.java b/src/jcgp/gui/settings/parameters/GUIIntegerParameter.java index 6bcfd55..70b78a6 100644 --- a/src/jcgp/gui/settings/parameters/GUIIntegerParameter.java +++ b/src/jcgp/gui/settings/parameters/GUIIntegerParameter.java @@ -4,12 +4,12 @@ import javafx.geometry.Pos; import javafx.scene.control.TextField; import javafx.scene.layout.Priority; import javafx.scene.text.Text; -import jcgp.GUI; -import jcgp.parameters.IntegerParameter; +import jcgp.backend.parameters.IntegerParameter; +import jcgp.gui.GUI; public class GUIIntegerParameter extends GUIParameter { - public GUIIntegerParameter(IntegerParameter parameter) { + GUIIntegerParameter(IntegerParameter parameter) { super(); this.parameter = parameter; @@ -23,27 +23,27 @@ public class GUIIntegerParameter extends GUIParameter { name.setWrappingWidth(GUI.WRAP_WIDTH); - ((TextField) value).setEditable(parameter.isEditable()); + ((TextField) value).setEditable(!parameter.isMonitor()); + + if (parameter.isMonitor()) { + makeLightBinding(); + } getChildren().addAll(name, value); } -// @Override -// public void doBindings() { -// ((TextField) value).textProperty().bind(((IntegerParameter) parameter).valueProperty().asString()); -// } -// -// @Override -// public void undoBindings() { -// ((TextField) value).textProperty().unbind(); -// } - - public TextField getTextField() { - return (TextField) value; - } - @Override public void refreshValue() { ((TextField) value).setText(String.valueOf(((IntegerParameter) parameter).get())); } + + @Override + public boolean applyChange() { + if (Integer.valueOf(((TextField) value).getText()) != ((IntegerParameter) parameter).get() && (!parameter.isMonitor())) { + // apply value + ((IntegerParameter) parameter).set(Integer.valueOf(((TextField) value).getText())); + return parameter.isCritical(); + } + return false; + } } diff --git a/src/jcgp/gui/settings/parameters/GUIParameter.java b/src/jcgp/gui/settings/parameters/GUIParameter.java index a2f2f9c..a783d71 100644 --- a/src/jcgp/gui/settings/parameters/GUIParameter.java +++ b/src/jcgp/gui/settings/parameters/GUIParameter.java @@ -1,10 +1,18 @@ package jcgp.gui.settings.parameters; +import java.util.concurrent.atomic.AtomicBoolean; + +import javafx.application.Platform; +import javafx.beans.value.ChangeListener; +import javafx.beans.value.ObservableValue; import javafx.geometry.Pos; import javafx.scene.control.Control; import javafx.scene.layout.HBox; import javafx.scene.text.Text; -import jcgp.parameters.Parameter; +import jcgp.backend.parameters.BooleanParameter; +import jcgp.backend.parameters.DoubleParameter; +import jcgp.backend.parameters.IntegerParameter; +import jcgp.backend.parameters.Parameter; public abstract class GUIParameter extends HBox { @@ -12,19 +20,51 @@ public abstract class GUIParameter extends HBox { protected Text name; protected Control value; - public GUIParameter() { + protected AtomicBoolean updateCheck = new AtomicBoolean(true); + + protected GUIParameter() { setAlignment(Pos.CENTER_LEFT); setSpacing(5); } - public Parameter getParameter() { - return parameter; + protected final void makeLightBinding() { + parameter.valueProperty().addListener(new ChangeListener() { + @Override + public void changed( + ObservableValue observable, + Object oldValue, Object newValue) { + if (updateCheck.getAndSet(false)) { + Platform.runLater(new Runnable() { + @Override + public void run() { + updateCheck.set(true); + refreshValue(); + } + }); + } + } + }); } -// public abstract void doBindings(); -// -// public abstract void undoBindings(); - public abstract void refreshValue(); + public static GUIParameter create(Parameter parameter) { + if (parameter instanceof IntegerParameter) { + return new GUIIntegerParameter((IntegerParameter) parameter); + } else if (parameter instanceof DoubleParameter) { + return new GUIDoubleParameter((DoubleParameter) parameter); + } else if (parameter instanceof BooleanParameter) { + return new GUIBooleanParameter((BooleanParameter) parameter); + } else { + throw new ClassCastException("No GUIParameter subclass exists for argument of type " + parameter.getClass()); + } + } + + /** + * Writes the GUI parameter value back to the resources parameter, + * if any changes were made. + * + * @return true if the experiment needs to be reset, false otherwise. + */ + public abstract boolean applyChange(); } diff --git a/src/jcgp/modules/Module.java b/src/jcgp/modules/Module.java deleted file mode 100644 index 9e0b267..0000000 --- a/src/jcgp/modules/Module.java +++ /dev/null @@ -1,11 +0,0 @@ -package jcgp.modules; - -import java.util.HashMap; - -import jcgp.JCGP.Resources; -import jcgp.parameters.Parameter; - -public interface Module { - public HashMap getLocalParameters(); - public ModuleStatus getStatus(Resources resources); -} diff --git a/src/jcgp/modules/ModuleStatus.java b/src/jcgp/modules/ModuleStatus.java deleted file mode 100644 index 02e2c01..0000000 --- a/src/jcgp/modules/ModuleStatus.java +++ /dev/null @@ -1,16 +0,0 @@ -package jcgp.modules; - -public enum ModuleStatus { - ERROR, WARNING, READY; - - private String details; - - public void setDetails(String details) { - this.details = details; - } - - public String getDetails() { - return details; - } - -} diff --git a/src/jcgp/modules/ea/EvolutionaryAlgorithm.java b/src/jcgp/modules/ea/EvolutionaryAlgorithm.java deleted file mode 100644 index 3bc7fcf..0000000 --- a/src/jcgp/modules/ea/EvolutionaryAlgorithm.java +++ /dev/null @@ -1,15 +0,0 @@ -package jcgp.modules.ea; - -import jcgp.JCGP.Resources; -import jcgp.modules.Module; -import jcgp.modules.mutator.Mutator; -import jcgp.population.Chromosome; -import jcgp.population.Population; - -public interface EvolutionaryAlgorithm extends Module { - - public abstract void evolve(Population population, Mutator mutator, Resources parameters); - - public abstract Chromosome getFittestChromosome(); - -} diff --git a/src/jcgp/modules/ea/MuPlusLambda.java b/src/jcgp/modules/ea/MuPlusLambda.java deleted file mode 100644 index 94900ca..0000000 --- a/src/jcgp/modules/ea/MuPlusLambda.java +++ /dev/null @@ -1,80 +0,0 @@ -package jcgp.modules.ea; - -import java.util.HashMap; - -import jcgp.JCGP.Resources; -import jcgp.modules.ModuleStatus; -import jcgp.modules.mutator.Mutator; -import jcgp.parameters.IntegerParameter; -import jcgp.parameters.Parameter; -import jcgp.population.Chromosome; -import jcgp.population.Population; - -/** - * (μ + λ) EA. - * - * - * @author Eduardo Pedroni - * - */ -public class MuPlusLambda implements EvolutionaryAlgorithm { - - private Chromosome fittestChromosome; - - private IntegerParameter parents, offspring; - - private HashMap localParameters; - - public MuPlusLambda() { - parents = new IntegerParameter(1, "Parents"); - offspring = new IntegerParameter(4, "Offspring"); - - localParameters = new HashMap(); - - localParameters.put("mu", parents); - localParameters.put("lambda", offspring); - } - - @Override - public void evolve(Population population, Mutator mutator, Resources parameters) { - // select fittest chromosome - int fittest = 0; - - for (int i = 1; i < parameters.getInt("popSize"); i++) { - if (population.getChromosome(i).getFitness() >= population.getChromosome(fittest).getFitness()) { - fittest = i; - } - } - fittestChromosome = population.getChromosome(fittest); - population.setBestIndividual(fittest); - // create copies of fittest chromosome, mutate them - Chromosome fc = population.getChromosome(fittest); - for (int i = 0; i < parameters.getInt("popSize"); i++) { - if (i != fittest) { - population.getChromosome(i).copyConnections(fc); - mutator.mutate(population.getChromosome(i), parameters); - } - } - } - - @Override - public Chromosome getFittestChromosome() { - return fittestChromosome; - } - - @Override - public HashMap getLocalParameters() { - return localParameters; - } - - @Override - public String toString() { - return "(μ + λ)"; - } - - @Override - public ModuleStatus getStatus(Resources resources) { - return ModuleStatus.READY; - } - -} diff --git a/src/jcgp/modules/ea/TournamentSelection.java b/src/jcgp/modules/ea/TournamentSelection.java deleted file mode 100644 index c2915a5..0000000 --- a/src/jcgp/modules/ea/TournamentSelection.java +++ /dev/null @@ -1,54 +0,0 @@ -package jcgp.modules.ea; - -import java.util.HashMap; - -import jcgp.JCGP.Resources; -import jcgp.modules.ModuleStatus; -import jcgp.modules.mutator.Mutator; -import jcgp.parameters.IntegerParameter; -import jcgp.parameters.Parameter; -import jcgp.population.Chromosome; -import jcgp.population.Population; - -public class TournamentSelection implements EvolutionaryAlgorithm { - - private Chromosome fittestChromosome; - - private IntegerParameter tournament; - private HashMap localParameters; - - public TournamentSelection() { - tournament = new IntegerParameter(1, "Tournament size"); - - localParameters = new HashMap(); - localParameters.put("tournament", tournament); - } - - @Override - public HashMap getLocalParameters() { - return localParameters; - } - - @Override - public void evolve(Population population, Mutator mutator, - Resources parameters) { - - // TODO implement this - - } - - @Override - public Chromosome getFittestChromosome() { - return fittestChromosome; - } - - @Override - public String toString() { - return "Tournament"; - } - - @Override - public ModuleStatus getStatus(Resources resources) { - return null; - } -} diff --git a/src/jcgp/modules/fitness/FitnessFunction.java b/src/jcgp/modules/fitness/FitnessFunction.java deleted file mode 100644 index f0800b0..0000000 --- a/src/jcgp/modules/fitness/FitnessFunction.java +++ /dev/null @@ -1,11 +0,0 @@ -package jcgp.modules.fitness; - -import jcgp.JCGP.Resources; -import jcgp.modules.Module; -import jcgp.population.Population; - -public interface FitnessFunction extends Module { - - public void evaluate(Population population, Resources resources); - -} diff --git a/src/jcgp/modules/fitness/TestCase.java b/src/jcgp/modules/fitness/TestCase.java deleted file mode 100644 index 081a257..0000000 --- a/src/jcgp/modules/fitness/TestCase.java +++ /dev/null @@ -1,29 +0,0 @@ -package jcgp.modules.fitness; - -public class TestCase { - - private Object[] inputs; - private Object[] outputs; - - public TestCase(Object[] inputs, Object[] outputs) { - this.inputs = inputs; - this.outputs = outputs; - } - - public Object getInput(int index) { - return inputs[index]; - } - - public Object getOutput(int index) { - return outputs[index]; - } - - public Object[] getInputs() { - return inputs; - } - - public Object[] getOutputs() { - return outputs; - } - -} diff --git a/src/jcgp/modules/fitness/TestCaseEvaluator.java b/src/jcgp/modules/fitness/TestCaseEvaluator.java deleted file mode 100644 index d8c1255..0000000 --- a/src/jcgp/modules/fitness/TestCaseEvaluator.java +++ /dev/null @@ -1,45 +0,0 @@ -package jcgp.modules.fitness; - -import java.util.HashMap; - -import jcgp.JCGP.Resources; -import jcgp.modules.ModuleStatus; -import jcgp.parameters.Parameter; -import jcgp.population.Population; - -public class TestCaseEvaluator implements FitnessFunction { - - @Override - public void evaluate(Population population, Resources resources) { - // for every chromosome in the population - for (int i = 0; i < resources.getInt("popSize"); i++) { - int fitness = 0; - // for every test case - for (int t = 0; t < resources.getTestCaseCount(); t++) { - population.getChromosome(i).setInputs(resources.getTestCase(t).getInputs()); - // check every output - for (int o = 0; o < resources.getInt("outputs"); o++) { - if (population.getChromosome(i).getOutput(o).calculate() == resources.getTestCase(t).getOutput(o)) { - fitness++; - } - } - } - population.getChromosome(i).setFitness(fitness); - } - } - - @Override - public HashMap getLocalParameters() { - return null; - } - - @Override - public String toString() { - return "Test case"; - } - - @Override - public ModuleStatus getStatus(Resources resources) { - return null; - } -} diff --git a/src/jcgp/modules/mutator/Mutator.java b/src/jcgp/modules/mutator/Mutator.java deleted file mode 100644 index 8dfa0f9..0000000 --- a/src/jcgp/modules/mutator/Mutator.java +++ /dev/null @@ -1,11 +0,0 @@ -package jcgp.modules.mutator; - -import jcgp.JCGP.Resources; -import jcgp.modules.Module; -import jcgp.population.Chromosome; - -public interface Mutator extends Module { - - void mutate(Chromosome chromosome, Resources parameters); - -} diff --git a/src/jcgp/modules/mutator/PointMutator.java b/src/jcgp/modules/mutator/PointMutator.java deleted file mode 100644 index 2298368..0000000 --- a/src/jcgp/modules/mutator/PointMutator.java +++ /dev/null @@ -1,71 +0,0 @@ -package jcgp.modules.mutator; - -import java.util.HashMap; - -import jcgp.modules.ModuleStatus; -import jcgp.parameters.DoubleParameter; -import jcgp.parameters.Parameter; -import jcgp.JCGP.Resources; -import jcgp.population.Chromosome; -import jcgp.population.MutableElement; -import jcgp.population.Node; -import jcgp.population.Output; - -public class PointMutator implements Mutator { - - private DoubleParameter mutationRate; - private HashMap localParameters; - - private ModuleStatus status = ModuleStatus.READY; - - public PointMutator() { - mutationRate = new DoubleParameter(0.5, "Percent mutation"); - - localParameters = new HashMap(); - localParameters.put("mutRate", mutationRate); - } - - @Override - public void mutate(Chromosome chromosome, Resources resources) { - int mutations = (int) Math.ceil(((mutationRate.get()) * ((((resources.getDouble("nodes")) + (resources.getDouble("outputs")))) / (double) 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) { - ((Node) m).setFunction(resources.getRandomFunction()); - } else { - m.setConnection(resources.getRandomInt(resources.getInt("arity")), chromosome.getRandomConnection(((Node) m).getColumn())); - } - } - } - } - - @Override - public HashMap getLocalParameters() { - return localParameters; - } - - @Override - public String toString() { - return "Point mutation"; - } - - @Override - public ModuleStatus getStatus(Resources resources) { - if (mutationRate.get() <= 0 || mutationRate.get() > 100) { - status = ModuleStatus.ERROR; - status.setDetails("Mutation rate must be > 0 and <= 100"); - } else if ((int) ((mutationRate.get() / 100) * resources.getDouble("nodes")) > 0) { - status = ModuleStatus.WARNING; - status.setDetails("With mutation rate " + mutationRate.get() + ", no mutations will occur."); - } else { - status = ModuleStatus.READY; - status.setDetails(""); - } - return status; - } -} diff --git a/src/jcgp/parameters/BooleanParameter.java b/src/jcgp/parameters/BooleanParameter.java deleted file mode 100644 index 63e9c73..0000000 --- a/src/jcgp/parameters/BooleanParameter.java +++ /dev/null @@ -1,32 +0,0 @@ -package jcgp.parameters; - -import javafx.beans.property.SimpleBooleanProperty; - -public class BooleanParameter extends Parameter { - - private SimpleBooleanProperty value; - - public BooleanParameter(boolean value, String name, boolean editable, boolean hidden) { - super(name, editable, hidden); - this.value = new SimpleBooleanProperty(value); - } - - public BooleanParameter(boolean value, String name) { - super(name, true, false); - this.value = new SimpleBooleanProperty(value); - } - - public boolean get() { - return value.get(); - } - - public void set(boolean newValue) { - if (!value.isBound()) { - value.set(newValue); - } - } - - public SimpleBooleanProperty valueProperty() { - return value; - } -} diff --git a/src/jcgp/parameters/DoubleParameter.java b/src/jcgp/parameters/DoubleParameter.java deleted file mode 100644 index d555452..0000000 --- a/src/jcgp/parameters/DoubleParameter.java +++ /dev/null @@ -1,33 +0,0 @@ -package jcgp.parameters; - -import javafx.beans.property.SimpleDoubleProperty; - -public class DoubleParameter extends Parameter { - - protected SimpleDoubleProperty value; - - public DoubleParameter(double value, String name, boolean editable, boolean hidden) { - super(name, editable, hidden); - this.value = new SimpleDoubleProperty(value); - } - - public DoubleParameter(double value, String name) { - super(name, true, false); - this.value = new SimpleDoubleProperty(value); - } - - public double get() { - return value.get(); - } - - public void set(double newValue) { - if (!value.isBound()) { - value.set(newValue); - } - } - - public SimpleDoubleProperty valueProperty() { - return value; - } - -} diff --git a/src/jcgp/parameters/IntegerParameter.java b/src/jcgp/parameters/IntegerParameter.java deleted file mode 100644 index c743e97..0000000 --- a/src/jcgp/parameters/IntegerParameter.java +++ /dev/null @@ -1,33 +0,0 @@ -package jcgp.parameters; - -import javafx.beans.property.SimpleIntegerProperty; - -public class IntegerParameter extends Parameter { - - protected SimpleIntegerProperty value; - - public IntegerParameter(int value, String name, boolean editable, boolean hidden) { - super(name, editable, hidden); - this.value = new SimpleIntegerProperty(value); - } - - public IntegerParameter(int value, String name) { - super(name, true, false); - this.value = new SimpleIntegerProperty(value); - } - - public int get() { - return value.get(); - } - - public void set(int newValue) { - if (!value.isBound()) { - value.set(newValue); - } - } - - public SimpleIntegerProperty valueProperty() { - return value; - } - -} diff --git a/src/jcgp/parameters/Parameter.java b/src/jcgp/parameters/Parameter.java deleted file mode 100644 index a5ecf9e..0000000 --- a/src/jcgp/parameters/Parameter.java +++ /dev/null @@ -1,30 +0,0 @@ -package jcgp.parameters; - -import javafx.beans.property.Property; - -public abstract class Parameter { - - protected boolean hidden = false, editable = true; - - protected String name; - - public Parameter(String name, boolean editable, boolean hidden) { - this.name = name; - this.hidden = hidden; - this.editable = editable; - } - - public boolean isHidden() { - return hidden; - } - - public boolean isEditable() { - return editable; - } - - public String getName() { - return name; - } - - public abstract Property valueProperty(); -} diff --git a/src/jcgp/population/Chromosome.java b/src/jcgp/population/Chromosome.java deleted file mode 100644 index 297d298..0000000 --- a/src/jcgp/population/Chromosome.java +++ /dev/null @@ -1,335 +0,0 @@ -package jcgp.population; - -import java.util.ArrayList; - -import jcgp.JCGP.Resources; -import jcgp.exceptions.ParameterMismatchException; - -public class Chromosome { - - private Resources resources; - - private Input[] inputs; - private Node[][] nodes; - private Output[] outputs; - - private ArrayList activeNodes; - - private int fitness = 0; - private boolean recomputeActiveNodes = true; - - /** - * Initialise a chromosome with the specified parameters. Random valid connections - * are created. - * - * - */ - public Chromosome(Resources resources) { - // store a reference to the parameters - this.resources = resources; - - // allocate memory for all elements of the chromosome - instantiateElements(); - // set random connections so that the chromosome can be evaluated - initialiseConnections(); - } - - /** - * Copy constructor. - * - * Initialise a new chromosome with the exact same connections as a given instance of Chromosome. - * - * @param clone the chromosome to be copied - */ - public Chromosome(Chromosome clone) { - // store a reference to the parameters - this.resources = clone.getParameters(); - - // allocate memory for all elements of the chromosome - instantiateElements(); - // initialise all connections based on argument - copyConnections(clone); - } - - /** - * - */ - private void instantiateElements() { - inputs = new Input[(resources.getInt("inputs"))]; - for (int i = 0; i < (resources.getInt("inputs")); i++) { - inputs[i] = new Input(i); - } - - int arity = resources.getInt("arity"); - - // rows first - nodes = new Node[(resources.getInt("rows"))][(resources.getInt("columns"))]; - for (int r = 0; r < (resources.getInt("rows")); r++) { - for (int c = 0; c < (resources.getInt("columns")); c++) { - nodes[r][c] = new Node(this, r, c, arity); - } - } - outputs = new Output[(resources.getInt("outputs"))]; - for (int o = 0; o < (resources.getInt("outputs")); o++) { - outputs[o] = new Output(this, o); - } - } - - /** - * - */ - private void initialiseConnections() { - - int arity = resources.getInt("arity"); - - // initialise nodes - [rows][columns] - for (int r = 0; r < nodes.length; r++) { - for (int c = 0; c < nodes[r].length; c++) { - Connection[] connections = new Connection[arity]; - for (int i = 0; i < connections.length; i++) { - connections[i] = getRandomConnection(c); - } - nodes[r][c].initialise(resources.getRandomFunction(), connections); - } - } - - for (Output output : outputs) { - output.setConnection(0, getRandomConnection()); - } - - } - - /** - * @param clone - */ - public void copyConnections(Chromosome clone) { - int arity = resources.getInt("arity"); - - // copy nodes - [rows][columns] - for (int r = 0; r < nodes.length; r++) { - for (int c = 0; c < nodes[r].length; c++) { - // make array of connections to initialise with - Connection[] connections = new Connection[arity]; - // populate with connections equivalent to clone - Connection copyConnection; - for (int i = 0; i < connections.length; i++) { - copyConnection = clone.getNode(r, c).getConnection(i); - if (copyConnection instanceof Input) { - connections[i] = inputs[((Input) copyConnection).getIndex()]; - } else if (copyConnection instanceof Node) { - connections[i] = nodes[((Node) copyConnection).getRow()][((Node) copyConnection).getColumn()]; - } else { - System.out.println("Warning: Connection of subtype " + copyConnection.getClass().toString() + " is not explicitly handled by copy constructor."); - } - } - // initialise with copied arguments - nodes[r][c].initialise(clone.getNode(r, c).getFunction(), connections); - } - } - - // do the same to outputs - Connection copyOutput; - for (int o = 0; o < outputs.length; o++) { - copyOutput = clone.getOutput(o).getSource(); - if (copyOutput instanceof Input) { - outputs[o].setConnection(0, inputs[((Input) copyOutput).getIndex()]); - } else if (copyOutput instanceof Node) { - outputs[o].setConnection(0, nodes[((Node) copyOutput).getRow()][((Node) copyOutput).getColumn()]); - } else { - // something bad happened - System.out.println("Warning: Connection of subtype " + copyOutput.getClass().toString() + " is not explicitly handled by copy constructor."); - } - } - } - - public Node getNode(int row, int column) { - return nodes[row][column]; - } - - public Output getOutput(int index) { - return outputs[index]; - } - - public Input getInput(int index) { - return inputs[index]; - } - - public int getFitness() { - return fitness; - } - - public void setFitness(int newFitness) { - fitness = newFitness; - } - - /** - * - * @param values - * @throws ParameterMismatchException - */ - public void setInputs(Object ... values) throws ParameterMismatchException { - // if the values provided don't match the specified number of inputs, the user should be warned - if (values.length == inputs.length) { - // set inputs for evaluation - for (int i = 0; i < values.length; i++) { - inputs[i].setValue(values[i]); - } - } else { - throw new ParameterMismatchException(); - } - } - - /** - * This method is useful for mutating chromosomes. - * - * @return a random element that can be mutated - Node or Output - */ - public MutableElement getRandomMutableElement() { - // choose output or node - int index = resources.getRandomInt(outputs.length + (resources.getInt("rows")) * (resources.getInt("columns"))); - - if (index < outputs.length) { - // outputs - return outputs[index]; - } else { - // node - index -= outputs.length; - return nodes[index / (resources.getInt("columns"))][index % (resources.getInt("columns"))]; - } - } - - /** - * Returns a random allowed connection respecting levels back.
- * This method may always pick inputs, as they can be picked - * regardless of the column. - * - * @param column the column to use as reference - * @return a random connection - */ - public Connection getRandomConnection(int column) { - // work out the allowed range obeying levels back - int allowedColumns = ((column >= (resources.getInt("levelsBack"))) ? (resources.getInt("levelsBack")) : column); - int offset = ((column - allowedColumns) * nodes.length) - inputs.length; - - // choose input or allowed node - int index = resources.getRandomInt(inputs.length + (nodes.length * allowedColumns)); - if (index < inputs.length) { - // input - return inputs[index]; - } else { - // node - // offset it to address the right columns - index += offset; - return nodes[index % nodes.length][index / nodes.length]; - } - } - - /** - * This method will pick a completely random connection, independently - * of levels back, including inputs. - * - * Useful for setting outputs. - * - * - * @return a random connection - */ - public Connection getRandomConnection() { - // choose output or node - int index = resources.getRandomInt(inputs.length + (resources.getInt("columns")) * (resources.getInt("rows"))); - if (index < inputs.length) { - // outputs - return inputs[index]; - } else { - // node - index -= inputs.length; - return nodes[index / (resources.getInt("columns"))][index % (resources.getInt("columns"))]; - } - } - - /** - * This causes the list of active nodes to be recomputed lazily (once it is actually requested). - */ - public void recomputeActiveNodes() { - recomputeActiveNodes = true; - } - - /** - * This method computes a list of active connections (if necessary) and returns it. - * - * @return - */ - public ArrayList getActiveNodes() { - computeActiveNodes(); - return activeNodes; - } - - private void computeActiveNodes() { - // lazy recomputation has been triggered, do it - if (recomputeActiveNodes) { - recomputeActiveNodes = false; - activeNodes = new ArrayList(); - - for (Output output : outputs) { - output.getActiveNodes(activeNodes); - } - } - - } - - public boolean compareTo(Chromosome chromosome) { - for (int r = 0; r < (resources.getInt("rows")); r++) { - for (int c = 0; c < (resources.getInt("columns")); c++) { - if (!(nodes[r][c].copyOf(chromosome.getNode(r, c)))) { - return false; - } - } - } - - for (int o = 0; o < (resources.getInt("outputs")); o++) { - if (!(outputs[o].copyOf(chromosome.getOutput(o)))) { - return false; - } - } - - return true; - } - - public boolean compareActiveTo(Chromosome chromosome) { - // update list if it is out of date - computeActiveNodes(); - - if (activeNodes.size() == chromosome.getActiveNodes().size()) { - for (int i = 0; i < activeNodes.size(); i++) { - if (!(activeNodes.get(i).copyOf(chromosome.getActiveNodes().get(i)))){ - return false; - } - } - return true; - } - return false; - } - - public void printNodes() { - int arity = resources.getInt("arity"); - - for (int r = 0; r < (resources.getInt("rows")); r++) { - System.out.print("r: " + r + "\t"); - for (int c = 0; c < (resources.getInt("columns")); c++) { - System.out.print("N: (" + r + ", " + c + ") "); - for (int i = 0; i < arity; i++) { - System.out.print("C" + i + ": (" + nodes[r][c].getConnection(i).getDescription() + ") "); - } - System.out.print("F: " + nodes[r][c].getFunction().getName() + "\t"); - } - System.out.print("\n"); - } - - for (int o = 0; o < (resources.getInt("outputs")); o++) { - System.out.print("o: " + o + " (" + outputs[o].getSource().getDescription() + ")\t"); - } - } - - public Resources getParameters() { - return resources; - } -} diff --git a/src/jcgp/population/Connection.java b/src/jcgp/population/Connection.java deleted file mode 100644 index 63a171e..0000000 --- a/src/jcgp/population/Connection.java +++ /dev/null @@ -1,9 +0,0 @@ -package jcgp.population; - -public interface Connection { - - public Object getValue(); - - public String getDescription(); - -} diff --git a/src/jcgp/population/Gene.java b/src/jcgp/population/Gene.java deleted file mode 100644 index 8865a01..0000000 --- a/src/jcgp/population/Gene.java +++ /dev/null @@ -1,5 +0,0 @@ -package jcgp.population; - -public abstract class Gene { - -} diff --git a/src/jcgp/population/Input.java b/src/jcgp/population/Input.java deleted file mode 100644 index cfcb3ce..0000000 --- a/src/jcgp/population/Input.java +++ /dev/null @@ -1,29 +0,0 @@ -package jcgp.population; - -public class Input extends Gene implements Connection { - - private Object value = 0; - private int index; - - public Input(int index) { - this.index = index; - } - - public void setValue(Object newValue) { - value = newValue; - } - - @Override - public Object getValue() { - return value; - } - - public int getIndex() { - return index; - } - - @Override - public String getDescription() { - return "i: " + index; - } -} diff --git a/src/jcgp/population/MutableElement.java b/src/jcgp/population/MutableElement.java deleted file mode 100644 index 12f6bd1..0000000 --- a/src/jcgp/population/MutableElement.java +++ /dev/null @@ -1,34 +0,0 @@ -package jcgp.population; - -public interface MutableElement { - - /** - * This method sets the indexed connection to the specified new connection. - * Implementing classes may choose to ignore the given index (such as in the - * case of outputs, which only have one connection). - * - * @param index - * @param newConnection - */ - public void setConnection(int index, Connection newConnection); - - /** - * This method returns true if and only if:
- * - the elements being compared are not the same instance;
- * - the connections of the compared elements are not the same instance;
- * - the elements have the same function (in the case of Node);
- * - the grid position of the elements themselves are the same;
- * - the grid position of all equivalent connections are the same;

- * - * The relationship computed by this method is:
- * - symmetric: a.copyOf(b) == b.copyOf(a);
- * - not reflexive: a.copyOf(a) returns false;
- * - not transitive: if a.copyOf(b) is true and b.copyOf(c) is true, a.copyOf(c) is - * not necessarily true since it is possible that a == c.
- * - * @param m - * @return - */ - boolean copyOf(MutableElement m); - -} diff --git a/src/jcgp/population/Node.java b/src/jcgp/population/Node.java deleted file mode 100644 index 141a32a..0000000 --- a/src/jcgp/population/Node.java +++ /dev/null @@ -1,114 +0,0 @@ -package jcgp.population; - -import java.util.ArrayList; -import java.util.Arrays; - -import jcgp.exceptions.InsufficientConnectionsException; -import jcgp.function.Function; - - -public class Node extends Gene implements MutableElement, Connection { - - private Function function; - private Connection[] connections; - private int column, row; - private Chromosome chromosome; - - public Node(Chromosome chromosome, int row, int column, int arity) { - this.chromosome = chromosome; - this.column = column; - this.row = row; - } - - @Override - public Object getValue() { - //System.out.print("Calculating node: (" + row + ", " + column + ") > "); - return function.run(Arrays.copyOfRange(connections, 0, function.getArity())); - } - - public void setFunction(Function newFunction) { - function = newFunction; - chromosome.recomputeActiveNodes(); - } - - @Override - public void setConnection(int index, Connection newConnection) { - connections[index] = newConnection; - chromosome.recomputeActiveNodes(); - } - - public void initialise(Function newFunction, Connection ... newConnections) throws InsufficientConnectionsException { - function = newFunction; - if (newConnections.length == function.getArity()) { - connections = newConnections; - } else { - throw new InsufficientConnectionsException(); - } - } - - public int getColumn() { - return column; - } - - public int getRow() { - return row; - } - - public Function getFunction() { - return function; - } - - public Connection getConnection(int index) { - return connections[index]; - } - - public void getActive(ArrayList activeNodes) { - if (!activeNodes.contains(this)) { - activeNodes.add(this); - } - for (int i = 0; i < function.getArity(); i++) { - if (connections[i] instanceof Node) { - ((Node) connections[i]).getActive(activeNodes); - } - - } - } - - @Override - public boolean copyOf(MutableElement m) { - if (this != m) { - if (m instanceof Node) { - Node n = (Node) m; - if (function == n.getFunction()) { - if (column == n.getColumn() && row == n.getRow()) { - for (int i = 0; i < connections.length; i++) { - if (connections[i] != n.getConnection(i)) { - if (connections[i] instanceof Input && n.getConnection(i) instanceof Input) { - if (((Input) connections[i]).getIndex() != ((Input) n.getConnection(i)).getIndex()) { - return false; - } - } else if (connections[i] instanceof Node && n.getConnection(i) instanceof Node) { - if (((Node) connections[i]).getRow() != ((Node) n.getConnection(i)).getRow() && - ((Node) connections[i]).getColumn() != ((Node) n.getConnection(i)).getColumn()) { - return false; - } - } else { - return false; - } - } else { - return false; - } - } - return true; - } - } - } - } - return false; - } - - @Override - public String getDescription() { - return "n: " + row + ", " + column; - } -} diff --git a/src/jcgp/population/Output.java b/src/jcgp/population/Output.java deleted file mode 100644 index 5cc6dcf..0000000 --- a/src/jcgp/population/Output.java +++ /dev/null @@ -1,69 +0,0 @@ -package jcgp.population; - -import java.util.ArrayList; - -public class Output extends Gene implements MutableElement { - - private Connection source; - private Chromosome chromosome; - private int index; - - public Output(Chromosome chromosome, int index) { - this.chromosome = chromosome; - this.index = index; - //this.source = new SimpleObjectProperty(); - } - - public Object calculate() { - Object result = source.getValue(); - return result; - } - - @Override - public void setConnection(int index, Connection newConnection) { - source = newConnection; - chromosome.recomputeActiveNodes(); - } - - public int getIndex() { - return index; - } - - public Connection getSource() { - return source; - } - -// public SimpleObjectProperty sourceProperty() { -// return source; -// } - - public void getActiveNodes(ArrayList activeNodes) { - if (source instanceof Node) { - ((Node) source).getActive(activeNodes); - } - } - - @Override - public boolean copyOf(MutableElement m) { - if (this != m) { - if (m instanceof Output) { - Output o = (Output) m; - if (index == o.getIndex()) { - if (source != o.getSource()) { - if (source instanceof Input && o.getSource() instanceof Input) { - if (((Input) source).getIndex() == ((Input) o.getSource()).getIndex()) { - return true; - } - } else if (source instanceof Node && o.getSource() instanceof Node) { - if (((Node) source).getRow() == ((Node) o.getSource()).getRow() && - ((Node) source).getColumn() == ((Node) o.getSource()).getColumn()) { - return true; - } - } - } - } - } - } - return false; - } -} diff --git a/src/jcgp/population/Population.java b/src/jcgp/population/Population.java deleted file mode 100644 index f5e0517..0000000 --- a/src/jcgp/population/Population.java +++ /dev/null @@ -1,45 +0,0 @@ -package jcgp.population; - -import jcgp.JCGP.Resources; - - -public class Population { - - private Chromosome[] chromosomes; - private int fittest; - - public Population(Resources resources) { - chromosomes = new Chromosome[(resources.getInt("popSize"))]; - for (int c = 0; c < chromosomes.length; c++) { - chromosomes[c] = new Chromosome(resources); - } - } - - public Population(Chromosome parent, Resources resources) { - chromosomes = new Chromosome[(resources.getInt("popSize"))]; - // make a clone for safety - this.chromosomes[0] = new Chromosome(parent); - // generate the rest of the individuals - for (int c = 1; c < chromosomes.length; c++) { - chromosomes[c] = new Chromosome(chromosomes[0]); - } - } - - /** - * Returns all chromosomes, parents first, then offspring. - * - * @param index - * @return - */ - public Chromosome getChromosome(int index) { - return chromosomes[index]; - } - - public void setBestIndividual(int index) { - fittest = index; - } - - public Chromosome getBestIndividual() { - return chromosomes[fittest]; - } -} diff --git a/src/jcgp/tests/ChromosomeTests.java b/src/jcgp/tests/ChromosomeTests.java deleted file mode 100644 index eb4b5d1..0000000 --- a/src/jcgp/tests/ChromosomeTests.java +++ /dev/null @@ -1,334 +0,0 @@ -package jcgp.tests; - -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import jcgp.JCGP.Resources; -import jcgp.population.Chromosome; -import jcgp.population.Connection; -import jcgp.population.Input; -import jcgp.population.MutableElement; -import jcgp.population.Node; -import jcgp.population.Output; - -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -/** - * - * Tests which cover the behaviour specified for a chromosome. - * - * - The chromosome should be able to return a specified node, input or output. - * - It should be able to return a random MutableElement. - * - It should be able to return a random allowed connection given a column. - * - It should be able to return a random connection. - * - It should contain a freely modifiable fitness value. - * - For truth table evaluations, it should be able to have its inputs set. - * - For truth table evaluations, the output should return a value according to the inputs. - * - It should feature a copy method, which creates a deep copy of a specified Chromosome object. - * - It should be able to return a list of active nodes. - * - It should contain a method to evaluate whether a given chromosome is identical - * to it. - * - Same as above, but only looking at the active portion of a chromosome. - * - * - * WARNING: changing parameters may cause the tests to incorrectly fail! - * - * @author Eduardo Pedroni - * - */ -public class ChromosomeTests { - - private Chromosome chromosome; - private static Resources resources; - - @BeforeClass - public static void setUpBeforeClass() { - resources = new Resources(); - } - - @Before - public void setUp() throws Exception { - chromosome = new Chromosome(resources); - } - - /** - * - */ - @Test - public void cloneTest() { - // create a clone, check to see if it really is a clone - Chromosome clone = new Chromosome(chromosome); - - // compare all elements, one by one - // check outputs - for (int o = 0; o < resources.getInt("outputs"); o++) { - // check that no cross-references exist between chromosomes - assertTrue("Cloned chromosome contains a reference to a member of the original chromosome.", - clone.getOutput(o) != chromosome.getOutput(o) && - clone.getOutput(o).getSource() != chromosome.getOutput(o).getSource()); - // check that the connections are equivalent - if (clone.getOutput(o).getSource() instanceof Input && chromosome.getOutput(o).getSource() instanceof Input) { - assertTrue("Outputs did not connect to equivalent inputs.", - ((Input) clone.getOutput(o).getSource()).getIndex() == ((Input) chromosome.getOutput(o).getSource()).getIndex()); - } else if (clone.getOutput(o).getSource() instanceof Node && chromosome.getOutput(o).getSource() instanceof Node) { - assertTrue("Outputs did not connect to equivalent nodes.", - ((Node) clone.getOutput(o).getSource()).getRow() == ((Node) chromosome.getOutput(o).getSource()).getRow() && - ((Node) clone.getOutput(o).getSource()).getColumn() == ((Node) chromosome.getOutput(o).getSource()).getColumn()); - } else { - fail("Output source types did not match."); - } - } - // check nodes, rows first - for (int row = 0; row < resources.getInt("rows"); row++) { - for (int column = 0; column < resources.getInt("columns"); column++) { - // check that nodes are not pointers to the same instance - assertTrue("Both chromosomes contain a reference to the same node.", clone.getNode(row, column) != chromosome.getNode(row, column)); - // check that both nodes reference their own position in the grid correctly - assertTrue("Equivalent nodes self-reference differently.", clone.getNode(row, column).getRow() == chromosome.getNode(row, column).getRow() && - clone.getNode(row, column).getColumn() == chromosome.getNode(row, column).getColumn()); - // check that the two nodes have the same function - assertTrue("Equivalent nodes have different functions.", clone.getNode(row, column).getFunction() == chromosome.getNode(row, column).getFunction()); - - // compare each connection - for (int connection = 0; connection < resources.getInt("arity"); connection++) { - // first look at whether they are actually the same instance - assertTrue("Nodes are connected to the same connection instance.", - clone.getNode(row, column).getConnection(connection) != chromosome.getNode(row, column).getConnection(connection)); - - // if the connections aren't the same instance, check that their addresses are the same - if (clone.getNode(row, column).getConnection(connection) instanceof Input && - chromosome.getNode(row, column).getConnection(connection) instanceof Input) { - - assertTrue("Nodes did not connect to equivalent inputs.", - ((Input) clone.getNode(row, column).getConnection(connection)).getIndex() == - ((Input) chromosome.getNode(row, column).getConnection(connection)).getIndex()); - - } else if (clone.getNode(row, column).getConnection(connection) instanceof Node && - chromosome.getNode(row, column).getConnection(connection) instanceof Node) { - - assertTrue("Nodes did not connect to equivalent nodes.", - ((Node) clone.getNode(row, column).getConnection(connection)).getRow() == - ((Node) chromosome.getNode(row, column).getConnection(connection)).getRow() && - - ((Node) clone.getNode(row, column).getConnection(connection)).getColumn() == - ((Node) chromosome.getNode(row, column).getConnection(connection)).getColumn()); - - } else { - fail("Connection types did not match."); - } - } - } - } - - // check cloning given a known topology - chromosome = createKnownConfiguration(); - clone = new Chromosome(chromosome); - - Integer[] testInputs = new Integer[] {5, 8, 4}; - chromosome.setInputs((Object[]) testInputs); - clone.setInputs((Object[]) testInputs); - - // check that both chromosomes have the same outputs - for (int i = 0; i < resources.getInt("outputs"); i++) { - assertTrue("Incorrect output returned", ((Integer) chromosome.getOutput(i).calculate()) == ((Integer) clone.getOutput(i).calculate())); - } - - // mutate an output in clone, check that the same node in chromosome produces a different output - clone.getOutput(1).setConnection(resources.getRandomInt(resources.getInt("arity")), clone.getInput(2)); - - assertTrue("Mutation affected nodes in both chromosomes.", - clone.getOutput(1).calculate() != chromosome.getOutput(1).calculate()); - - } - /** - * - */ - @Test - public void fitnessTest() { - // set a fitness value, check if returned value is the same - chromosome.setFitness(10); - assertTrue("Incorrect fitness returned.", chromosome.getFitness() == 10); - } - - /** - * - */ - @Test - public void randomConnectionTest() { - // get random connections with column 0, check that they are all inputs - for (int i = 0; i < 10000; i++) { - boolean connectionReturn = chromosome.getRandomConnection(0) instanceof Input; - assertTrue("Connection is not an input.", connectionReturn); - } - - // get random connections with the last column as reference, check that they're all within range - int connectionNodes = 0, connectionOutOfRange = 0, connectionInputs = 0, connectionPicks = 100000; - int chosenColumn = resources.getInt("columns") - 1; - for (int i = 0; i < connectionPicks; i++) { - Connection c = chromosome.getRandomConnection(chosenColumn); - if (c instanceof Node) { - connectionNodes++; - if (((Node) c).getColumn() >= chosenColumn) { - connectionOutOfRange++; - } - assertTrue("Connection is not allowed : " + ((Node) c).getColumn(), ((Node) c).getColumn() < chosenColumn && ((Node) c).getColumn() < chosenColumn); - } else if (c instanceof Input) { - connectionInputs++; - } else { - fail("Return is neither Node nor Input."); - - } - } - System.out.println("Out of " + connectionPicks + " connections picked from " + ((chosenColumn >= resources.getInt("levelsBack")) ? resources.getInt("levelsBack") : chosenColumn) * resources.getInt("rows") + - " allowed nodes and " + resources.getInt("inputs") + " inputs, " + connectionNodes + " were nodes and " + connectionInputs + " were inputs."); - - System.out.println("Node/input ratio: " + (chosenColumn >= resources.getInt("levelsBack") ? resources.getInt("levelsBack") : chosenColumn) * resources.getDouble("rows") / resources.getDouble("inputs") + - ", picked ratio: " + (double) connectionNodes / (double) connectionInputs); - - System.out.println(connectionOutOfRange + " nodes that disrespected levels back were picked."); - } - /** - * - */ - @Test - public void randomMutableTest() { - // get mutable elements, check Node to Output ratio - int mutablePicks = 100000; - int mutableNodes = 0, mutableOutputs = 0; - for (int i = 0; i < mutablePicks; i++) { - MutableElement m = chromosome.getRandomMutableElement(); - - if (m instanceof Node) { - mutableNodes++; - } else if (m instanceof Output) { - mutableOutputs++; - } else { - fail("Return is neither Node nor Output."); - } - } - System.out.println("Out of " + mutablePicks + " mutable elements picked from " + resources.getInt("nodes") + - " nodes and " + resources.getInt("outputs") + " outputs, " + mutableNodes + " were nodes and " + - mutableOutputs + " were outputs."); - System.out.println("Node/output ratio: " + resources.getDouble("nodes") / resources.getDouble("outputs") + - ", picked ratio: " + (double) mutableNodes / (double) mutableOutputs + "\n"); - } - - /** - * - */ - @Test - public void getOutputsTest() { - chromosome = createKnownConfiguration(); - - chromosome.setInputs(5, 8, 4); - - // with this configuration, the outputs should be 13 and 25. - assertTrue("Incorrect output returned.", (Integer) chromosome.getOutput(0).calculate() == 13); - assertTrue("Incorrect output returned.", (Integer) chromosome.getOutput(1).calculate() == 25); - } - - /** - * - */ - @Test - public void setInputTest() { - // set input values, check that acquired values are correct - Integer[] testInputs = new Integer[resources.getInt("inputs")]; - for (int i = 0; i < resources.getInt("inputs"); i++) { - testInputs[i] = i * 2 - 3; - } - chromosome.setInputs((Object[]) testInputs); - for (int i = 0; i < resources.getInt("inputs"); i++) { - assertTrue("Incorrect input returned.", ((Integer) chromosome.getInput(i).getValue()) == i * 2 - 3); - } - } - - /** - * - */ - @Test - public void getNodeTest() { - // get all nodes one by one, check that they are all correct - for (int r = 0; r < resources.getInt("rows"); r++) { - for (int c = 0; c < resources.getInt("columns"); c++) { - assertTrue("Incorrect node returned.", chromosome.getNode(r, c).getColumn() == c && - chromosome.getNode(r, c).getRow() == r); - } - } - } - - /** - * - */ - @Test - public void activeNodeTest() { - // active node detection happens recursively, the user only calls a single method - // set connections to a known configuration - chromosome = createKnownConfiguration(); - - assertTrue("Active node missing from list.", chromosome.getActiveNodes().contains(chromosome.getNode(0, 0))); - assertTrue("Active node missing from list.", chromosome.getActiveNodes().contains(chromosome.getNode(1, 1))); - assertTrue("Active node missing from list.", chromosome.getActiveNodes().contains(chromosome.getNode(1, 2))); - - assertTrue("List has the wrong number of nodes.", chromosome.getActiveNodes().size() == 3); - } - - /** - * - */ - @Test - public void compareActiveTest() { - // create a clone of the chromosome, compare active nodes - should return true - Chromosome c = new Chromosome(chromosome); - assertTrue("Active nodes did not match.", chromosome.compareActiveTo(c)); - assertTrue("Symmetry not obeyed.", c.compareActiveTo(chromosome)); - - // create a new random chromosome, this time they should not match - c = new Chromosome(resources); - assertTrue("Active nodes did match.", !chromosome.compareActiveTo(c)); - } - - /** - * - */ - @Test - public void compareTest() { - // create a clone of the chromosome, compare - should return true - Chromosome c = new Chromosome(chromosome); - assertTrue("Chromosomes did not match.", chromosome.compareTo(c)); - assertTrue("Symmetry not obeyed.", c.compareTo(chromosome)); - - // create a new random chromosome, this time they should not match - c = new Chromosome(resources); - assertTrue("Chromosomes did match.", !chromosome.compareTo(c)); - } - /** - * Utility for creating a chromosome of known configuration. - * Topology is 3x3, with 3 inputs and 2 outputs. - * Given inputs 5, 8 and 4 outputs should be 13 and 25. - * - * Active nodes (r, c): [0, 0], [1, 1], [1, 2] - * - * @return the configured chromosome - */ - private Chromosome createKnownConfiguration() { - // with a small topology, build a chromosome of known connections and check outputs - resources.set("columns", 3); - resources.set("rows", 3); - resources.set("inputs", 3); - resources.set("outputs", 2); - resources.set("levelsBack", 3); - - Chromosome c = new Chromosome(resources); - - c.getNode(0, 0).initialise(resources.getFunction(0), c.getInput(0), c.getInput(1)); - c.getNode(1, 1).initialise(resources.getFunction(0), c.getNode(0, 0), c.getInput(1)); - c.getNode(1, 2).initialise(resources.getFunction(0), c.getNode(1, 1), c.getInput(2)); - - c.getOutput(0).setConnection(0, c.getNode(0, 0)); - c.getOutput(1).setConnection(0, c.getNode(1, 2)); - - return c; - } -} diff --git a/src/jcgp/tests/InputTests.java b/src/jcgp/tests/InputTests.java deleted file mode 100644 index 012a734..0000000 --- a/src/jcgp/tests/InputTests.java +++ /dev/null @@ -1,47 +0,0 @@ -package jcgp.tests; - -import static org.junit.Assert.assertTrue; -import jcgp.population.Input; - -import org.junit.Before; -import org.junit.Test; - -/** - * - * Tests which cover the behaviour specified for an input. - * - * - An input contains a single set value. This value can be freely set for - * fitness evaluation purposes. - * - It must be addressable by an index set upon construction only. - * - * - * @author Eduardo Pedroni - * - */ -public class InputTests { - - private Input input; - // these are the test values - private final int inputValue = 19; - private final int inputIndex = 12; - - @Before - public void setUp() throws Exception { - input = new Input(inputIndex); - } - - @Test - public void valueTest() { - // assign a value to input, check that the returned value is correct - input.setValue(inputValue); - - assertTrue("Incorrect value returned.", ((Integer) input.getValue()) == inputValue); - } - - @Test - public void indexTest() { - // check that the index returned is the one passed to the constructor - assertTrue("Incorrect index returned.", input.getIndex() == inputIndex); - } - -} diff --git a/src/jcgp/tests/NodeTests.java b/src/jcgp/tests/NodeTests.java deleted file mode 100644 index d8aa742..0000000 --- a/src/jcgp/tests/NodeTests.java +++ /dev/null @@ -1,196 +0,0 @@ -package jcgp.tests; - -import static org.junit.Assert.assertTrue; -import jcgp.JCGP.Resources; -import jcgp.function.Arithmetic; -import jcgp.function.Function; -import jcgp.population.Chromosome; -import jcgp.population.Connection; -import jcgp.population.Node; - -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -/** - * - * Tests which cover the behaviour specified for a node. - * - * - A node should contain read-only row and column values which are set upon construction. - * - It should contain a fully accessible Function object. - * - It should contain a set of connections which can be initialised and randomly - * modified. It should be able to return an addressed connection. - * - It should be able to compute a value using its function with its connections as arguments. - * - * WARNING: changing parameters may cause the tests to incorrectly fail! - * - * @author Eduardo Pedroni - * - */ -public class NodeTests { - - private Node node; - private static Chromosome chromosome; - private static Resources resources; - // these numbers will be used by the node under test - private final int arg1 = 2; - private final int arg2 = 5; - - @BeforeClass - public static void setUpBeforeClass() { - - resources = new Resources(); - - chromosome = new Chromosome(resources); - } - - @Before - public void setUp() throws Exception { - node = new Node(chromosome, 0, 0, resources.getInt("arity")); - // make node with anonymous addition function and hard-coded value connections - node.initialise(new Arithmetic.Addition(), - new Connection[]{new Connection() { - - @Override - public Object getValue() { - // hardcode a value - return arg1; - } - - @Override - public String getDescription() { - // blank - return null; - } - - }, - new Connection() { - - @Override - public Object getValue() { - // hardcode a value - return arg2; - } - - @Override - public String getDescription() { - // blank - return null; - } - - }}); - } - - @Test - public void rowAndColumnTest() { - assertTrue("Incorrect row.", node.getRow() == 0); - assertTrue("Incorrect column.", node.getColumn() == 0); - } - - @Test - public void functionTest() { - // make a new function and assign to node - Function f = new Function() { - - @Override - public Object run(Connection... connections) { - // blank - return 0; - } - - @Override - public int getArity() { - // blank - return 0; - } - - @Override - public String getName() { - // blank - return null; - } - }; - - node.setFunction(f); - - // check that the function returned by the node is f - assertTrue("Incorrect function returned.", node.getFunction() == f); - // check that it outputs 0 as it should - assertTrue("Incorrect function output.", ((Integer) node.getValue()) == 0); - } - - @Test - public void evaluationTest() { - // check that addition is working - assertTrue("Node did not return expected value (sum of arguments). Output was: " + ((int) node.getValue()), - ((int) node.getValue()) == arg1 + arg2); - - // put in a different function, check the output has changed appropriately - node.setFunction(new Arithmetic.Subtraction()); - - assertTrue("Node did not return expected value (difference of arguments).", ((Integer) node.getValue()) == arg1 - arg2); - - } - - @Test - public void connectionsTest() { - // make new blank connections, check that they are returned correctly when addressed - Connection conn0, conn1, conn2; - conn0 = new Connection() { - - @Override - public Object getValue() { - // blank - return 0; - } - - @Override - public String getDescription() { - // blank - return null; - } - - }; - conn1 = new Connection() { - - @Override - public Object getValue() { - // blank - return 0; - } - - @Override - public String getDescription() { - // blank - return null; - } - - }; - node.initialise(null, conn0, conn1); - - assertTrue("Connection 0 is incorrect.", node.getConnection(0) == conn0); - assertTrue("Connection 1 is incorrect.", node.getConnection(1) == conn1); - - // make yet another connection, set it randomly, check that it is one of the node's connections - conn2 = new Connection() { - - @Override - public Object getValue() { - // blank - return 0; - } - - @Override - public String getDescription() { - // blank - return null; - } - }; - node.setConnection(resources.getRandomInt(resources.getInt("arity")), conn2); - - assertTrue("Connection was not found in node.", node.getConnection(0) == conn2 || node.getConnection(1) == conn2); - - } - - -} diff --git a/src/jcgp/tests/OutputTests.java b/src/jcgp/tests/OutputTests.java deleted file mode 100644 index 8658fa4..0000000 --- a/src/jcgp/tests/OutputTests.java +++ /dev/null @@ -1,94 +0,0 @@ -package jcgp.tests; - -import static org.junit.Assert.assertTrue; - -import jcgp.JCGP.Resources; -import jcgp.population.Chromosome; -import jcgp.population.Connection; -import jcgp.population.Output; - -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -/** - * - * Tests which cover the behaviour specified for an output. - * - * - An output contains a single source Connection, which can be set and got. - * - It should return the value of its source connection. - * - It must be addressable by an index set upon construction only. - * - * - * @author Eduardo Pedroni - * - */ -public class OutputTests { - - private Output output; - private static Chromosome chromosome; - private static Resources resources; - // these are the test values - private final int outputValue = 10; - private final int outputIndex = 2; - - @BeforeClass - public static void setUpBeforeClass() { - resources = new Resources(); - chromosome = new Chromosome(resources); - } - - @Before - public void setUp() throws Exception { - output = new Output(chromosome, outputIndex); - } - - @Test - public void evaluationsTest() { - // set source connection, check that the appropriate value is returned - output.setConnection(0, new Connection() { - - @Override - public Object getValue() { - // test value - return outputValue; - } - - @Override - public String getDescription() { - // blank - return null; - } - }); - - assertTrue("Incorrect evaluation.", ((Integer) output.calculate()) == outputValue); - } - - @Test - public void connectionTest() { - // set a new connection, check that it is correctly returned - Connection newConn = new Connection() { - - @Override - public Object getValue() { - // blank - return 0; - } - - @Override - public String getDescription() { - // blank - return null; - } - }; - output.setConnection(0, newConn); - - assertTrue("Incorrect connection returned.", output.getSource() == newConn); - } - - @Test - public void indexTest() { - // check that the index returned is the one passed to the constructor - assertTrue("Incorrect index returned.", output.getIndex() == outputIndex); - } -} diff --git a/src/jcgp/tests/PopulationTests.java b/src/jcgp/tests/PopulationTests.java deleted file mode 100644 index a11becf..0000000 --- a/src/jcgp/tests/PopulationTests.java +++ /dev/null @@ -1,86 +0,0 @@ -package jcgp.tests; - -import static org.junit.Assert.assertTrue; -import jcgp.JCGP.Resources; -import jcgp.population.Chromosome; -import jcgp.population.Population; - -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -/** - * - * Tests which cover the behaviour specified for a population. - * - * - It should be possible to iterate through all the chromosomes in a population. - * - When constructed with no arguments, it should generate populationSize - * random chromosomes, distributed according to the EA parameters. - * - If one or more chromosomes are passed into the constructor, it should use them - * as parents to create the rest of the population. - * - * - * @author Eduardo Pedroni - * - */ -public class PopulationTests { - - private Population population; - private static Resources resources; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - resources = new Resources(); - - -// // initialise function set -// FunctionSet functionSet = new FunctionSet(new Arithmetic.Addition(), new Arithmetic.Subtraction()); -// -// // initialise utilities -// Utilities.setResources(new Random(1234), functionSet); -// -// // initialise parameters -// Resources.setColumns(20); -// Resources.setRows(20); -// Resources.setInputs(2); -// Resources.setOutputs(4); -// Resources.setLevelsBack(1); -// Resources.setMutationRate(10); -// Resources.setTotalGenerations(100); -// Resources.setTotalRuns(5); -// Resources.setPopulationSize(1, 4); -// Resources.setMaxArity(functionSet.getMaxArity()); - } - - @Before - public void setUp() throws Exception { - population = new Population(resources); - } - - @Test - public void defaultPopulationTest() { - // check that the constructor really generates populationSize chromosomes when none is given - int chromosomes = 0; - while (true) { - try { - population.getChromosome(chromosomes); - } catch (IndexOutOfBoundsException e) { - break; - } - chromosomes++; - } - - assertTrue("Incorrect number of chromosomes generated.", chromosomes == resources.getInt("popSize")); - } - - @Test - public void preinitialisedChromosomeTest() { - // the original chromosome that will be cloned - Chromosome oc = new Chromosome(resources); - - // initialise a population with a copy of it - population = new Population(oc, resources); - // check that the first parent chromosome is identical to, but not the same instance as, the one given - assertTrue("Incorrect chromosome in population.", population.getChromosome(0).compareTo(oc) && population.getChromosome(0) != oc); - } -} -- cgit v1.2.3