diff options
30 files changed, 1036 insertions, 651 deletions
diff --git a/src/jcgp/JCGP.java b/src/jcgp/JCGP.java index ee42792..538f677 100644 --- a/src/jcgp/JCGP.java +++ b/src/jcgp/JCGP.java @@ -169,25 +169,25 @@ public class JCGP { problem.evaluate(population, (Resources) resources); report(); - if (resources.getInt("currentGen") < resources.getInt("generations")) { + if (resources.currentGeneration() < resources.generations()) { // we still have generations left to go if (problem.isPerfectSolution(population.getChromosome(evolutionaryStrategy.getFittestChromosome()))) { // solution has been found, start next run - resources.println("[CGP] Solution found on generation " + resources.getInt("currentGen") + ", chromosome: " + evolutionaryStrategy.getFittestChromosome()); + resources.println("[CGP] Solution found, generation " + resources.currentGeneration() + ", chromosome " + evolutionaryStrategy.getFittestChromosome()); - if (resources.getInt("currentRun") < resources.getInt("runs")) { + if (resources.currentRun() < resources.runs()) { // there are still runs left - resources.set("currentRun", resources.getInt("currentRun") + 1); - resources.set("currentGen", 0); + resources.setCurrentRun(resources.currentRun() + 1); + resources.setCurrentGeneration(0); // start a new population - population = new Population((Resources) resources); + population.reinitialise(); } else { // no more generations and no more runs, we're done finished = true; } } else { - resources.set("currentGen", resources.getInt("currentGen") + 1); + resources.setCurrentGeneration(resources.currentGeneration() + 1); } } else { // the run has ended, check if any more runs must be done @@ -195,13 +195,13 @@ public class JCGP { + population.getChromosome(evolutionaryStrategy.getFittestChromosome()).getFitness() + " by chromosome " + evolutionaryStrategy.getFittestChromosome()); - if (resources.getInt("currentRun") < resources.getInt("runs")) { + if (resources.currentRun() < resources.runs()) { // the run has ended but there are still runs left - resources.set("currentRun", resources.getInt("currentRun") + 1); - resources.set("currentGen", 0); + resources.setCurrentRun(resources.currentRun() + 1); + resources.setCurrentGeneration(0); // start a new population - population = new Population(resources); + population.reinitialise();; } else { // no more generations and no more runs, we're done finished = true; @@ -214,16 +214,16 @@ public class JCGP { } private void report() { - if (resources.getInt("report") > 0) { - if (resources.getInt("currentGen") % resources.getInt("report") == 0) { - resources.println("[CGP] Generation: " + resources.getInt("currentGen") + ", fitness: " + population.getChromosome(evolutionaryStrategy.getFittestChromosome()).getFitness()); + if (resources.report() > 0) { + if (resources.currentGeneration() % resources.report() == 0) { + resources.println("[CGP] Generation: " + resources.currentGeneration() + ", fitness: " + population.getChromosome(evolutionaryStrategy.getFittestChromosome()).getFitness()); } } } public void start() { if (!finished) { - while (resources.getInt("currentGen") <= resources.getInt("generations")) { + while (resources.currentGeneration() <= resources.generations()) { nextGeneration(); if (finished) { break; @@ -236,8 +236,8 @@ public class JCGP { public void reset() { finished = false; population = new Population(resources); - resources.set("currentGen", 1); - resources.set("currentRun", 1); + resources.setCurrentGeneration(1); + resources.setCurrentRun(1); resources.println("-----------------------------"); resources.println("New experiment: " + problem.toString()); } diff --git a/src/jcgp/backend/modules/Module.java b/src/jcgp/backend/modules/Module.java index 8a95737..a6b4d73 100644 --- a/src/jcgp/backend/modules/Module.java +++ b/src/jcgp/backend/modules/Module.java @@ -4,6 +4,6 @@ import jcgp.backend.resources.parameters.Parameter; public interface Module { - public abstract Parameter[] getLocalParameters(); + public abstract Parameter<?>[] getLocalParameters(); } diff --git a/src/jcgp/backend/modules/es/MuPlusLambda.java b/src/jcgp/backend/modules/es/MuPlusLambda.java index 53fb932..67236f9 100644 --- a/src/jcgp/backend/modules/es/MuPlusLambda.java +++ b/src/jcgp/backend/modules/es/MuPlusLambda.java @@ -25,11 +25,11 @@ public class MuPlusLambda implements EvolutionaryStrategy { public MuPlusLambda(final Resources resources) { parents = new IntegerParameter(1, "Parents") { @Override - public void validate(int newValue) { - if (newValue + offspring.get() != resources.getInt("popSize")) { + public void validate(Number newValue) { + if (newValue.intValue() + offspring.get() != resources.populationSize()) { status = ParameterStatus.INVALID; status.setDetails("Parents + offspring must equal population size."); - } else if (newValue <= 0) { + } else if (newValue.intValue() <= 0) { status = ParameterStatus.INVALID; status.setDetails("EA needs at least 1 parent."); } else { @@ -39,11 +39,11 @@ public class MuPlusLambda implements EvolutionaryStrategy { }; offspring = new IntegerParameter(4, "Offspring") { @Override - public void validate(int newValue) { - if (newValue + parents.get() != resources.getInt("popSize")) { + public void validate(Number newValue) { + if (newValue.intValue() + parents.get() != resources.populationSize()) { status = ParameterStatus.INVALID; status.setDetails("Parents + offspring must equal population size."); - } else if (newValue <= 0) { + } else if (newValue.intValue() <= 0) { status = ParameterStatus.INVALID; status.setDetails("EA needs at least 1 offspring."); } else { @@ -53,7 +53,7 @@ public class MuPlusLambda implements EvolutionaryStrategy { }; report = new BooleanParameter(false, "Report") { @Override - public void validate(boolean newValue) { + public void validate(Boolean newValue) { // nothing } }; @@ -65,7 +65,7 @@ public class MuPlusLambda implements EvolutionaryStrategy { fittestChromosome = 0; if (report.get()) resources.reportln("[ES] Selecting fittest chromosome..."); - for (int i = 0; i < resources.getInt("popSize"); i++) { + for (int i = 0; i < resources.populationSize(); i++) { if (report.get()) resources.reportln("[ES] Chromosome " + i + ", fitness: " + population.getChromosome(i).getFitness()); if (population.getChromosome(i).getFitness() >= population.getChromosome(fittestChromosome).getFitness()) { fittestChromosome = i; @@ -74,7 +74,7 @@ public class MuPlusLambda implements EvolutionaryStrategy { if (report.get()) resources.reportln("[ES] Selected chromosome: " + fittestChromosome); // create copies of fittest chromosome, mutate them - for (int i = 0; i < resources.getInt("popSize"); i++) { + for (int i = 0; i < resources.populationSize(); i++) { if (i != fittestChromosome) { if (report.get()) resources.reportln("[ES] Copying fittest chromosome to population position " + i); population.copyChromosome(fittestChromosome, i); @@ -83,6 +83,8 @@ public class MuPlusLambda implements EvolutionaryStrategy { } } + if (report.get()) resources.reportln("[ES] Generation is complete."); + } @Override @@ -91,7 +93,7 @@ public class MuPlusLambda implements EvolutionaryStrategy { } @Override - public Parameter[] getLocalParameters() { + public Parameter<?>[] getLocalParameters() { return new Parameter[] {parents, offspring, report}; } diff --git a/src/jcgp/backend/modules/es/TournamentSelection.java b/src/jcgp/backend/modules/es/TournamentSelection.java index 3954de8..8286101 100644 --- a/src/jcgp/backend/modules/es/TournamentSelection.java +++ b/src/jcgp/backend/modules/es/TournamentSelection.java @@ -1,7 +1,5 @@ package jcgp.backend.modules.es; -import java.util.HashMap; - import jcgp.backend.modules.mutator.Mutator; import jcgp.backend.population.Population; import jcgp.backend.resources.Resources; @@ -13,22 +11,18 @@ public class TournamentSelection implements EvolutionaryStrategy { private int fittestChromosome; private IntegerParameter tournament; - private HashMap<String, Parameter> localParameters; public TournamentSelection() { tournament = new IntegerParameter(1, "Tournament size") { @Override - public void validate(int newValue) { + public void validate(Number newValue) { // TODO this } }; - - localParameters = new HashMap<String, Parameter>(); - localParameters.put("tournament", tournament); } @Override - public Parameter[] getLocalParameters() { + public Parameter<?>[] getLocalParameters() { return new Parameter[] {tournament}; } diff --git a/src/jcgp/backend/modules/fitness/TestCaseProblem.java b/src/jcgp/backend/modules/fitness/TestCaseProblem.java index 4259285..7dd24af 100644 --- a/src/jcgp/backend/modules/fitness/TestCaseProblem.java +++ b/src/jcgp/backend/modules/fitness/TestCaseProblem.java @@ -56,7 +56,7 @@ public abstract class TestCaseProblem<U> extends Problem { maxFitness = new IntegerParameter(0, "Max fitness", true, false) { @Override - public void validate(int newValue) { + public void validate(Number newValue) { // blank } }; @@ -67,14 +67,14 @@ public abstract class TestCaseProblem<U> extends Problem { @Override public void evaluate(Population population, Resources resources) { // for every chromosome in the population - for (int i = 0; i < resources.getInt("popSize"); i++) { + for (int i = 0; i < resources.populationSize(); i++) { // assume an initial fitness of 0 int fitness = 0; // for each test case for (int t = 0; t < testCases.size(); t++) { population.getChromosome(i).setInputs(testCases.get(t).getInputs()); // check each output - for (int o = 0; o < resources.getInt("outputs"); o++) { + for (int o = 0; o < resources.outputs(); o++) { if (population.getChromosome(i).getOutput(o).calculate() == testCases.get(t).getOutput(o)) { fitness++; } @@ -86,7 +86,7 @@ public abstract class TestCaseProblem<U> extends Problem { } @Override - public Parameter[] getLocalParameters() { + public Parameter<?>[] getLocalParameters() { return new Parameter[]{maxFitness}; } diff --git a/src/jcgp/backend/modules/mutator/PointMutator.java b/src/jcgp/backend/modules/mutator/PointMutator.java index 1f38cfe..ab8efad 100644 --- a/src/jcgp/backend/modules/mutator/PointMutator.java +++ b/src/jcgp/backend/modules/mutator/PointMutator.java @@ -18,11 +18,11 @@ public class PointMutator implements Mutator { public PointMutator(final Resources resources) { mutationRate = new DoubleParameter(50, "Percent mutation", false, false) { @Override - public void validate(double newValue) { - if (newValue <= 0 || newValue > 100) { + public void validate(Number newValue) { + if (newValue.doubleValue() <= 0 || newValue.doubleValue() > 100) { status = ParameterStatus.INVALID; status.setDetails("Mutation rate must be > 0 and <= 100"); - } else if ((int) ((newValue / 100) * resources.getDouble("nodes")) <= 0) { + } else if ((int) ((newValue.doubleValue() / 100) * (double) resources.nodes()) <= 0) { status = ParameterStatus.WARNING; status.setDetails("With mutation rate " + mutationRate.get() + ", 0 genes will be mutated."); } else { @@ -33,7 +33,7 @@ public class PointMutator implements Mutator { report = new BooleanParameter(false, "Report") { @Override - public void validate(boolean newValue) { + public void validate(Boolean newValue) { // blank } }; @@ -41,7 +41,7 @@ public class PointMutator implements Mutator { @Override public void mutate(Chromosome chromosome, Resources resources) { - int mutations = (int) ((mutationRate.get()) * ((((resources.getDouble("nodes")) + (resources.getDouble("outputs")))) / 100)); + int mutations = (int) ((mutationRate.get()) * (((((double) resources.nodes() + resources.outputs()))) / 100)); if (report.get()) resources.reportln("[Mutator] Number of mutations to be performed: " + mutations); for (int i = 0; i < mutations; i++) { MutableElement m = chromosome.getRandomMutableElement(); @@ -54,7 +54,7 @@ public class PointMutator implements Mutator { if (report.get()) resources.reportln("to " + ((Output) m).getSource().toString()); } else if (m instanceof Node) { - int geneType = resources.getRandomInt(1 + resources.getInt("arity")); + int geneType = resources.getRandomInt(1 + resources.arity()); if (geneType < 1) { if (report.get()) resources.report("changed function from " + ((Node) m).getFunction().getName() + " "); @@ -62,7 +62,7 @@ public class PointMutator implements Mutator { if (report.get()) resources.reportln("to " + ((Node) m).getFunction().getName()); } else { - int connection = resources.getRandomInt(resources.getInt("arity")); + int connection = resources.getRandomInt(resources.arity()); if (report.get()) resources.report("changed connection " + connection + " from " + ((Node) m).getConnection(connection) + " "); m.setConnection(connection, chromosome.getRandomConnection(((Node) m).getColumn())); @@ -74,7 +74,7 @@ public class PointMutator implements Mutator { } @Override - public Parameter[] getLocalParameters() { + public Parameter<?>[] getLocalParameters() { return new Parameter[] {mutationRate, report}; } diff --git a/src/jcgp/backend/population/Chromosome.java b/src/jcgp/backend/population/Chromosome.java index bbada14..71e19ec 100644 --- a/src/jcgp/backend/population/Chromosome.java +++ b/src/jcgp/backend/population/Chromosome.java @@ -31,7 +31,7 @@ public class Chromosome { // allocate memory for all elements of the chromosome instantiateElements(); // set random connections so that the chromosome can be evaluated - initialiseConnections(); + reinitialiseConnections(); } /** @@ -55,22 +55,22 @@ public class Chromosome { * */ private void instantiateElements() { - inputs = new Input[(resources.getInt("inputs"))]; - for (int i = 0; i < (resources.getInt("inputs")); i++) { + inputs = new Input[(resources.inputs())]; + for (int i = 0; i < inputs.length; i++) { inputs[i] = new Input(i); } - int arity = resources.getInt("arity"); + int arity = resources.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 = new Node[(resources.rows())][(resources.columns())]; + for (int r = 0; r < nodes.length; r++) { + for (int c = 0; c < nodes[r].length; 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 = new Output[resources.outputs()]; + for (int o = 0; o < outputs.length; o++) { outputs[o] = new Output(this, o); } } @@ -78,9 +78,9 @@ public class Chromosome { /** * */ - private void initialiseConnections() { + public void reinitialiseConnections() { - int arity = resources.getInt("arity"); + int arity = resources.arity(); // initialise nodes - [rows][columns] for (int r = 0; r < nodes.length; r++) { @@ -103,7 +103,7 @@ public class Chromosome { * @param clone */ public void copyGenes(Chromosome clone) { - int arity = resources.getInt("arity"); + int arity = resources.arity(); // copy nodes - [rows][columns] for (int r = 0; r < nodes.length; r++) { @@ -164,6 +164,7 @@ public class Chromosome { /** * + * * @param values * @throws ParameterMismatchException */ @@ -186,7 +187,7 @@ public class Chromosome { */ public MutableElement getRandomMutableElement() { // choose output or node - int index = resources.getRandomInt(outputs.length + (resources.getInt("rows")) * (resources.getInt("columns"))); + int index = resources.getRandomInt(outputs.length + (resources.rows() * resources.columns())); if (index < outputs.length) { // outputs @@ -194,7 +195,7 @@ public class Chromosome { } else { // node index -= outputs.length; - return nodes[index / (resources.getInt("columns"))][index % (resources.getInt("columns"))]; + return nodes[index / resources.columns()][index % resources.columns()]; } } @@ -208,7 +209,7 @@ public class Chromosome { */ public Connection getRandomConnection(int column) { // work out the allowed range obeying levels back - int allowedColumns = ((column >= (resources.getInt("levelsBack"))) ? (resources.getInt("levelsBack")) : column); + int allowedColumns = column >= resources.levelsBack() ? resources.levelsBack() : column; int offset = ((column - allowedColumns) * nodes.length) - inputs.length; // choose input or allowed node @@ -235,14 +236,14 @@ public class Chromosome { */ public Connection getRandomConnection() { // choose output or node - int index = resources.getRandomInt(inputs.length + (resources.getInt("columns")) * (resources.getInt("rows"))); + int index = resources.getRandomInt(inputs.length + (resources.columns() * resources.rows())); if (index < inputs.length) { // outputs return inputs[index]; } else { // node index -= inputs.length; - return nodes[index / (resources.getInt("columns"))][index % (resources.getInt("columns"))]; + return nodes[index / resources.columns()][index % resources.columns()]; } } @@ -273,19 +274,18 @@ public class Chromosome { 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++) { + for (int r = 0; r < resources.rows(); r++) { + for (int c = 0; c < resources.columns(); c++) { if (!(nodes[r][c].copyOf(chromosome.getNode(r, c)))) { return false; } } } - for (int o = 0; o < (resources.getInt("outputs")); o++) { + for (int o = 0; o < resources.outputs(); o++) { if (!(outputs[o].copyOf(chromosome.getOutput(o)))) { return false; } @@ -311,11 +311,11 @@ public class Chromosome { public void printNodes() { // TODO make this proper - int arity = resources.getInt("arity"); + int arity = resources.arity(); - for (int r = 0; r < (resources.getInt("rows")); r++) { + for (int r = 0; r < resources.rows(); r++) { System.out.print("r: " + r + "\t"); - for (int c = 0; c < (resources.getInt("columns")); c++) { + for (int c = 0; c < resources.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).toString() + ") "); @@ -325,9 +325,11 @@ public class Chromosome { System.out.print("\n"); } - for (int o = 0; o < (resources.getInt("outputs")); o++) { + for (int o = 0; o < resources.outputs(); o++) { System.out.print("o: " + o + " (" + outputs[o].getSource().toString() + ")\t"); } + + System.out.println(); } public Resources getResources() { diff --git a/src/jcgp/backend/population/Node.java b/src/jcgp/backend/population/Node.java index 87a2f99..6a558a4 100644 --- a/src/jcgp/backend/population/Node.java +++ b/src/jcgp/backend/population/Node.java @@ -37,7 +37,7 @@ public class Node extends Gene implements MutableElement, Connection { public void initialise(Function newFunction, Connection ... newConnections) throws InsufficientConnectionsException { function = newFunction; - if (newConnections.length == chromosome.getResources().getInt("arity")) { + if (newConnections.length == chromosome.getResources().arity()) { connections = newConnections; } else { throw new InsufficientConnectionsException(); diff --git a/src/jcgp/backend/population/Population.java b/src/jcgp/backend/population/Population.java index d2e6058..fdeec82 100644 --- a/src/jcgp/backend/population/Population.java +++ b/src/jcgp/backend/population/Population.java @@ -5,7 +5,7 @@ import jcgp.backend.resources.Resources; public class Population { private Chromosome[] chromosomes; - private Resources resources; + private final Resources resources; /** * Initialise a random population according to the parameters specified @@ -16,7 +16,7 @@ public class Population { public Population(Resources resources) { this.resources = resources; - chromosomes = new Chromosome[(resources.getInt("popSize"))]; + chromosomes = new Chromosome[resources.populationSize()]; for (int c = 0; c < chromosomes.length; c++) { chromosomes[c] = new Chromosome(resources); } @@ -31,8 +31,7 @@ public class Population { public Population(Chromosome parent, Resources resources) { this.resources = resources; - chromosomes = new Chromosome[(resources.getInt("popSize"))]; - // generate the rest of the individuals + chromosomes = new Chromosome[resources.populationSize()]; for (int c = 0; c < chromosomes.length; c++) { chromosomes[c] = new Chromosome(parent); } @@ -72,7 +71,10 @@ public class Population { } } - - + public void reinitialise() { + for (int c = 0; c < chromosomes.length; c++) { + chromosomes[c].reinitialiseConnections(); + } + } } diff --git a/src/jcgp/backend/resources/ModifiableResources.java b/src/jcgp/backend/resources/ModifiableResources.java index a221f73..689f846 100644 --- a/src/jcgp/backend/resources/ModifiableResources.java +++ b/src/jcgp/backend/resources/ModifiableResources.java @@ -1,8 +1,6 @@ package jcgp.backend.resources; import jcgp.backend.function.FunctionSet; -import jcgp.backend.resources.parameters.BooleanParameter; -import jcgp.backend.resources.parameters.DoubleParameter; import jcgp.backend.resources.parameters.IntegerParameter; /** @@ -21,19 +19,191 @@ public class ModifiableResources extends Resources { super(); } - public void set(String key, Object value) { - if (parameters.get(key) instanceof IntegerParameter) { - ((IntegerParameter) parameters.get(key)).set(((Integer) value).intValue()); - } else if (parameters.get(key) instanceof DoubleParameter) { - ((DoubleParameter) parameters.get(key)).set(((Double) value).doubleValue()); - } else if (parameters.get(key) instanceof BooleanParameter) { - ((BooleanParameter) parameters.get(key)).set(((Boolean) value).booleanValue()); - } + /** + * @param rows the rows to set + */ + public void setRows(int rows) { + this.rows.set(rows); + } + + /** + * @param columns the columns to set + */ + public void setColumns(int columns) { + this.columns.set(columns); + } + + /** + * @param inputs the inputs to set + */ + public void setInputs(int inputs) { + this.inputs.set(inputs); + } + + /** + * @param outputs the outputs to set + */ + public void setOutputs(int outputs) { + this.outputs.set(outputs); + } + + /** + * @param populationSize the populationSize to set + */ + public void setPopulationSize(int populationSize) { + this.populationSize.set(populationSize); + } + + /** + * @param levelsBack the levelsBack to set + */ + public void setLevelsBack(int levelsBack) { + this.levelsBack.set(levelsBack); + } + + /** + * @param currentGeneration the currentGeneration to set + */ + public void setCurrentGeneration(int currentGeneration) { + this.currentGeneration.set(currentGeneration); + } + + /** + * @param generations the generations to set + */ + public void setGenerations(int generations) { + this.generations.set(generations); + } + + /** + * @param currentRun the currentRun to set + */ + public void setCurrentRun(int currentRun) { + this.currentRun.set(currentRun); + } + + /** + * @param runs the runs to set + */ + public void setRuns(int runs) { + this.runs.set(runs); + } + + /** + * @param arity the arity to set + */ + public void setArity(int arity) { + this.arity.set(arity); + } + + /** + * @param seed the seed to set + */ + public void setSeed(int seed) { + this.seed.set(seed); + } + + /** + * @param report the report to set + */ + public void setReport(int report) { + this.report.set(report); + } + + /** + * @return the rows + */ + public IntegerParameter getRowsParameter() { + return rows; + } + + /** + * @return the columns + */ + public IntegerParameter getColumnsParameter() { + return columns; + } + + /** + * @return the inputs + */ + public IntegerParameter getInputsParameter() { + return inputs; + } + + /** + * @return the outputs + */ + public IntegerParameter getOutputsParameter() { + return outputs; + } + + /** + * @return the populationSize + */ + public IntegerParameter getPopulationSizeParameter() { + return populationSize; + } + + /** + * @return the levelsBack + */ + public IntegerParameter getLevelsBackParameter() { + return levelsBack; + } + + /** + * @return the currentGeneration + */ + public IntegerParameter getCurrentGenerationParameter() { + return currentGeneration; + } + + /** + * @return the generations + */ + public IntegerParameter getGenerationsParameter() { + return generations; + } + + /** + * @return the currentRun + */ + public IntegerParameter getCurrentRunParameter() { + return currentRun; + } + + /** + * @return the runs + */ + public IntegerParameter getRunsParameter() { + return runs; + } + + /** + * @return the arity + */ + public IntegerParameter getArityParameter() { + return arity; + } + + /** + * @return the seed + */ + public IntegerParameter getSeedParameter() { + return seed; + } + + /** + * @return the report + */ + public IntegerParameter getReportParameter() { + return report; } public void setFunctionSet(FunctionSet functionSet) { this.functionSet = functionSet; - set("arity", functionSet.getMaxArity()); + setArity(functionSet.getMaxArity()); } public void setConsole(Console console) { @@ -56,5 +226,4 @@ public class ModifiableResources extends Resources { console.print(s); } } - } diff --git a/src/jcgp/backend/resources/Resources.java b/src/jcgp/backend/resources/Resources.java index 13e0c51..c83fa35 100644 --- a/src/jcgp/backend/resources/Resources.java +++ b/src/jcgp/backend/resources/Resources.java @@ -1,16 +1,12 @@ package jcgp.backend.resources; -import java.util.HashMap; import java.util.Random; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import jcgp.backend.function.Function; import jcgp.backend.function.FunctionSet; -import jcgp.backend.resources.parameters.BooleanParameter; -import jcgp.backend.resources.parameters.DoubleParameter; import jcgp.backend.resources.parameters.IntegerParameter; -import jcgp.backend.resources.parameters.Parameter; import jcgp.backend.resources.parameters.ParameterStatus; /** @@ -23,12 +19,12 @@ import jcgp.backend.resources.parameters.ParameterStatus; * */ public class Resources { - protected HashMap<String, Parameter> parameters = new HashMap<String, Parameter>(); + protected IntegerParameter rows, columns, inputs, outputs, populationSize, + levelsBack, currentGeneration, generations, currentRun, runs, + arity, seed, report; protected Random numberGenerator = new Random(); - protected FunctionSet functionSet; - // GUI console protected Console console; @@ -36,175 +32,234 @@ public class Resources { createBaseParameters(); } - public int getInt(String key) { - if (parameters.get(key) instanceof IntegerParameter) { - return ((IntegerParameter) parameters.get(key)).get(); - } else if (parameters.get(key) instanceof DoubleParameter) { - return (int) ((DoubleParameter) parameters.get(key)).get(); - } else { - throw new ClassCastException("Could not cast " + parameters.get(key).getClass() + " to int."); - } + /** + * @return the rows + */ + public int rows() { + return rows.get(); } - - public double getDouble(String key) { - if (parameters.get(key) instanceof IntegerParameter) { - return ((IntegerParameter) parameters.get(key)).get(); - } else if (parameters.get(key) instanceof DoubleParameter) { - return ((DoubleParameter) parameters.get(key)).get(); - } else { - throw new ClassCastException("Could not cast " + parameters.get(key).getClass() + " to double."); - } + + /** + * @return the columns + */ + public int columns() { + return columns.get(); } - - public boolean getBoolean(String key) { - if (parameters.get(key) instanceof BooleanParameter) { - return ((BooleanParameter) parameters.get(key)).get(); - } else { - throw new ClassCastException("Could not cast " + parameters.get(key).getClass() + " to int."); - } + + /** + * @return the inputs + */ + public int inputs() { + return inputs.get(); } - - public Parameter getParameter(String key) { - return parameters.get(key); + + /** + * @return the outputs + */ + public int outputs() { + return outputs.get(); } - - public boolean contains(String key) { - return parameters.containsKey(key); + + /** + * @return the populationSize + */ + public int populationSize() { + return populationSize.get(); } - + + /** + * @return the levelsBack + */ + public int levelsBack() { + return levelsBack.get(); + } + + /** + * @return the nodes + */ + public int nodes() { + return columns.get() * rows.get(); + } + + /** + * @return the currentGeneration + */ + public int currentGeneration() { + return currentGeneration.get(); + } + + /** + * @return the generations + */ + public int generations() { + return generations.get(); + } + + /** + * @return the currentRun + */ + public int currentRun() { + return currentRun.get(); + } + + /** + * @return the runs + */ + public int runs() { + return runs.get(); + } + + /** + * @return the arity + */ + public int arity() { + return arity.get(); + } + + /** + * @return the seed + */ + public int seed() { + return seed.get(); + } + + /** + * @return the report + */ + public int report() { + return report.get(); + } + private void createBaseParameters() { - parameters.put("rows", new IntegerParameter(8, "Rows", false, true) { + rows = new IntegerParameter(5, "Rows", false, true) { @Override - public void validate(int newValue) { - if (newValue <= 0) { + public void validate(Number newValue) { + if (newValue.intValue() <= 0) { status = ParameterStatus.INVALID; status.setDetails("Chromosome must have at least 1 row."); } else { status = ParameterStatus.VALID; } } - }); - parameters.put("columns", new IntegerParameter(9, "Columns", false, true) { + }; + + columns = new IntegerParameter(5, "Columns", false, true) { @Override - public void validate(int newValue) { - if (newValue <= 0) { + public void validate(Number newValue) { + if (newValue.intValue() <= 0) { status = ParameterStatus.INVALID; status.setDetails("Chromosome must have at least 1 column."); } else { status = ParameterStatus.VALID; } } - }); - parameters.put("inputs", new IntegerParameter(3, "Inputs", false, true) { + }; + + inputs = new IntegerParameter(3, "Inputs", false, true) { @Override - public void validate(int newValue) { - if (newValue <= 0) { + public void validate(Number newValue) { + if (newValue.intValue() <= 0) { status = ParameterStatus.INVALID; status.setDetails("Chromosome must have at least 1 input."); } else { status = ParameterStatus.VALID; } } - }); - parameters.put("outputs", new IntegerParameter(3, "Outputs", false, true) { + }; + + outputs = new IntegerParameter(3, "Outputs", false, true) { @Override - public void validate(int newValue) { - if (newValue <= 0) { + public void validate(Number newValue) { + if (newValue.intValue() <= 0) { status = ParameterStatus.INVALID; status.setDetails("Chromosome must have at least 1 output."); } else { status = ParameterStatus.VALID; } } - }); - parameters.put("popSize", new IntegerParameter(5, "Population", false, true) { + }; + + populationSize = new IntegerParameter(5, "Population", false, true) { @Override - public void validate(int newValue) { - if (newValue <= 0) { + public void validate(Number newValue) { + if (newValue.intValue() <= 0) { status = ParameterStatus.INVALID; status.setDetails("Population size must be at least 1."); } else { status = ParameterStatus.VALID; } } - }); - parameters.put("levelsBack", new IntegerParameter(2, "Levels back", false, true) { + }; + + levelsBack = new IntegerParameter(2, "Levels back", false, true) { @Override - public void validate(int newValue) { - if (newValue <= 0) { + public void validate(Number newValue) { + if (newValue.intValue() <= 0) { status = ParameterStatus.INVALID; status.setDetails("Levels back must be at least 1."); - } else if (newValue > getInt("columns")) { + } else if (newValue.intValue() > columns.get()) { status = ParameterStatus.INVALID; status.setDetails("Levels back must be less than or equal to the number of columns."); } else { status = ParameterStatus.VALID; } } - }); - - IntegerParameter nodes = new IntegerParameter(1, "Nodes", true, false) { - @Override - public void validate(int newValue) { - // blank - } }; - nodes.valueProperty().bind(((IntegerParameter) parameters.get("rows")).valueProperty().multiply(((IntegerParameter) parameters.get("columns")).valueProperty())); - parameters.put("nodes", nodes); - - parameters.put("generations", new IntegerParameter(1000000, "Generations") { + + generations = new IntegerParameter(1000000, "Generations") { @Override - public void validate(int newValue) { - if (newValue <= 0) { + public void validate(Number newValue) { + if (newValue.intValue() <= 0) { status = ParameterStatus.INVALID; status.setDetails("Number of generations must be greater than 0."); - } else if (newValue < getInt("currentGen")) { + } else if (newValue.intValue() < currentGeneration.get()) { status = ParameterStatus.WARNING_RESET; status.setDetails("Setting generations to less than the current generation will cause the experiment to restart."); } else { status = ParameterStatus.VALID; } } - }); - parameters.put("currentGen", new IntegerParameter(1, "Generation", true, false) { + }; + + currentGeneration = new IntegerParameter(1, "Generation", true, false) { @Override - public void validate(int newValue) { + public void validate(Number newValue) { // blank } - }); + }; - parameters.put("runs", new IntegerParameter(5, "Runs") { + runs = new IntegerParameter(5, "Runs") { @Override - public void validate(int newValue) { - if (newValue <= 0) { + public void validate(Number newValue) { + if (newValue.intValue() <= 0) { status = ParameterStatus.INVALID; status.setDetails("Number of runs must be greater than 0."); - } else if (newValue < getInt("currentRun")) { + } else if (newValue.intValue() < currentRun.get()) { status = ParameterStatus.WARNING_RESET; status.setDetails("Setting runs to less than the current run will cause the experiment to restart."); } else { status = ParameterStatus.VALID; } } - }); - parameters.put("currentRun", new IntegerParameter(1, "Run", true, false) { + }; + + currentRun = new IntegerParameter(1, "Run", true, false) { @Override - public void validate(int newValue) { + public void validate(Number newValue) { // blank } - }); + }; - //parameters.put("arity", new IntegerParameter(functionSet.getMaxArity(), "Max arity", true, false) { - parameters.put("arity", new IntegerParameter(0, "Max arity", true, false) { + arity = new IntegerParameter(0, "Max arity", true, false) { @Override - public void validate(int newValue) { + public void validate(Number newValue) { // blank } - }); + }; - IntegerParameter seed = new IntegerParameter(1234, "Seed", false, true) { + seed = new IntegerParameter(1234, "Seed", false, true) { @Override - public void validate(int newValue) { + public void validate(Number newValue) { status = ParameterStatus.VALID; } }; @@ -217,19 +272,18 @@ public class Resources { } }); numberGenerator.setSeed(seed.get()); - parameters.put("seed", seed); - parameters.put("report", new IntegerParameter(1, "Report", false, false) { + report = new IntegerParameter(1, "Report", false, false) { @Override - public void validate(int newValue) { - if (newValue > getInt("generations")) { + public void validate(Number newValue) { + if (newValue.intValue() > generations.get()) { status = ParameterStatus.WARNING; status.setDetails("No reports will be printed."); } else { status = ParameterStatus.VALID; } } - }); + }; } /* @@ -271,8 +325,8 @@ public class Resources { * These are affected by parameter report */ public void reportln(String s) { - if (getInt("report") > 0) { - if (getInt("currentGen") % getInt("report") == 0) { + if (report.get() > 0) { + if (currentGeneration.get() % report.get() == 0) { System.out.println(s); if (console != null) { console.println(s); @@ -282,8 +336,8 @@ public class Resources { } public void report(String s) { - if (getInt("report") > 0) { - if (getInt("currentGen") % getInt("report") == 0) { + if (report.get() > 0) { + if (currentGeneration.get() % report.get() == 0) { System.out.print(s); if (console != null) { console.print(s); diff --git a/src/jcgp/backend/resources/parameters/BooleanParameter.java b/src/jcgp/backend/resources/parameters/BooleanParameter.java index cd17649..cc74a64 100644 --- a/src/jcgp/backend/resources/parameters/BooleanParameter.java +++ b/src/jcgp/backend/resources/parameters/BooleanParameter.java @@ -2,13 +2,11 @@ package jcgp.backend.resources.parameters; import javafx.beans.property.SimpleBooleanProperty; -public abstract class BooleanParameter extends Parameter { - - private SimpleBooleanProperty value; - +public abstract class BooleanParameter extends Parameter<Boolean> { + public BooleanParameter(boolean value, String name, boolean monitor, boolean critical) { super(name, monitor, critical); - this.value = new SimpleBooleanProperty(value); + this.valueProperty = new SimpleBooleanProperty(value); } /** @@ -20,23 +18,6 @@ public abstract class BooleanParameter extends Parameter { */ public BooleanParameter(boolean value, String name) { super(name, false, false); - this.value = new SimpleBooleanProperty(value); - } - - public boolean get() { - return value.get(); - } - - public void set(boolean newValue) { - if (!value.isBound()) { - value.set(newValue); - } - } - - public abstract void validate(boolean newValue); - - @Override - public SimpleBooleanProperty valueProperty() { - return value; + this.valueProperty = new SimpleBooleanProperty(value); } } diff --git a/src/jcgp/backend/resources/parameters/DoubleParameter.java b/src/jcgp/backend/resources/parameters/DoubleParameter.java index 8464c83..b109446 100644 --- a/src/jcgp/backend/resources/parameters/DoubleParameter.java +++ b/src/jcgp/backend/resources/parameters/DoubleParameter.java @@ -2,35 +2,20 @@ package jcgp.backend.resources.parameters; import javafx.beans.property.SimpleDoubleProperty; -public abstract class DoubleParameter extends Parameter { - - protected SimpleDoubleProperty value; +public abstract class DoubleParameter extends Parameter<Number> { public DoubleParameter(double value, String name, boolean monitor, boolean critical) { super(name, monitor, critical); - this.value = new SimpleDoubleProperty(value); + this.valueProperty = new SimpleDoubleProperty(value); } public DoubleParameter(double value, String name) { super(name, false, false); - this.value = new SimpleDoubleProperty(value); + this.valueProperty = new SimpleDoubleProperty(value); } - public double get() { - return value.get(); - } - - public void set(double newValue) { - if (!value.isBound()) { - value.set(newValue); - } - } - @Override - public SimpleDoubleProperty valueProperty() { - return value; + public Double get() { + return super.get().doubleValue(); } - - public abstract void validate(double newValue); - } diff --git a/src/jcgp/backend/resources/parameters/IntegerParameter.java b/src/jcgp/backend/resources/parameters/IntegerParameter.java index 2a7b2a7..7cf68bd 100644 --- a/src/jcgp/backend/resources/parameters/IntegerParameter.java +++ b/src/jcgp/backend/resources/parameters/IntegerParameter.java @@ -2,36 +2,20 @@ package jcgp.backend.resources.parameters; import javafx.beans.property.SimpleIntegerProperty; -public abstract class IntegerParameter extends Parameter { - - private SimpleIntegerProperty value; +public abstract class IntegerParameter extends Parameter<Number> { public IntegerParameter(int value, String name, boolean monitor, boolean critical) { super(name, monitor, critical); - this.value = new SimpleIntegerProperty(value); + this.valueProperty = new SimpleIntegerProperty(value); } public IntegerParameter(int value, String name) { super(name, false, false); - this.value = new SimpleIntegerProperty(value); + this.valueProperty = new SimpleIntegerProperty(value); } - public int get() { - return value.get(); - } - - public void set(int newValue) { - if (!value.isBound()) { - validate(newValue); - value.set(newValue); - } - } - @Override - public SimpleIntegerProperty valueProperty() { - return value; + public Integer get() { + return super.get().intValue(); } - - public abstract void validate(int newValue); - } diff --git a/src/jcgp/backend/resources/parameters/Parameter.java b/src/jcgp/backend/resources/parameters/Parameter.java index 7e12ff8..3990ae6 100644 --- a/src/jcgp/backend/resources/parameters/Parameter.java +++ b/src/jcgp/backend/resources/parameters/Parameter.java @@ -1,8 +1,9 @@ package jcgp.backend.resources.parameters; import javafx.beans.property.Property; +import javafx.beans.property.ReadOnlyProperty; -public abstract class Parameter { +public abstract class Parameter<T> { protected boolean monitor, critical, reset = false; @@ -10,6 +11,8 @@ public abstract class Parameter { protected String name; + protected Property<T> valueProperty; + public Parameter(String name, boolean monitor, boolean critical) { this.name = name; this.monitor = monitor; @@ -36,6 +39,19 @@ public abstract class Parameter { return status; } - public abstract Property<?> valueProperty(); - + public ReadOnlyProperty<T> valueProperty() { + return valueProperty; + } + + public T get() { + return valueProperty.getValue(); + } + + public void set(T newValue) { + if (!valueProperty.isBound()) { + valueProperty.setValue(newValue); + } + } + + public abstract void validate(T newValue); } diff --git a/src/jcgp/backend/tests/ChromosomeTests.java b/src/jcgp/backend/tests/ChromosomeTests.java index a16ba75..07326a7 100644 --- a/src/jcgp/backend/tests/ChromosomeTests.java +++ b/src/jcgp/backend/tests/ChromosomeTests.java @@ -2,6 +2,7 @@ package jcgp.backend.tests; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import jcgp.backend.function.IntegerArithmetic; import jcgp.backend.population.Chromosome; import jcgp.backend.population.Connection; import jcgp.backend.population.Input; @@ -45,6 +46,7 @@ public class ChromosomeTests { @BeforeClass public static void setUpBeforeClass() { resources = new ModifiableResources(); + resources.setFunctionSet(new IntegerArithmetic()); } @Before @@ -62,7 +64,7 @@ public class ChromosomeTests { // compare all elements, one by one // check outputs - for (int o = 0; o < resources.getInt("outputs"); o++) { + for (int o = 0; o < resources.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) && @@ -80,8 +82,8 @@ public class ChromosomeTests { } } // check nodes, rows first - for (int row = 0; row < resources.getInt("rows"); row++) { - for (int column = 0; column < resources.getInt("columns"); column++) { + for (int row = 0; row < resources.rows(); row++) { + for (int column = 0; column < resources.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 @@ -91,7 +93,7 @@ public class ChromosomeTests { 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++) { + for (int connection = 0; connection < resources.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)); @@ -130,12 +132,12 @@ public class ChromosomeTests { clone.setInputs((Object[]) testInputs); // check that both chromosomes have the same outputs - for (int i = 0; i < resources.getInt("outputs"); i++) { + for (int i = 0; i < resources.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)); + clone.getOutput(1).setConnection(resources.getRandomInt(resources.arity()), clone.getInput(2)); assertTrue("Mutation affected nodes in both chromosomes.", clone.getOutput(1).calculate() != chromosome.getOutput(1).calculate()); @@ -164,7 +166,7 @@ public class ChromosomeTests { // 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; + int chosenColumn = resources.columns() - 1; for (int i = 0; i < connectionPicks; i++) { Connection c = chromosome.getRandomConnection(chosenColumn); if (c instanceof Node) { @@ -180,10 +182,10 @@ public class ChromosomeTests { } } - 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("Out of " + connectionPicks + " connections picked from " + ((chosenColumn >= resources.levelsBack()) ? resources.levelsBack() : chosenColumn) * resources.rows() + + " allowed nodes and " + resources.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") + + System.out.println("Node/input ratio: " + (chosenColumn >= resources.levelsBack() ? resources.levelsBack() : chosenColumn) * (double) resources.rows() / (double) resources.inputs() + ", picked ratio: " + (double) connectionNodes / (double) connectionInputs); System.out.println(connectionOutOfRange + " nodes that disrespected levels back were picked."); @@ -207,10 +209,10 @@ public class ChromosomeTests { 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 " + + System.out.println("Out of " + mutablePicks + " mutable elements picked from " + resources.nodes() + + " nodes and " + resources.outputs() + " outputs, " + mutableNodes + " were nodes and " + mutableOutputs + " were outputs."); - System.out.println("Node/output ratio: " + resources.getDouble("nodes") / resources.getDouble("outputs") + + System.out.println("Node/output ratio: " + (double) resources.nodes() / (double) resources.outputs() + ", picked ratio: " + (double) mutableNodes / (double) mutableOutputs + "\n"); } @@ -234,12 +236,12 @@ public class ChromosomeTests { @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++) { + Integer[] testInputs = new Integer[resources.inputs()]; + for (int i = 0; i < resources.inputs(); i++) { testInputs[i] = i * 2 - 3; } chromosome.setInputs((Object[]) testInputs); - for (int i = 0; i < resources.getInt("inputs"); i++) { + for (int i = 0; i < resources.inputs(); i++) { assertTrue("Incorrect input returned.", ((Integer) chromosome.getInput(i).getValue()) == i * 2 - 3); } } @@ -250,8 +252,8 @@ public class ChromosomeTests { @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++) { + for (int r = 0; r < resources.rows(); r++) { + for (int c = 0; c < resources.columns(); c++) { assertTrue("Incorrect node returned.", chromosome.getNode(r, c).getColumn() == c && chromosome.getNode(r, c).getRow() == r); } @@ -271,7 +273,9 @@ public class ChromosomeTests { 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); + chromosome.printNodes(); + + assertTrue("List has the wrong number of nodes: " + chromosome.getActiveNodes(), chromosome.getActiveNodes().size() == 3); } /** @@ -314,11 +318,11 @@ public class ChromosomeTests { */ 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); + resources.setColumns(3); + resources.setRows(3); + resources.setInputs(3); + resources.setOutputs(2); + resources.setLevelsBack(3); Chromosome c = new Chromosome(resources); @@ -328,7 +332,7 @@ public class ChromosomeTests { 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/NodeTests.java b/src/jcgp/backend/tests/NodeTests.java index e8fe02f..0e08d92 100644 --- a/src/jcgp/backend/tests/NodeTests.java +++ b/src/jcgp/backend/tests/NodeTests.java @@ -7,7 +7,7 @@ import jcgp.backend.function.IntegerArithmetic; import jcgp.backend.population.Chromosome; import jcgp.backend.population.Connection; import jcgp.backend.population.Node; -import jcgp.backend.resources.Resources; +import jcgp.backend.resources.ModifiableResources; import org.junit.Before; import org.junit.BeforeClass; @@ -32,7 +32,7 @@ public class NodeTests { private Node node; private static Chromosome chromosome; - private static Resources resources; + private static ModifiableResources resources; // these numbers will be used by the node under test private final int arg1 = 2; private final int arg2 = 5; @@ -40,14 +40,14 @@ public class NodeTests { @BeforeClass public static void setUpBeforeClass() { - resources = new Resources(); - + resources = new ModifiableResources(); + resources.setFunctionSet(new IntegerArithmetic()); chromosome = new Chromosome(resources); } @Before public void setUp() throws Exception { - node = new Node(chromosome, 0, 0, resources.getInt("arity")); + node = new Node(chromosome, 0, 0, resources.arity()); // make node with anonymous addition function and hard-coded value connections node.initialise(new IntegerArithmetic.Addition(), new Connection[]{new Connection() { @@ -174,7 +174,7 @@ public class NodeTests { return 0; } }; - node.setConnection(resources.getRandomInt(resources.getInt("arity")), conn2); + node.setConnection(resources.getRandomInt(resources.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 index afe44a7..a331f2d 100644 --- a/src/jcgp/backend/tests/OutputTests.java +++ b/src/jcgp/backend/tests/OutputTests.java @@ -1,10 +1,11 @@ package jcgp.backend.tests; import static org.junit.Assert.assertTrue; +import jcgp.backend.function.IntegerArithmetic; import jcgp.backend.population.Chromosome; import jcgp.backend.population.Connection; import jcgp.backend.population.Output; -import jcgp.backend.resources.Resources; +import jcgp.backend.resources.ModifiableResources; import org.junit.Before; import org.junit.BeforeClass; @@ -26,14 +27,15 @@ public class OutputTests { private Output output; private static Chromosome chromosome; - private static Resources resources; + private static ModifiableResources resources; // these are the test values private final int outputValue = 10; private final int outputIndex = 2; @BeforeClass public static void setUpBeforeClass() { - resources = new Resources(); + resources = new ModifiableResources(); + resources.setFunctionSet(new IntegerArithmetic()); chromosome = new Chromosome(resources); } diff --git a/src/jcgp/backend/tests/PopulationTests.java b/src/jcgp/backend/tests/PopulationTests.java index 31df8b9..fb8ced4 100644 --- a/src/jcgp/backend/tests/PopulationTests.java +++ b/src/jcgp/backend/tests/PopulationTests.java @@ -1,9 +1,10 @@ package jcgp.backend.tests; import static org.junit.Assert.assertTrue; +import jcgp.backend.function.IntegerArithmetic; import jcgp.backend.population.Chromosome; import jcgp.backend.population.Population; -import jcgp.backend.resources.Resources; +import jcgp.backend.resources.ModifiableResources; import org.junit.Before; import org.junit.BeforeClass; @@ -26,30 +27,12 @@ import org.junit.Test; public class PopulationTests { private Population population; - private static Resources resources; + private static ModifiableResources 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()); + resources = new ModifiableResources(); + resources.setFunctionSet(new IntegerArithmetic()); } @Before @@ -70,7 +53,7 @@ public class PopulationTests { chromosomes++; } - assertTrue("Incorrect number of chromosomes generated.", chromosomes == resources.getInt("popSize")); + assertTrue("Incorrect number of chromosomes generated.", chromosomes == resources.populationSize()); } @Test diff --git a/src/jcgp/gui/GUI.java b/src/jcgp/gui/GUI.java index eaca077..5a7a16d 100644 --- a/src/jcgp/gui/GUI.java +++ b/src/jcgp/gui/GUI.java @@ -46,11 +46,11 @@ public class GUI extends Application { private PopulationPane populationPane; - private GUIConsole console = new GUIConsole(); + private GUIConsole console; private SettingsPane settingsPane; - private boolean evolving = false; + private static boolean working = false; private Object printLock = new Object(); @@ -93,16 +93,13 @@ public class GUI extends Application { }; public static void main(String[] args) { -// jcgp = new JCGP(); -// resources = jcgp.getResources(); -// -// functionSelector = launch(); } @Override public void start(Stage primaryStage) throws Exception { + console = new GUIConsole(); jcgp.setConsole(console); /* @@ -142,7 +139,7 @@ public class GUI extends Application { public void runPause() { if (!jcgp.isFinished() && settingsPane.areParametersValid()) { - if (!evolving) { + if (!working) { runningMode(true); cgpService.restart(); } else { @@ -153,7 +150,7 @@ public class GUI extends Application { } public void step() { - if (!evolving && !jcgp.isFinished() && settingsPane.areParametersValid()) { + if (!working && !jcgp.isFinished() && settingsPane.areParametersValid()) { if (settingsPane.isResetRequired()) { reset(); } @@ -164,12 +161,12 @@ public class GUI extends Application { populationPane.updateGenes(); populationPane.relockOutputs(); - + settingsPane.revalidateParameters(); } } public void reset() { - if (!evolving && settingsPane.areParametersValid()) { + if (!working && settingsPane.areParametersValid()) { settingsPane.applyParameters(); jcgp.reset(); populationPane.remakeTabs(jcgp.getPopulation(), jcgp.getResources()); @@ -182,7 +179,7 @@ public class GUI extends Application { private void runningMode(boolean value) { populationPane.setDisable(value); settingsPane.updateControls(value, jcgp.isFinished()); - + if (value) { populationPane.unlockOutputs(); if (settingsPane.isResetRequired()) { @@ -191,12 +188,16 @@ public class GUI extends Application { } else { populationPane.updateGenes(); populationPane.relockOutputs(); + settingsPane.revalidateParameters(); } - evolving = value; + working = value; } public static void updateFunctionSelector() { functionSelector.remakeFunctions(resources.getFunctionSet()); } + public static boolean isWorking() { + return working; + } } diff --git a/src/jcgp/gui/console/GUIConsole.java b/src/jcgp/gui/console/GUIConsole.java index 55291aa..8148ec8 100644 --- a/src/jcgp/gui/console/GUIConsole.java +++ b/src/jcgp/gui/console/GUIConsole.java @@ -1,6 +1,16 @@ package jcgp.gui.console; +import javafx.event.ActionEvent; +import javafx.event.Event; +import javafx.event.EventDispatchChain; +import javafx.event.EventDispatcher; +import javafx.event.EventHandler; +import javafx.scene.control.ContextMenu; +import javafx.scene.control.MenuItem; +import javafx.scene.control.SeparatorMenuItem; import javafx.scene.control.TextArea; +import javafx.scene.input.MouseButton; +import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import jcgp.backend.resources.Console; import jcgp.gui.GUI; @@ -15,6 +25,58 @@ public class GUIConsole extends AnchorPane implements Console { super(); textArea.setEditable(false); + /* + * This nasty hack is needed because the default TextArea ContextMenu is not + * in the public API, making it impossible to override it with a custom one. + * This has not been fixed as of 8/4/2014. + * + * The following code modifies the EventDispatcher to consume the right mouse + * button click, preventing the default menu from appearing. + */ + final EventDispatcher initial = textArea.getEventDispatcher(); + textArea.setEventDispatcher(new EventDispatcher() { + @Override + public Event dispatchEvent(Event event, EventDispatchChain tail) { + if (event instanceof MouseEvent) { + //shot in the dark guess for OSX, might not work + MouseEvent mouseEvent = (MouseEvent)event; + if (mouseEvent.getButton() == MouseButton.SECONDARY || + (mouseEvent.getButton() == MouseButton.PRIMARY && mouseEvent.isControlDown())) { + event.consume(); + } + } + return initial.dispatchEvent(event, tail); + } + }); + + // make the new context menu including the clear option + MenuItem copySelected = new MenuItem("Copy"); + copySelected.setOnAction(new EventHandler<ActionEvent>() { + @Override + public void handle(ActionEvent event) { + textArea.copy(); + } + }); + MenuItem selectAll = new MenuItem("Select all"); + selectAll.setOnAction(new EventHandler<ActionEvent>() { + @Override + public void handle(ActionEvent event) { + textArea.selectAll(); + } + }); + MenuItem clearConsole = new MenuItem("Clear"); + clearConsole.setOnAction(new EventHandler<ActionEvent>() { + @Override + public void handle(ActionEvent event) { + textArea.setText(""); + } + }); + + textArea.setContextMenu(new ContextMenu(copySelected, + selectAll, + new SeparatorMenuItem(), + clearConsole)); + AnchorPane.setTopAnchor(textArea, GUI.RESIZE_MARGIN); AnchorPane.setBottomAnchor(textArea, 0.0); AnchorPane.setRightAnchor(textArea, 0.0); diff --git a/src/jcgp/gui/population/ChromosomePane.java b/src/jcgp/gui/population/ChromosomePane.java index 841c18a..1f67255 100644 --- a/src/jcgp/gui/population/ChromosomePane.java +++ b/src/jcgp/gui/population/ChromosomePane.java @@ -35,19 +35,19 @@ public class ChromosomePane extends ScrollPane { // generate the GUIGenes // inputs - guiInputs = new GUIInput[resources.getInt("inputs")]; + guiInputs = new GUIInput[resources.inputs()]; for (int i = 0; i < guiInputs.length; i++) { // make the GUI elements guiInputs[i] = new GUIInput(this, chromosome.getInput(i)); content.getChildren().addAll(guiInputs[i]); } // nodes - guiNodes = new GUINode[resources.getInt("rows")][resources.getInt("columns")]; + guiNodes = new GUINode[resources.rows()][resources.columns()]; double angle, xPos, yPos; for (int r = 0; r < guiNodes.length; r++) { for (int c = 0; c < guiNodes[r].length; c++) { // make the connection lines - Line lines[] = new Line[resources.getInt("arity")]; + Line lines[] = new Line[resources.arity()]; for (int l = 0; l < lines.length; l++) { angle = ((((double) (l + 1)) / ((double) (lines.length + 1))) * GUIGene.THETA) - (GUIGene.THETA / 2); xPos = (-Math.cos(angle) * GUIGene.NODE_RADIUS) + (((c + 1) * (2 * GUIGene.NODE_RADIUS + GUIGene.SPACING)) + GUIGene.NODE_RADIUS); @@ -64,9 +64,9 @@ public class ChromosomePane extends ScrollPane { content.getChildren().addAll(guiNodes[r]); } // outputs - guiOutputs = new GUIOutput[resources.getInt("outputs")]; + guiOutputs = new GUIOutput[resources.outputs()]; for (int i = 0; i < guiOutputs.length; i++) { - xPos = ((resources.getInt("columns") + 1) * (2 * GUIGene.NODE_RADIUS + GUIGene.SPACING)); + xPos = ((resources.columns() + 1) * (2 * GUIGene.NODE_RADIUS + GUIGene.SPACING)); yPos = (chromosome.getOutput(i).getIndex() * (2 * GUIGene.NODE_RADIUS + GUIGene.SPACING)) + GUIGene.NODE_RADIUS; // make the line Line line = new Line(xPos, yPos, xPos, yPos); diff --git a/src/jcgp/gui/population/GUINode.java b/src/jcgp/gui/population/GUINode.java index 98ba738..8e2d8a0 100644 --- a/src/jcgp/gui/population/GUINode.java +++ b/src/jcgp/gui/population/GUINode.java @@ -42,10 +42,10 @@ public class GUINode extends GUIGene { text.setText(node.getFunction().getName()); - Circle[] sockets = new Circle[GUI.resources.getInt("arity")]; + Circle[] sockets = new Circle[GUI.resources.arity()]; double angle, xPos, yPos; for (int l = 0; l < sockets.length; l++) { - angle = (((l + 1) / ((GUI.resources.getDouble("arity") + 1))) * THETA) - (THETA / 2); + angle = (((l + 1) / ((double) (GUI.resources.arity() + 1))) * THETA) - (THETA / 2); xPos = -Math.cos(angle) * NODE_RADIUS; yPos = Math.sin(angle) * NODE_RADIUS; @@ -316,7 +316,7 @@ public class GUINode extends GUIGene { } else if (target instanceof GUINode) { // target and source are nodes, let's look at levels back Node t = ((GUINode) target).getGene(), s = ((GUINode) source).getGene(); - if (s.getColumn() - t.getColumn() > 0 && s.getColumn() - t.getColumn() <= GUI.resources.getInt("levelsBack")) { + if (s.getColumn() - t.getColumn() > 0 && s.getColumn() - t.getColumn() <= GUI.resources.levelsBack()) { return true; } return false; diff --git a/src/jcgp/gui/population/GUIOutput.java b/src/jcgp/gui/population/GUIOutput.java index 4a12385..c5b889e 100644 --- a/src/jcgp/gui/population/GUIOutput.java +++ b/src/jcgp/gui/population/GUIOutput.java @@ -26,7 +26,7 @@ public class GUIOutput extends GUIGene { this.output = output; this.sourceLine = line; - relocate(((GUI.resources.getInt("columns") + 1) * (2 * NODE_RADIUS + SPACING)) + NODE_RADIUS, + relocate(((GUI.resources.columns() + 1) * (2 * NODE_RADIUS + SPACING)) + NODE_RADIUS, (output.getIndex() * (2 * NODE_RADIUS + SPACING)) + NODE_RADIUS); // set the line ends correctly diff --git a/src/jcgp/gui/population/PopulationPane.java b/src/jcgp/gui/population/PopulationPane.java index 3a83a86..5232eb5 100644 --- a/src/jcgp/gui/population/PopulationPane.java +++ b/src/jcgp/gui/population/PopulationPane.java @@ -21,7 +21,7 @@ public class PopulationPane extends TabPane { Tab tab; ChromosomePane cp; - for (int i = 0; i < resources.getInt("popSize"); i++) { + for (int i = 0; i < resources.populationSize(); i++) { cp = new ChromosomePane(population.getChromosome(i), resources); tab = new Tab("Chr " + i); tab.setContent(cp); diff --git a/src/jcgp/gui/settings/SettingsPane.java b/src/jcgp/gui/settings/SettingsPane.java index d7ffd79..e455846 100644 --- a/src/jcgp/gui/settings/SettingsPane.java +++ b/src/jcgp/gui/settings/SettingsPane.java @@ -30,8 +30,9 @@ public class SettingsPane extends AnchorPane { private VBox baseParameterPane, eaPane, mutatorPane, problemPane; private Button runPause = new Button("Run"), step = new Button("Step"), reset = new Button("Reset"); + private Button loadParameters = new Button("Load parameters"), loadChromosome = new Button("Load chromosome"), saveChromosome = new Button("Save chromosome"); - private ArrayList<GUIParameter> parameters = new ArrayList<GUIParameter>(); + private ArrayList<GUIParameter<?>> parameters = new ArrayList<GUIParameter<?>>(); public SettingsPane(JCGP cgp, GUI gui) { super(); @@ -50,7 +51,7 @@ public class SettingsPane extends AnchorPane { initialiseProblemTypeParameters(cgp, gui); - createControls(cgp, gui); + createControls(gui); ScrollPane scroll = new ScrollPane(); scroll.setFitToWidth(true); @@ -74,27 +75,26 @@ public class SettingsPane extends AnchorPane { baseParameterPane.getChildren().add(header); - parameters.add(GUIParameter.create(cgp.getResources().getParameter("rows"), this)); - parameters.add(GUIParameter.create(cgp.getResources().getParameter("columns"), this)); - parameters.add(GUIParameter.create(cgp.getResources().getParameter("inputs"), this)); - parameters.add(GUIParameter.create(cgp.getResources().getParameter("outputs"), this)); - parameters.add(GUIParameter.create(cgp.getResources().getParameter("levelsBack"), this)); + parameters.add(GUIParameter.create(cgp.getResources().getRowsParameter(), this)); + parameters.add(GUIParameter.create(cgp.getResources().getColumnsParameter(), this)); + parameters.add(GUIParameter.create(cgp.getResources().getInputsParameter(), this)); + parameters.add(GUIParameter.create(cgp.getResources().getOutputsParameter(), this)); + parameters.add(GUIParameter.create(cgp.getResources().getLevelsBackParameter(), this)); - GUIParameter gp = GUIParameter.create(cgp.getResources().getParameter("popSize"), this); + GUIParameter<?> gp = GUIParameter.create(cgp.getResources().getPopulationSizeParameter(), this); gp.setPadding(new Insets(0, 0, 10, 0)); parameters.add(gp); - parameters.add(GUIParameter.create(cgp.getResources().getParameter("currentGen"), this)); - parameters.add(GUIParameter.create(cgp.getResources().getParameter("generations"), this)); - parameters.add(GUIParameter.create(cgp.getResources().getParameter("currentRun"), this)); + parameters.add(GUIParameter.create(cgp.getResources().getCurrentGenerationParameter(), this)); + parameters.add(GUIParameter.create(cgp.getResources().getGenerationsParameter(), this)); + parameters.add(GUIParameter.create(cgp.getResources().getCurrentRunParameter(), this)); - gp = GUIParameter.create(cgp.getResources().getParameter("runs"), this); + gp = GUIParameter.create(cgp.getResources().getRunsParameter(), this); gp.setPadding(new Insets(0, 0, 10, 0)); parameters.add(gp); - parameters.add(GUIParameter.create(cgp.getResources().getParameter("seed"), this)); - parameters.add(GUIParameter.create(cgp.getResources().getParameter("report"), this)); - //parameters.add(GUIParameter.create(cgp.getResources().getParameter("maxFitness"), this)); + parameters.add(GUIParameter.create(cgp.getResources().getSeedParameter(), this)); + parameters.add(GUIParameter.create(cgp.getResources().getReportParameter(), this)); baseParameterPane.getChildren().addAll(parameters); mainContainer.getChildren().add(baseParameterPane); @@ -204,7 +204,7 @@ public class SettingsPane extends AnchorPane { } - private void createControls(final JCGP cgp, final GUI gui) { + private void createControls(final GUI gui) { Text header = new Text("Experiment controls"); header.setFont(Font.font("Arial", 14)); header.setUnderline(true); @@ -220,7 +220,6 @@ public class SettingsPane extends AnchorPane { } }); - step = new Button("Step"); step.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { @@ -228,7 +227,6 @@ public class SettingsPane extends AnchorPane { } }); - reset = new Button("Reset"); reset.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { @@ -236,8 +234,6 @@ public class SettingsPane extends AnchorPane { } }); - flowButtons.getChildren().addAll(runPause, step, reset); - HBox.setHgrow(runPause, Priority.ALWAYS); runPause.setMaxWidth(Double.MAX_VALUE); HBox.setHgrow(step, Priority.ALWAYS); @@ -245,7 +241,37 @@ public class SettingsPane extends AnchorPane { HBox.setHgrow(reset, Priority.ALWAYS); reset.setMaxWidth(Double.MAX_VALUE); - controls.getChildren().addAll(header, flowButtons); + flowButtons.getChildren().addAll(runPause, step, reset); + flowButtons.setPadding(new Insets(0, 0, 10, 0)); + + loadParameters.setOnAction(new EventHandler<ActionEvent>() { + @Override + public void handle(ActionEvent event) { + //gui.runPause(); + } + }); + + loadChromosome.setOnAction(new EventHandler<ActionEvent>() { + @Override + public void handle(ActionEvent event) { + //gui.step(); + } + }); + saveChromosome.setOnAction(new EventHandler<ActionEvent>() { + @Override + public void handle(ActionEvent event) { + //gui.step(); + } + }); + + HBox.setHgrow(loadParameters, Priority.ALWAYS); + loadParameters.setMaxWidth(Double.MAX_VALUE); + HBox.setHgrow(loadChromosome, Priority.ALWAYS); + loadChromosome.setMaxWidth(Double.MAX_VALUE); + HBox.setHgrow(saveChromosome, Priority.ALWAYS); + saveChromosome.setMaxWidth(Double.MAX_VALUE); + + controls.getChildren().addAll(header, flowButtons, loadParameters, loadChromosome, saveChromosome); mainContainer.getChildren().add(controls); } @@ -254,11 +280,11 @@ public class SettingsPane extends AnchorPane { * @param cgp * @param vb */ - private void refreshParameters(Parameter[] newParameters, VBox vb) { + private void refreshParameters(Parameter<?>[] newParameters, VBox vb) { parameters.removeAll(vb.getChildren()); vb.getChildren().clear(); for (int i = 0; i < newParameters.length; i++) { - GUIParameter gp = GUIParameter.create(newParameters[i], this); + GUIParameter<?> gp = GUIParameter.create(newParameters[i], this); parameters.add(gp); vb.getChildren().add(gp); } @@ -290,25 +316,12 @@ public class SettingsPane extends AnchorPane { } } - - -// public void runningMode(boolean value) { -// baseParameterPane.setDisable(value); -// eaPane.setDisable(value); -// mutatorPane.setDisable(value); -// problemPane.setDisable(value); -// step.setDisable(value); -// reset.setDisable(value); -// -// runPause.setText(value ? "Pause" : "Run"); -// } -// /** * * @return true if the experiment needs to be reset, false otherwise. */ public boolean isResetRequired() { - for (GUIParameter parameter : parameters) { + for (GUIParameter<?> parameter : parameters) { if (parameter.requiresReset()) { return true; } @@ -317,7 +330,7 @@ public class SettingsPane extends AnchorPane { } public boolean areParametersValid() { - for (GUIParameter parameter : parameters) { + for (GUIParameter<?> parameter : parameters) { if (!parameter.isValid()) { return false; } @@ -327,7 +340,7 @@ public class SettingsPane extends AnchorPane { public void revalidateParameters() { runPause.setDisable(false); - for (GUIParameter parameter : parameters) { + for (GUIParameter<?> parameter : parameters) { parameter.validate(); if (parameter.requiresReset()) { runPause.setDisable(true); @@ -336,7 +349,7 @@ public class SettingsPane extends AnchorPane { } public void applyParameters() { - for (GUIParameter parameter : parameters) { + for (GUIParameter<?> parameter : parameters) { parameter.applyValue(); } } @@ -351,6 +364,5 @@ public class SettingsPane extends AnchorPane { runPause.setDisable(finished); step.setDisable(running || finished); reset.setDisable(running); - } } diff --git a/src/jcgp/gui/settings/parameters/GUIBooleanParameter.java b/src/jcgp/gui/settings/parameters/GUIBooleanParameter.java index 4339562..bada5d4 100644 --- a/src/jcgp/gui/settings/parameters/GUIBooleanParameter.java +++ b/src/jcgp/gui/settings/parameters/GUIBooleanParameter.java @@ -3,83 +3,79 @@ package jcgp.gui.settings.parameters; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.scene.control.CheckBox; +import javafx.scene.control.Control; import jcgp.backend.resources.parameters.BooleanParameter; import jcgp.backend.resources.parameters.ParameterStatus; +import jcgp.gui.GUI; import jcgp.gui.settings.SettingsPane; -public class GUIBooleanParameter extends GUIParameter { - - private boolean originalValue; +/** + * This extension of GUIParameter uses a CheckBox to display + * the value of a BooleanParameter. It cannot be constructed + * directly - instead, use GUIParameter.create(). + * <br><br> + * See {@link GUIParameter} for more information. + * + * @author Eduardo Pedroni + */ +public class GUIBooleanParameter extends GUIParameter<Boolean> { + + private CheckBox checkBox; + /** + * This default-visibility constructor is intended for use + * by the factory method only. + * + */ GUIBooleanParameter(final BooleanParameter parameter, final SettingsPane sp) { - super(); - - this.parameter = parameter; - - originalValue = parameter.get(); - - valueControl = new CheckBox(parameter.getName()); - ((CheckBox) valueControl).setSelected(parameter.get()); - - valueControl.setDisable(parameter.isMonitor()); - - if (parameter.isMonitor()) { - makeLightBinding(); - } else { - ((CheckBox) valueControl).selectedProperty().addListener(new ChangeListener<Boolean>() { - @Override - public void changed( - ObservableValue<? extends Boolean> observable, - Boolean oldValue, Boolean newValue) { - parameter.set(newValue); - setValidityStyle(); - sp.revalidateParameters(); - } - }); - } - - getChildren().add(valueControl); - } - - @Override - public void refreshValue() { - if (!((CheckBox) valueControl).selectedProperty().isBound()) { - ((CheckBox) valueControl).setSelected(((BooleanParameter) parameter).get()); - } + super(parameter, sp); } @Override - public boolean requiresReset() { - return (parameter.isCritical() && ((BooleanParameter) parameter).get() != originalValue) - || parameter.getStatus() == ParameterStatus.WARNING_RESET; + protected Control makeControl() { + checkBox = new CheckBox(); + checkBox.setSelected(parameter.get()); + + return checkBox; } @Override - public void applyValue() { - originalValue = ((BooleanParameter) parameter).get(); + protected void setControlListeners(final SettingsPane sp) { + /* pass the CheckBox value back to the parameter whenever it gets + * modified, provided the experiment isn't running */ + checkBox.selectedProperty().addListener(new ChangeListener<Boolean>() { + @Override + public void changed( + ObservableValue<? extends Boolean> observable, + Boolean oldValue, Boolean newValue) { + if (!GUI.isWorking()) { + parameter.set(newValue); + sp.revalidateParameters(); + } + } + }); } - /** - * @param parameter - */ - private void setValidityStyle() { + @Override + protected void setValidityStyle() { + // update the Control's style and tooltip based on the status of the parameter if (parameter.getStatus() == ParameterStatus.INVALID) { - valueControl.setStyle(BASE_CHECKBOX_STYLE + INVALID_PARAMETER_STYLE); - valueControl.setTooltip(tooltip); + checkBox.setStyle(BASE_CHECKBOX_STYLE + INVALID_PARAMETER_STYLE); + checkBox.setTooltip(tooltip); tooltip.setText(parameter.getStatus().getDetails()); } else if (parameter.getStatus() == ParameterStatus.WARNING || parameter.getStatus() == ParameterStatus.WARNING_RESET) { - valueControl.setStyle(BASE_CHECKBOX_STYLE + WARNING_PARAMETER_STYLE); - valueControl.setTooltip(tooltip); + checkBox.setStyle(BASE_CHECKBOX_STYLE + WARNING_PARAMETER_STYLE); + checkBox.setTooltip(tooltip); tooltip.setText(parameter.getStatus().getDetails()); } else { - valueControl.setStyle(BASE_CHECKBOX_STYLE + VALID_PARAMETER_STYLE); - valueControl.setTooltip(null); + checkBox.setStyle(BASE_CHECKBOX_STYLE + VALID_PARAMETER_STYLE); + checkBox.setTooltip(null); } } @Override - public void validate() { - ((BooleanParameter) parameter).validate(((BooleanParameter) parameter).get()); - setValidityStyle(); + public void refreshValue() { + checkBox.setSelected(parameter.get()); } + } diff --git a/src/jcgp/gui/settings/parameters/GUIDoubleParameter.java b/src/jcgp/gui/settings/parameters/GUIDoubleParameter.java index 4a8e0e1..87e7b69 100644 --- a/src/jcgp/gui/settings/parameters/GUIDoubleParameter.java +++ b/src/jcgp/gui/settings/parameters/GUIDoubleParameter.java @@ -4,115 +4,105 @@ import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.EventHandler; import javafx.geometry.Pos; +import javafx.scene.control.Control; import javafx.scene.control.TextField; import javafx.scene.input.KeyEvent; -import javafx.scene.layout.Priority; -import javafx.scene.text.Text; -import jcgp.backend.resources.parameters.DoubleParameter; +import jcgp.backend.resources.parameters.Parameter; import jcgp.backend.resources.parameters.ParameterStatus; +import jcgp.gui.GUI; import jcgp.gui.settings.SettingsPane; -public class GUIDoubleParameter extends GUIParameter { +/** + * This extension of GUIParameter uses a TextField to display + * the value of a DoubleParameter. It cannot be constructed + * directly - instead, use GUIParameter.create(). + * <br><br> + * See {@link GUIParameter} for more information. + * + * @author Eduardo Pedroni + */ +public class GUIDoubleParameter extends GUIParameter<Number> { + + private TextField textField; - private double originalValue; + /** + * This default-visibility constructor is intended for use + * by the factory method only. + * + */ + GUIDoubleParameter(Parameter<Number> parameter, SettingsPane sp) { + super(parameter, sp); + } - GUIDoubleParameter(final DoubleParameter parameter, final SettingsPane sp) { - super(); - - this.parameter = parameter; - - originalValue = parameter.get(); - - name = new Text(parameter.getName()); - valueControl = new TextField(String.valueOf(parameter.get())); - valueControl.setStyle(VALID_PARAMETER_STYLE); - - ((TextField) valueControl).setAlignment(Pos.CENTER_RIGHT); - - setHgrow(valueControl, Priority.ALWAYS); - setHgrow(name, Priority.ALWAYS); - - name.wrappingWidthProperty().bind(widthProperty().divide(2)); - - ((TextField) valueControl).setDisable(parameter.isMonitor()); + @Override + protected Control makeControl() { + textField = new TextField(String.valueOf(parameter.get())); + textField.setStyle(VALID_PARAMETER_STYLE); + textField.setAlignment(Pos.CENTER_RIGHT); - // bind if monitor, else set changelistener - if (parameter.isMonitor()) { - makeLightBinding(); - } else { - valueControl.addEventFilter(KeyEvent.KEY_TYPED, new EventHandler<KeyEvent>() { - @Override - public void handle( KeyEvent t ) { - char ch = t.getCharacter().toCharArray()[t.getCharacter().toCharArray().length - 1]; - if (!((ch >= '0' && ch <= '9') || (ch == '.' && !((TextField) valueControl).getText().contains(".")))) { - t.consume(); - } - } - }); - ((TextField) valueControl).textProperty().addListener(new ChangeListener<String>() { - @Override - public void changed( - ObservableValue<? extends String> observable, - String oldValue, String newValue) { - if (!newValue.isEmpty()) { - parameter.set(Double.parseDouble(newValue)); - setValidityStyle(); - sp.revalidateParameters(); - } + return textField; + } + @Override + protected void setControlListeners(final SettingsPane sp) { + /* filter keypresses and ignore anything that is not a number + * and any decimal point beyond the first ones */ + textField.addEventFilter(KeyEvent.KEY_TYPED, new EventHandler<KeyEvent>() { + @Override + public void handle( KeyEvent t ) { + char ch = t.getCharacter().toCharArray()[t.getCharacter().toCharArray().length - 1]; + if (!((ch >= '0' && ch <= '9') || (ch == '.' && !textField.getText().contains(".")))) { + t.consume(); } - }); - valueControl.focusedProperty().addListener(new ChangeListener<Boolean>() { - @Override - public void changed( - ObservableValue<? extends Boolean> observable, - Boolean oldValue, Boolean newValue) { - if (!newValue && ((TextField) valueControl).getText().isEmpty()) { - ((TextField) valueControl).setText(String.valueOf(parameter.get())); - } + } + }); + /* pass the TextField value back to the parameter whenever it gets + * modified, provided it is not empty and the experiment isn't running */ + textField.textProperty().addListener(new ChangeListener<String>() { + @Override + public void changed( + ObservableValue<? extends String> observable, + String oldValue, String newValue) { + if (!newValue.isEmpty() && !GUI.isWorking()) { + parameter.set(Double.parseDouble(newValue)); + sp.revalidateParameters(); } - }); - } - - - getChildren().addAll(name, valueControl); - } - @Override - public void refreshValue() { - ((TextField) valueControl).setText(String.valueOf(((DoubleParameter) parameter).get())); - } - - @Override - public boolean requiresReset() { - return (parameter.isCritical() && ((DoubleParameter) parameter).get() != originalValue) - || parameter.getStatus() == ParameterStatus.WARNING_RESET; - } - - @Override - public void applyValue() { - originalValue = ((DoubleParameter) parameter).get(); + } + }); + /* if the TextField loses focus and is empty, set it to the current + * value of the parameter */ + textField.focusedProperty().addListener(new ChangeListener<Boolean>() { + @Override + public void changed( + ObservableValue<? extends Boolean> observable, + Boolean oldValue, Boolean newValue) { + if (!newValue && textField.getText().isEmpty()) { + textField.setText(String.valueOf(parameter.get())); + } + } + }); } @Override - public void validate() { - ((DoubleParameter) parameter).validate(((DoubleParameter) parameter).get()); - setValidityStyle(); - } - - private void setValidityStyle() { + protected void setValidityStyle() { + // update the Control's style and tooltip based on the status of the parameter if (parameter.getStatus() == ParameterStatus.INVALID) { - valueControl.setStyle(BASE_TEXT_STYLE + INVALID_PARAMETER_STYLE); - valueControl.setTooltip(tooltip); + textField.setStyle(BASE_TEXT_STYLE + INVALID_PARAMETER_STYLE); + textField.setTooltip(tooltip); tooltip.setText(parameter.getStatus().getDetails()); } else if (parameter.getStatus() == ParameterStatus.WARNING || parameter.getStatus() == ParameterStatus.WARNING_RESET) { - valueControl.setStyle(BASE_TEXT_STYLE + WARNING_PARAMETER_STYLE); - valueControl.setTooltip(tooltip); + textField.setStyle(BASE_TEXT_STYLE + WARNING_PARAMETER_STYLE); + textField.setTooltip(tooltip); tooltip.setText(parameter.getStatus().getDetails()); } else { - valueControl.setStyle(BASE_TEXT_STYLE + VALID_PARAMETER_STYLE); - valueControl.setTooltip(null); + textField.setStyle(BASE_TEXT_STYLE + VALID_PARAMETER_STYLE); + textField.setTooltip(null); } } - + + @Override + public void refreshValue() { + textField.setText(String.valueOf((parameter).get())); + } } diff --git a/src/jcgp/gui/settings/parameters/GUIIntegerParameter.java b/src/jcgp/gui/settings/parameters/GUIIntegerParameter.java index 204e7a2..6927f26 100644 --- a/src/jcgp/gui/settings/parameters/GUIIntegerParameter.java +++ b/src/jcgp/gui/settings/parameters/GUIIntegerParameter.java @@ -4,115 +4,104 @@ import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.EventHandler; import javafx.geometry.Pos; +import javafx.scene.control.Control; import javafx.scene.control.TextField; import javafx.scene.input.KeyEvent; -import javafx.scene.layout.Priority; -import javafx.scene.text.Text; -import jcgp.backend.resources.parameters.IntegerParameter; +import jcgp.backend.resources.parameters.Parameter; import jcgp.backend.resources.parameters.ParameterStatus; +import jcgp.gui.GUI; import jcgp.gui.settings.SettingsPane; -public class GUIIntegerParameter extends GUIParameter { - - private int originalValue; +/** + * This extension of GUIParameter uses a TextField to display + * the value of a IntegerParameter. It cannot be constructed + * directly - instead, use GUIParameter.create(). + * <br><br> + * See {@link GUIParameter} for more information. + * + * @author Eduardo Pedroni + */ +public class GUIIntegerParameter extends GUIParameter<Number> { - GUIIntegerParameter(final IntegerParameter parameter, final SettingsPane sp) { - super(); - - this.parameter = parameter; - - originalValue = parameter.get(); - - name = new Text(parameter.getName()); - valueControl = new TextField(String.valueOf(parameter.get())); - valueControl.setStyle(VALID_PARAMETER_STYLE); - - ((TextField) valueControl).setAlignment(Pos.CENTER_RIGHT); - - setHgrow(valueControl, Priority.ALWAYS); - setHgrow(name, Priority.ALWAYS); - - name.wrappingWidthProperty().bind(widthProperty().divide(2)); - - ((TextField) valueControl).setDisable(parameter.isMonitor()); - - // bind if monitor, else set listeners - if (parameter.isMonitor()) { - makeLightBinding(); - } else { - valueControl.addEventFilter(KeyEvent.KEY_TYPED, new EventHandler<KeyEvent>() { - @Override - public void handle( KeyEvent t ) { - char ch = t.getCharacter().toCharArray()[t.getCharacter().toCharArray().length - 1]; - if (!(ch >= '0' && ch <= '9')) { - t.consume(); - } - } - }); - ((TextField) valueControl).textProperty().addListener(new ChangeListener<String>() { - @Override - public void changed( - ObservableValue<? extends String> observable, - String oldValue, String newValue) { - if (!newValue.isEmpty()) { - parameter.set(Integer.parseInt(newValue)); - setValidityStyle(); - sp.revalidateParameters(); - } - - } - }); - valueControl.focusedProperty().addListener(new ChangeListener<Boolean>() { - @Override - public void changed( - ObservableValue<? extends Boolean> observable, - Boolean oldValue, Boolean newValue) { - if (!newValue && ((TextField) valueControl).getText().isEmpty()) { - ((TextField) valueControl).setText(String.valueOf(parameter.get())); - } - } - }); - } - - getChildren().addAll(name, valueControl); + private TextField textField; + + /** + * This default-visibility constructor is intended for use + * by the factory method only. + * + */ + GUIIntegerParameter(Parameter<Number> parameter, SettingsPane sp) { + super(parameter, sp); } @Override - public void refreshValue() { - ((TextField) valueControl).setText(String.valueOf(((IntegerParameter) parameter).get())); + protected Control makeControl() { + textField = new TextField(String.valueOf(parameter.get())); + textField.setStyle(VALID_PARAMETER_STYLE); + textField.setAlignment(Pos.CENTER_RIGHT); + + return textField; } @Override - public boolean requiresReset() { - // true if critical and the value has changed, or it requires a reset anyway - return (parameter.isCritical() && ((IntegerParameter) parameter).get() != originalValue) - || parameter.getStatus() == ParameterStatus.WARNING_RESET; + protected void setControlListeners(final SettingsPane settingsPane) { + /* filter keypresses and ignore anything that is not a number */ + textField.addEventFilter(KeyEvent.KEY_TYPED, new EventHandler<KeyEvent>() { + @Override + public void handle( KeyEvent t ) { + char ch = t.getCharacter().toCharArray()[t.getCharacter().toCharArray().length - 1]; + if (!(ch >= '0' && ch <= '9')) { + t.consume(); + } + } + }); + /* pass the TextField value back to the parameter whenever it gets + * modified, provided it is not empty and the experiment isn't running */ + textField.textProperty().addListener(new ChangeListener<String>() { + @Override + public void changed( + ObservableValue<? extends String> observable, + String oldValue, String newValue) { + if (!newValue.isEmpty() && !GUI.isWorking()) { + parameter.set(Double.parseDouble(newValue)); + settingsPane.revalidateParameters(); + } + } + }); + /* if the TextField loses focus and is empty, set it to the current + * value of the parameter */ + textField.focusedProperty().addListener(new ChangeListener<Boolean>() { + @Override + public void changed( + ObservableValue<? extends Boolean> observable, + Boolean oldValue, Boolean newValue) { + if (!newValue && textField.getText().isEmpty()) { + textField.setText(String.valueOf(parameter.get())); + } + } + }); } @Override - public void applyValue() { - originalValue = ((IntegerParameter) parameter).get(); - } - - @Override - public void validate() { - ((IntegerParameter) parameter).validate(((IntegerParameter) parameter).get()); - setValidityStyle(); - } - - private void setValidityStyle() { + protected void setValidityStyle() { + // update the Control's style and tooltip based on the status of the parameter if (parameter.getStatus() == ParameterStatus.INVALID) { - valueControl.setStyle(BASE_TEXT_STYLE + INVALID_PARAMETER_STYLE); - valueControl.setTooltip(tooltip); + textField.setStyle(BASE_TEXT_STYLE + INVALID_PARAMETER_STYLE); + textField.setTooltip(tooltip); tooltip.setText(parameter.getStatus().getDetails()); - } else if (parameter.getStatus() == ParameterStatus.WARNING || parameter.getStatus() == ParameterStatus.WARNING_RESET) { - valueControl.setStyle(BASE_TEXT_STYLE + WARNING_PARAMETER_STYLE); - valueControl.setTooltip(tooltip); + } else if (parameter.getStatus() == ParameterStatus.WARNING + || parameter.getStatus() == ParameterStatus.WARNING_RESET) { + textField.setStyle(BASE_TEXT_STYLE + WARNING_PARAMETER_STYLE); + textField.setTooltip(tooltip); tooltip.setText(parameter.getStatus().getDetails()); } else { - valueControl.setStyle(BASE_TEXT_STYLE + VALID_PARAMETER_STYLE); - valueControl.setTooltip(null); + textField.setStyle(BASE_TEXT_STYLE + VALID_PARAMETER_STYLE); + textField.setTooltip(null); } } + @Override + public void refreshValue() { + textField.setText(String.valueOf((parameter).get())); + } } diff --git a/src/jcgp/gui/settings/parameters/GUIParameter.java b/src/jcgp/gui/settings/parameters/GUIParameter.java index 6bfdf30..b7afb74 100644 --- a/src/jcgp/gui/settings/parameters/GUIParameter.java +++ b/src/jcgp/gui/settings/parameters/GUIParameter.java @@ -9,6 +9,7 @@ import javafx.geometry.Pos; import javafx.scene.control.Control; import javafx.scene.control.Tooltip; import javafx.scene.layout.HBox; +import javafx.scene.layout.Priority; import javafx.scene.text.Text; import jcgp.backend.resources.parameters.BooleanParameter; import jcgp.backend.resources.parameters.DoubleParameter; @@ -18,7 +19,25 @@ import jcgp.backend.resources.parameters.ParameterStatus; import jcgp.gui.GUI; import jcgp.gui.settings.SettingsPane; -public abstract class GUIParameter extends HBox { +/** + * + * This is the base class for all GUIParameters. Using the factory method GUIParameter.create() + * generates an appropriate instance of this class for the specified parameter. + * <br><br> + * GUIParameter is an HBox containing a Text for the parameter name and a Control for interaction. + * It stores an instance of its associated Parameter object and also contains a Tooltip for + * displaying status information. + * <br><br> + * Monitor parameters have their Control disabled so that no changed can be made via the GUI. + * Non-monitor parameters are updated automatically as well, but may be changed by the user + * if the program is not evolving. + * <br><br> + * For more information on how parameters work in JCGP, see {@link Parameter}. + * + * @author Eduardo Pedroni + * @param <T> the parameter data type + */ +public abstract class GUIParameter<T> extends HBox { public static final String BASE_TEXT_STYLE = "-fx-border-color: #C9C9C9; -fx-border-radius: 2; -fx-padding: 0; "; public static final String BASE_CHECKBOX_STYLE = "-fx-padding: 0; "; @@ -26,66 +45,204 @@ public abstract class GUIParameter extends HBox { public static final String INVALID_PARAMETER_STYLE = "-fx-background-color: " + GUI.BAD_SELECTION_COLOUR; public static final String WARNING_PARAMETER_STYLE = "-fx-background-color: " + GUI.NEUTRAL_SELECTION_COLOUR; public static final String VALID_PARAMETER_STYLE = "-fx-background-color: " + GUI.NEUTRAL_COLOUR; - - protected Parameter parameter; - protected Text name; - protected Control valueControl; + + private Text name; + private Control valueControl; protected Tooltip tooltip; + protected Parameter<T> parameter; + + /** This is the lock used to prevent more than one update task to be scheduled + * at the same time on the same GUIParameter. */ + private AtomicBoolean updateLock = new AtomicBoolean(false); - protected AtomicBoolean updateCheck = new AtomicBoolean(true); + /** + * This value is used to assert whether the control has changed values since + * the program last ran. Therefore, it is updated whenever a generation occurs + * or the experiment is reset. + */ + private T referenceValue; - protected GUIParameter() { + /** + * This protected constructor contains the common elements to all GUIParameters + * and should be invoked by any subclasses using super(). + * + * @param parameter a Parameter for which to generate a GUIParameter + * @param sp a reference to the SettingsPane + */ + protected GUIParameter(Parameter<T> parameter, final SettingsPane sp) { + this.parameter = parameter; + this.referenceValue = parameter.get(); + setAlignment(Pos.CENTER_LEFT); setSpacing(5); + name = new Text(parameter.getName()); + // set text width to half of the total width of the GUIParameter + name.wrappingWidthProperty().bind(widthProperty().divide(2)); + // allow the text to grow to always fill half of the GUIParameter + + // the tooltip is the hover-over label containing status information, when appropriate tooltip = new Tooltip(); tooltip.setStyle("-fx-background-color: white; -fx-border-color: black; .page-corner {-fx-background-color: transparent;}"); tooltip.setSkin(null); + + + valueControl = makeControl(); + setHgrow(valueControl, Priority.ALWAYS); + + // if the parameter is a monitor, it should be permanently disabled + valueControl.setDisable(parameter.isMonitor()); + + // bind to parameter value property in a thread-safe way + makeThreadSafeBinding(); + + // if parameter is not a monitor, make sure the control is constrained appropriately + if (!parameter.isMonitor()) { + setControlListeners(sp); + } + + getChildren().addAll(name, valueControl); } - protected final void makeLightBinding() { + /** + * Factory method to create GUIParameters from Parameters. + * Use this to create an appropriate GUIParameter from any instance of Parameter, + * rather than manually downcasting the Parameter object every time. + * + * @param parameter a Parameter for which to generate a GUIParameter + * @param sp a reference to the SettingsPane + * @return an appropriate instance of GUIParameter + */ + public static GUIParameter<?> create(Parameter<?> parameter, SettingsPane sp) { + if (parameter instanceof IntegerParameter) { + return new GUIIntegerParameter((IntegerParameter) parameter, sp); + } else if (parameter instanceof DoubleParameter) { + return new GUIDoubleParameter((DoubleParameter) parameter, sp); + } else if (parameter instanceof BooleanParameter) { + return new GUIBooleanParameter((BooleanParameter) parameter, sp); + } else { + throw new ClassCastException("No GUIParameter subclass exists for argument of type " + parameter.getClass()); + } + } + + /** + * Parameters are intended to communicate information from the experiment + * to the GUI. Since the experiment runs on a separate threads and it is illegal + * to modify JavaFX objects from outside the JavaFX Application thread, this + * special ChangeListener updates the GUIParameter in a safe way. + * <br><br> + * Note that this is applied to all parameters regardless of whether they are + * monitors or not; the only difference between monitor and non-monitor parameters + * is that monitor parameters cannot be modified from the GUI. + */ + private void makeThreadSafeBinding() { parameter.valueProperty().addListener(new ChangeListener<Object>() { @Override public void changed( ObservableValue<? extends Object> observable, Object oldValue, Object newValue) { - if (updateCheck.getAndSet(false)) { - Platform.runLater(new Runnable() { - @Override - public void run() { - updateCheck.set(true); - refreshValue(); - } - }); + // only do this if the experiment is running + if (GUI.isWorking()) { + /* here's the catch - atomically get the lock state and set it to true + * the lock will only be false again when the runnable is finished executing, + * preventing multiple runnables to concurrently update the same GUIParameter + */ + if (!updateLock.getAndSet(true)) { + Platform.runLater(new Runnable() { + @Override + public void run() { + refreshValue(); + updateLock.set(false); + } + }); + } } } }); } - public abstract void refreshValue(); - - public abstract boolean requiresReset(); - - public abstract void applyValue(); - - public abstract void validate(); + /** + * @return true if the current value of the parameter does not prevent the + * experiment from running. + */ + public boolean isValid() { + return parameter.getStatus() != ParameterStatus.INVALID; + } - public static GUIParameter create(Parameter parameter, SettingsPane sp) { - if (parameter instanceof IntegerParameter) { - return new GUIIntegerParameter((IntegerParameter) parameter, sp); - } else if (parameter instanceof DoubleParameter) { - return new GUIDoubleParameter((DoubleParameter) parameter, sp); - } else if (parameter instanceof BooleanParameter) { - return new GUIBooleanParameter((BooleanParameter) parameter, sp); - } else { - throw new ClassCastException("No GUIParameter subclass exists for argument of type " + parameter.getClass()); - } + /** + * Force the parameter to validate its current value, and apply the associated + * style to the GUIParameter. + */ + public void validate() { + parameter.validate(parameter.get()); + refreshValue(); + setValidityStyle(); } - public boolean isValid() { - return parameter.getStatus() == ParameterStatus.VALID - || parameter.getStatus() == ParameterStatus.WARNING + /** + * Certain parameter changes might require the experiment to be reset, either + * because the parameter is critical or because its status requires a reset. + * + * @return true if an experiment reset is required due to this parameter changing. + */ + public boolean requiresReset() { + return (parameter.isCritical() && !parameter.get().equals(referenceValue)) || parameter.getStatus() == ParameterStatus.WARNING_RESET; } + + /** + * Set the current parameter value as the reference value of the GUIParameter. + * The new reference value will be used to determine the validity of the parameter, + * should its value change. + */ + public void applyValue() { + referenceValue = parameter.get(); + } + + /* + * The following prototypes are instance-dependent and are called from + * GUIParameter() as necessary. + */ + /** + * This method returns the Control object used to control the parameter. + * <br><br> + * Implementations of GUIParameter must override this method and return + * a control appropriate to the type of parameter. This will typically be + * done by referencing the protected field GUIParameter.parameter. + * + * @return the Control object to be added to the GUIParameter. + */ + protected abstract Control makeControl(); + + /** + * Adds the necessary handlers to the Control object in order to modify + * the underlying parameter. This will typically consist of filtering key + * presses to ensure no invalid characters are inserted, applying the new + * value to the underlying parameter and revalidating the parameters to + * reflect the changes made. + * + * @param settingsPane the parent Pane on which revalidateParameters() should + * be called. + */ + protected abstract void setControlListeners(SettingsPane settingsPane); + + /** + * This method is called to style the GUIParameter according to the status of + * the parameter, which can be obtained with parameter.getStatus(). While the + * subclass is free to style itself in any way, the CSS strings defined here + * (INVALID_PARAMETER_STYLE, WARNING_PARAMETER_STYLE, VALID_PARAMETER_STYLE) + * provide a way to keep the GUI consistent. + * + * TODO update this if the strings are externalised + * + * @see ParameterStatus + */ + protected abstract void setValidityStyle(); + + /** + * Update the control so it shows the correct value of the parameter. This method + * is used exclusively by the thread-safe binding created if the module is a monitor. + */ + protected abstract void refreshValue(); } |