ECJ will generate Lisp output, by default, but wouldn't it be nice if it could generate pure Java code for you - automatically?
ECJ2Java allows you to do exactly that, with a minimum amount of disruption to your existing GP functions. It fits into your existing ECJ framework easily too. Please note that this only applies to Genetic Programming problems!
All you need to do is extend either ParseableGPNode
, or ParseableERC
instead of ECJ's default GPNode
and ERC
classes, and implement the required getJavaCode()
function. You can then use the ECJ2Java program to automatically convert a GPIndividual
tree into
a Java class. You can do this in the describe
method of your Problem class's code.
A full, standalone, example is provided in ac.essex.ooechs.ecj2java.example
. The example shows
a equation solving program that outputs its individuals as Java Files. Have a look at its solution to the Pythagoras Equation.
These are the essential steps:
ParseableGPNode
instead of GPNode
ParseableERC
instead of ERC
describe
method on your problemdescribe
method in your Problem class (if not already present)Listing 1 - Example Describe Method
static int counter = 0; public void describe(final Individual ind, final EvolutionState state, final int threadnum, final int log, final int verbosity) { state.output.println("\n\nBest Individual", verbosity, log); KozaFitness f = ((KozaFitness) ind.fitness); counter++; /** * Create a ECJ2Java Writer here, with the following parameters: */ String classPackage = "ac.essex.ooechs.ecj2java.example.individuals"; String className = "MathsSolution" + counter; String functionSignature = "public double calculate(double x)"; String comment = "Fitness: " + f.hits; JavaWriter writer = new JavaWriter(className, functionSignature, comment, classPackage); /** * Decide where the Java file is to be saved: */ File saveTo = new File("/home/ooechs/Ecj2Java/src/ac/essex/ooechs/ecj2java/example/individuals/"); /** * Generate and save the file */ try { writer.saveJavaCode((GPIndividual) ind, saveTo); } catch (IOException e) { e.printStackTrace(); } /** * And that's all there is to it! */ System.out.println("TP: " + f.hits); System.out.println("Fitness: " + f.standardizedFitness()); }
Have a look at some code generated automatically:
MathSolution1.java
Please note that ParseableERC.java refers to a class in my commons library that is currently unavailable. You'll need to change the import statement to import your own Data class. There is a compatible one here
The example may be run with the following command:
java ec.Evolve -file [full/path/to]example.params -p stat.gather-full=true
Page written by Olly Oechsle, ooechs at essex dot ac dot uk.
Please note that ECJ2Java is a work in progress - comments and suggestions are appreciated.
Updated: Dec 8th 2006.