Merging mk rev. 211, 212: Matlab interface now works with binary data using uint32 (GAIndividualIntegerData).

This commit is contained in:
Marcel Kronfeld 2008-09-19 12:49:13 +00:00
parent 45d35a68e3
commit d6f2ec1ad1
12 changed files with 359 additions and 235 deletions

View File

@ -6,7 +6,7 @@ function int = JEInterface(interfaceName, fhandle, range, varargin)
% name as a String to allow callbacks from Java. % name as a String to allow callbacks from Java.
% fhandle: a function handle defining the optimization target. % fhandle: a function handle defining the optimization target.
% range: a 2 x dim array defining the solution subspace with lower and % range: a 2 x dim array defining the solution subspace with lower and
% upper bounds. % upper bounds - or a scalar defining the bitwidth for binary problems.
% optset: (optional) an optimset struct defining optimization parameters, % optset: (optional) an optimset struct defining optimization parameters,
% especially tolerance and maximum function calls. Defaults to the % especially tolerance and maximum function calls. Defaults to the
% EvA2 default values. % EvA2 default values.
@ -24,6 +24,11 @@ function int = JEInterface(interfaceName, fhandle, range, varargin)
% and TolFun for a certain time, e.g. 100 evaluations. % and TolFun for a certain time, e.g. 100 evaluations.
% To ignore a criterion, set it to 0. E.g. to perform 10^5 evaluations in % To ignore a criterion, set it to 0. E.g. to perform 10^5 evaluations in
% any case, set TolX=TolFun=0 and MaxFunEvals=10^5. % any case, set TolX=TolFun=0 and MaxFunEvals=10^5.
%
% You may define a 2xdim range with a double valued function handle or for
% binary problems set a scalar as range defining the number of bits to be
% used. The values passed to the function handle will then be arrays of
% uint32, each of them representing 32 bits.
int.args = []; int.args = [];
int.opts = optimset('MaxFunEvals', eva2.OptimizerFactory.getDefaultFitCalls, 'TolX', 1e-4, 'TolFun', 1e-4); int.opts = optimset('MaxFunEvals', eva2.OptimizerFactory.getDefaultFitCalls, 'TolX', 1e-4, 'TolFun', 1e-4);
@ -40,6 +45,7 @@ int.funCalls = 0;
int.mediator = ''; int.mediator = '';
int.optParams = []; int.optParams = [];
int.optParamValues = []; int.optParamValues = [];
int.hexMask=hex2dec('ffffffff');
if (isa(interfaceName, 'char')); if (isa(interfaceName, 'char'));
int.callback = interfaceName; int.callback = interfaceName;
@ -56,7 +62,11 @@ if (isa(range, 'double') && (size(range,1) == 2))
int.dim=length(range); int.dim=length(range);
int.range=transpose(range); int.range=transpose(range);
else else
error('Wrong third argument type, expected double array of 2 x dim'); %error('Wrong third argument type, expected double array of 2 x dim');
if (size(range,1)==size(range,2)==1)
int.range=[];
int.dim=range;
end
end end
int = class(int,'JEInterface'); int = class(int,'JEInterface');
@ -80,7 +90,7 @@ switch nargin
end end
% finally create the java object % finally create the java object
int.mp = eva2.server.go.problems.MatlabProblem(int.callback, int.dim, int.range); int.mp = eva2.server.go.problems.MatlabProblem(int.dim, int.range);

View File

@ -0,0 +1,14 @@
function [ z ] = convertUnsignedJE( int, x )
%CONVERTUNSIGNEDJE Convert signed 32-bit integer to unsigned.
% Detailed explanation goes here
z=zeros(size(x,1),size(x,2), 'uint32');
for j=1 : size(x,1)
for i=1 : size(x,2)
if (x(j,i) < 0)
z(j,i) = 1+bitxor(uint32(-x(j,i)), int.hexMask);
else
z(j,i) = x(j,i);
end
end
end

View File

@ -13,6 +13,10 @@ end
if (isempty(sol)) if (isempty(sol))
fit = NaN; fit = NaN;
else else
if (isempty(int.range))
sol=convertUnsignedJE(int, sol);
end;
if (isempty(int.args)) if (isempty(int.args))
fit = feval(int.f, sol); fit = feval(int.f, sol);
else else

View File

@ -64,11 +64,25 @@ try
int.mediator.run; int.mediator.run;
if (~int.mediator.isFinished()) if (~int.mediator.isFinished())
x = int.mediator.getQuestion(); x = int.mediator.getQuestion();
if (isempty(int.range))
%size(x)
x=convertUnsignedJE(int, x);
%disp('here B');
%x
end
% size(x)
try
if (isempty(int.args)) if (isempty(int.args))
res = feval(int.f, x); res = feval(int.f, x);
else else
res = feval(int.f, x, int.args); res = feval(int.f, x, int.args);
end end
%res
catch ME
disp('function evaluation failed:');
disp(ME.message);
stopOptimization=1;
end
int.mediator.setAnswer(res); int.mediator.setAnswer(res);
drawnow; drawnow;
if ((stopOptimization==1) && (stopOnce==1)) if ((stopOptimization==1) && (stopOnce==1))
@ -79,8 +93,9 @@ try
end end
end end
clear global JEMediator; clear global JEMediator;
catch catch ME
disp('Error in evaluate!'); disp('Error in evaluate!');
disp(ME.message);
%int.mediator.quit; % just in case %int.mediator.quit; % just in case
%int.mediator=''; %int.mediator='';

View File

@ -2,7 +2,6 @@ function int = setJEResult(int, result)
% Interface function to be called by EvA2. % Interface function to be called by EvA2.
% Write back the solution and retrieve some additional data. % Write back the solution and retrieve some additional data.
int.result = result; int.result = result;
int.finished = 1; int.finished = 1;
int.msg=int.mp.getInfoString; int.msg=int.mp.getInfoString;

View File

@ -962,4 +962,34 @@ public abstract class AbstractEAIndividual implements IndividualInterface, java.
return isDominatingDebConstraints((AbstractEAIndividual)indy); return isDominatingDebConstraints((AbstractEAIndividual)indy);
} }
/**
* Return the individual data (phenotype) as BitSet, int[], double[], int[] (coding permutation)
* or InterfaceProgram[].
*
* @param individual
* @return
*/
public static Object getIndyData(AbstractEAIndividual individual) {
if (individual instanceof InterfaceDataTypeBinary) {
BitSet b = ((InterfaceDataTypeBinary)individual).getBinaryData();
return b;
} else if (individual instanceof InterfaceDataTypeInteger) {
int[] b = ((InterfaceDataTypeInteger)individual).getIntegerData();
return b;
} else if (individual instanceof InterfaceDataTypeDouble) {
double[] b = ((InterfaceDataTypeDouble)individual).getDoubleData();
return b;
} else if (individual instanceof InterfaceDataTypePermutation) {
int[] b = ((InterfaceDataTypePermutation)individual).getPermutationData()[0];
return b;
} else if (individual instanceof InterfaceDataTypeProgram) {
InterfaceProgram[] b = ((InterfaceDataTypeProgram)individual).getProgramData();
return b;
} else {
System.err.println("error in AbstractEAIndividual::getDefaultDataString: type " + individual.getClass() + " not implemented");
return null;
} }
}
}

View File

@ -135,7 +135,7 @@ public class GAIndividualIntegerData extends AbstractEAIndividual implements Int
return this.m_Range.length; return this.m_Range.length;
} }
/** This method will set the range of the double attributes. If range.length /** This method will set the range of the integer attributes. If range.length
* does not equal doubledata.length only range[i] will be used to set all * does not equal doubledata.length only range[i] will be used to set all
* ranges. * ranges.
* @param range The new range for the double data. * @param range The new range for the double data.
@ -152,6 +152,32 @@ public class GAIndividualIntegerData extends AbstractEAIndividual implements Int
this.setIntegerDataLength(range.length); this.setIntegerDataLength(range.length);
} }
/**
* Set lower and upper integer range in all dimensions.
*
* @param lower
* @param upper
*/
public void SetIntRange(int lower, int upper) {
for (int i=0; i<m_Range.length; i++) {
SetIntRange(i, lower, upper);
m_CodingLenghts[i] = m_IntegerCoding.calculateNecessaryBits(m_Range[i]);
}
}
/**
* Set lower and upper integer range in a specific dimension.
*
* @param index
* @param lower
* @param upper
*/
public void SetIntRange(int index, int lower, int upper) {
m_Range[index][0] = lower;
m_Range[index][1] = upper;
m_CodingLenghts[index] = m_IntegerCoding.calculateNecessaryBits(m_Range[index]);
}
/** This method will return the range for all double attributes. /** This method will return the range for all double attributes.
* @return The range array. * @return The range array.
*/ */

View File

@ -124,7 +124,7 @@ public class GAStandardCodingInteger implements InterfaceGAIntegerCoding, java.i
*/ */
public int calculateNecessaryBits(int[] range) { public int calculateNecessaryBits(int[] range) {
int result = 0; int result = 0;
int maxStore = 1 + range[1] -range[0]; double maxStore = 1. + range[1] -range[0];
while (Math.pow(2, result) < maxStore) result++; while (Math.pow(2, result) < maxStore) result++;

View File

@ -1,5 +1,8 @@
package eva2.server.go.problems; package eva2.server.go.problems;
import java.lang.reflect.Array;
import java.util.BitSet;
import eva2.gui.BeanInspector; import eva2.gui.BeanInspector;
/** /**
@ -26,11 +29,11 @@ public class MatlabEvalMediator implements Runnable {
volatile boolean requesting = false; volatile boolean requesting = false;
// final static boolean TRACE = false; // final static boolean TRACE = false;
volatile boolean fin = false; volatile boolean fin = false;
volatile double[] question = null; volatile Object question = null;
volatile double[] answer = null; volatile double[] answer = null;
boolean quit = false; boolean quit = false;
volatile double[] optSolution = null; volatile Object optSolution = null;
volatile double[][] optSolSet = null; volatile Object[] optSolSet = null;
// MatlabProblem mp = null; // MatlabProblem mp = null;
// no good: even when waiting for only 1 ms the Matlab execution time increases by a factor of 5-10 // no good: even when waiting for only 1 ms the Matlab execution time increases by a factor of 5-10
final static int sleepTime = 0; final static int sleepTime = 0;
@ -41,9 +44,18 @@ public class MatlabEvalMediator implements Runnable {
* @param x * @param x
* @return * @return
*/ */
double[] requestEval(MatlabProblem mp, double[] x) { double[] requestEval(MatlabProblem mp, Object x) {
// this.mp = mp; // this.mp = mp;
question = x; question = x;
// System.err.println("IN REQUESTEVAL, x is " + BeanInspector.toString(x));
if (question.getClass().isArray()) {
// System.err.println("array of type ** " + Array.get(question, 0).getClass().toString());
// } else if (question instanceof BitSet){
// BitSet b = (BitSet)x;
// Integer.decode()
//
} else System.err.println("Error, requesting evaluation for non array!");
requesting = true; requesting = true;
// int k=0; // int k=0;
// System.out.println("Requesting eval for " + BeanInspector.toString(x) + ", req state is " + requesting + "\n"); // System.out.println("Requesting eval for " + BeanInspector.toString(x) + ", req state is " + requesting + "\n");
@ -89,7 +101,7 @@ public class MatlabEvalMediator implements Runnable {
* To be called from Matlab. * To be called from Matlab.
* @return * @return
*/ */
public double[] getQuestion() { public Object getQuestion() {
// mp.log("-- Question: " + BeanInspector.toString(question) + "\n"); // mp.log("-- Question: " + BeanInspector.toString(question) + "\n");
return question; return question;
} }
@ -105,6 +117,7 @@ public class MatlabEvalMediator implements Runnable {
*/ */
public void setAnswer(double[] y) { public void setAnswer(double[] y) {
// mp.log("-- setAnswer: " + BeanInspector.toString(y) + "\n"); // mp.log("-- setAnswer: " + BeanInspector.toString(y) + "\n");
// System.err.println("answer is " + BeanInspector.toString(y));
answer = y; answer = y;
requesting = false; // answer is finished, break request loop requesting = false; // answer is finished, break request loop
} }
@ -121,13 +134,18 @@ public class MatlabEvalMediator implements Runnable {
return fin; return fin;
} }
void setSolution(double[] sol) { void setSolution(Object sol) {
//System.out.println("setting Sol"); //System.out.println("setting Sol");
optSolution = sol; optSolution = sol;
} }
void setSolutionSet(double[][] solSet) { void setSolutionSet(double[][] solSet) {
//System.out.println("setting SolSet " + ((solSet != null) ? solSet.length : 0)); // System.err.println("setting SolSet " + ((solSet != null) ? solSet.length : 0));
optSolSet = solSet;
}
void setSolutionSet(int[][] solSet) {
// System.err.println("setting SolSet " + ((solSet != null) ? solSet.length : 0));
optSolSet = solSet; optSolSet = solSet;
} }
@ -135,17 +153,17 @@ public class MatlabEvalMediator implements Runnable {
* Matlab may retrieve result. * Matlab may retrieve result.
* @return * @return
*/ */
public double[] getSolution() { public Object getSolution() {
//System.out.println("getting Sol"); // System.err.println("getting Sol");
return optSolution; return optSolution;
} }
/** /**
* Matlab may retrieve result. * Matlab may retrieve result as Object[] containing either double[] or int[].
* @return * @return
*/ */
public double[][] getSolutionSet() { public Object[] getSolutionSet() {
//System.out.println("getting SolSet" + ((optSolSet != null) ? optSolSet.length : 0)); // System.err.println("getting SolSet " + ((optSolSet != null) ? optSolSet.length : 0));
return optSolSet; return optSolSet;
} }
} }

View File

@ -3,16 +3,16 @@ package eva2.server.go.problems;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.PrintStream; import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.Serializable; import java.io.Serializable;
import java.io.StringWriter;
import eva2.OptimizerFactory; import eva2.OptimizerFactory;
import eva2.OptimizerRunnable; import eva2.OptimizerRunnable;
import eva2.gui.BeanInspector; import eva2.gui.BeanInspector;
import eva2.server.go.individuals.AbstractEAIndividual; import eva2.server.go.individuals.AbstractEAIndividual;
import eva2.server.go.individuals.ESIndividualDoubleData; import eva2.server.go.individuals.ESIndividualDoubleData;
import eva2.server.go.individuals.GAIndividualIntegerData;
import eva2.server.go.individuals.InterfaceDataTypeDouble; import eva2.server.go.individuals.InterfaceDataTypeDouble;
import eva2.server.go.individuals.InterfaceDataTypeInteger;
import eva2.server.go.operators.postprocess.InterfacePostProcessParams; import eva2.server.go.operators.postprocess.InterfacePostProcessParams;
import eva2.server.go.operators.postprocess.PostProcess; import eva2.server.go.operators.postprocess.PostProcess;
import eva2.server.go.operators.postprocess.PostProcessParams; import eva2.server.go.operators.postprocess.PostProcessParams;
@ -28,19 +28,18 @@ import eva2.server.stat.InterfaceTextListener;
* @author mkron * @author mkron
* *
*/ */
public class MatlabProblem extends AbstractProblemDouble implements InterfaceTextListener, Serializable { public class MatlabProblem extends AbstractOptimizationProblem implements InterfaceTextListener, Serializable {
private static final long serialVersionUID = 4913310869887420815L; private static final long serialVersionUID = 4913310869887420815L;
public static final boolean TRACE = false; public static final boolean TRACE = true;
// transient protected Matlab matlab = null;
transient OptimizerRunnable runnable = null; transient OptimizerRunnable runnable = null;
protected boolean allowSingleRunnable = true; protected boolean allowSingleRunnable = true;
// protected String jmInterface;
protected int problemDimension = 10; protected int problemDimension = 10;
transient PrintStream dos = null; transient PrintStream dos = null;
protected double[][] range = null; private double range[][] = null;
private static final String defTestOut = "matlabproblem-testout.dat"; private static final String defTestOut = "matlabproblem-testout.dat";
int verbosityLevel = 0; int verbosityLevel = 0;
private MatlabEvalMediator handler = null; private MatlabEvalMediator handler = null;
private boolean isDouble = true;
public static boolean hideFromGOE = true; public static boolean hideFromGOE = true;
@ -56,7 +55,8 @@ public class MatlabProblem extends AbstractProblemDouble implements InterfaceTex
this.problemDimension = o.problemDimension; this.problemDimension = o.problemDimension;
// this.res = new ResultArr(); // this.res = new ResultArr();
// if (o.res != null) if (o.res.get() != null) res.set(o.res.get()); // if (o.res != null) if (o.res.get() != null) res.set(o.res.get());
this.range = o.makeRange(); this.range = o.range;
this.isDouble = o.isDouble;
// this.mtCmd = o.mtCmd; // this.mtCmd = o.mtCmd;
// currArray = null; // currArray = null;
} }
@ -65,17 +65,16 @@ public class MatlabProblem extends AbstractProblemDouble implements InterfaceTex
return new MatlabProblem(this); return new MatlabProblem(this);
} }
public MatlabProblem(String nameJEInterface, int dim) { public MatlabProblem(int dim) {
this(nameJEInterface, dim, null); this(dim, (double[][])null);
range = super.makeRange();
} }
public MatlabProblem(String nameJEInterface, int dim, double[][] range) { public MatlabProblem(int dim, double[][] range) {
init(nameJEInterface, dim, range, defTestOut); init(dim, range, defTestOut);
} }
public MatlabProblem(String nameJEInterface, int dim, double lower, double upper) { public MatlabProblem(int dim, double lower, double upper) {
this(nameJEInterface, dim, null); this(dim, null);
double[][] range = new double[dim][2]; double[][] range = new double[dim][2];
for (int i=0; i<dim; i++) { for (int i=0; i<dim; i++) {
range[dim][0] = lower; range[dim][0] = lower;
@ -83,18 +82,45 @@ public class MatlabProblem extends AbstractProblemDouble implements InterfaceTex
} }
} }
protected void initTemplate() {
if (isDouble) {
if (m_Template == null) m_Template = new ESIndividualDoubleData();
if (getProblemDimension() > 0) { // avoid evil case setting dim to 0 during object init
((InterfaceDataTypeDouble)this.m_Template).setDoubleDataLength(getProblemDimension());
((InterfaceDataTypeDouble)this.m_Template).SetDoubleRange(range);
}
} else {
m_Template = new GAIndividualIntegerData();
int intLen = 1+((getProblemDimension()-1)/32);
int lastIntCodingBits = getProblemDimension()-((intLen-1)*32);
if (lastIntCodingBits > 32) System.err.println("ERROR in MatlabProblem:initTemplate");
((GAIndividualIntegerData)m_Template).setIntegerDataLength(intLen);
((GAIndividualIntegerData)m_Template).SetIntRange(Integer.MIN_VALUE, Integer.MAX_VALUE);
if (lastIntCodingBits < 32) ((GAIndividualIntegerData)m_Template).SetIntRange(intLen-1, 0, (int)Math.pow(2, lastIntCodingBits)-1);
// System.err.println("integer length is "+((GAIndividualIntegerData)m_Template).getIntegerData().length);
// System.err.println("Range is " + BeanInspector.toString(((GAIndividualIntegerData)m_Template).getIntRange()));
// m_Template = new GAIndividualBinaryData();
// ((GAIndividualBinaryData)m_Template).setBinaryDataLength(getProblemDimension());
}
}
public void setMediator(MatlabEvalMediator h) { public void setMediator(MatlabEvalMediator h) {
handler = h; handler = h;
} }
public void initProblem() { public void initProblem() {
init(/*this.jmInterface*/ null, this.problemDimension, this.range, defTestOut); init(this.problemDimension, range, defTestOut);
} }
private void init(String nameJEInterface, int dim, double[][] rng, String outFile) { private void init(int dim, double[][] rng, String outFile) {
problemDimension = dim; problemDimension = dim;
if ((rng != null) && (dim != rng.length)) throw new ArrayIndexOutOfBoundsException("Mismatching dimension and range!"); // if ((rng != null) && (dim != rng.length)) throw new ArrayIndexOutOfBoundsException("Mismatching dimension and range!");
range = rng; range = rng;
if (range==null) isDouble = false;
else isDouble = true;
// System.err.println("isDouble: " + isDouble);
// System.err.println("range: " + BeanInspector.toString(range));
initTemplate(); initTemplate();
// res = new ResultArr(); // res = new ResultArr();
if ((dos == null) && TRACE) { if ((dos == null) && TRACE) {
@ -105,39 +131,10 @@ public class MatlabProblem extends AbstractProblemDouble implements InterfaceTex
} }
} }
log("range is " + BeanInspector.toString(range)+ "\n"); // log("range is " + BeanInspector.toString(range)+ "\n");
log("template len: " + ((ESIndividualDoubleData)m_Template).getDGenotype().length + "\n"); // log("template len: " + ((ESIndividualDoubleData)m_Template).getDGenotype().length + "\n");
// try {
// if (matlab == null)
// matlab = new Matlab();//this command links to the current matlab session
// try {
// matlab.eval("JE='hello'");
// } catch (Exception e) {
// e.printStackTrace();
// }
// } catch (Error e) {
// log("Error: " + e.toString());
// System.err.println("Error: could not create MatlabProblem instance. MatlabProblem can only be used from Matlab.");
// }
// this.jmInterface = nameJEInterface;
// mtCmd = new String("evaluateJE("+jmInterface+")");
} }
// /**
// * @return the jmInterface
// */
// public String getJmInterfaceName() {
// return jmInterface;
// }
// /**
// * @param jmInterface the jmInterface to set
// */
// public void setJmInterfaceName(String jmInterface) {
// this.jmInterface = jmInterface;
// }
public void setStatsOutput(int verboLevel) { public void setStatsOutput(int verboLevel) {
if ((verboLevel >= 0) && (verboLevel <= 3)) { if ((verboLevel >= 0) && (verboLevel <= 3)) {
verbosityLevel = verboLevel; verbosityLevel = verboLevel;
@ -165,23 +162,23 @@ public class MatlabProblem extends AbstractProblemDouble implements InterfaceTex
return "The dimension of the problem."; return "The dimension of the problem.";
} }
public double[][] makeRange() { // public double[][] makeRange() {
if (range==null) range=super.makeRange(); // if (range==null) range=super.makeRange();
return range; // return range;
} // }
protected double getRangeLowerBound(int dim) { // protected double getRangeLowerBound(int dim) {
return (range==null) ? super.getRangeLowerBound(dim) : range[dim][0]; // return (range==null) ? super.getRangeLowerBound(dim) : range[dim][0];
} // }
protected double getRangeUpperBound(int dim) { // protected double getRangeUpperBound(int dim) {
return (range==null) ? super.getRangeUpperBound(dim) : range[dim][1]; // return (range==null) ? super.getRangeUpperBound(dim) : range[dim][1];
} // }
// public double[] getCurrentDoubleArray() { // public double[] getCurrentDoubleArray() {
// return currArray; // return currArray;
// } // }
//
// public double[] getNewDoubleArray() { // public double[] getNewDoubleArray() {
// currArray = new double[problemDimension]; // currArray = new double[problemDimension];
// for (int i=0; i<problemDimension; i++) currArray[i] = RNG.gaussianDouble(1); // for (int i=0; i<problemDimension; i++) currArray[i] = RNG.gaussianDouble(1);
@ -195,32 +192,6 @@ public class MatlabProblem extends AbstractProblemDouble implements InterfaceTex
} }
} }
public double[] eval(double[] x) {
log("evaluating " + BeanInspector.toString(x) + "\n");
double[] res = handler.requestEval(this, x);
// double diff = PhenotypeMetric.euclidianDistance(res, f1.eval(x));
// log("result: " + BeanInspector.toString(res) + " compared to " + BeanInspector.toString(f1.eval(x)) + "\n");
// if (diff != 0) {
// log("!!! diff is " + diff + "\n");
// }
return res;
// synchronized (this) {
// try {
// res.reset();
// currArray = x;
// log("evaluating " + BeanInspector.toString(x) + "\n");
// matlab.eval(mtCmd, (CompletionObserver)this);
// this.wait();
// } catch (InterruptedException e) {
// log("wait interrupted: " + e.getMessage() + " \n");
// }
// }
// log("wait done, returning " + res.get()[0] + " \n");
// return res.get();
}
public void optimize(final int optType, String outputFilePrefix) { public void optimize(final int optType, String outputFilePrefix) {
optimize(optType, outputFilePrefix, null, null); optimize(optType, outputFilePrefix, null, null);
} }
@ -330,59 +301,41 @@ public class MatlabProblem extends AbstractProblemDouble implements InterfaceTex
if (runnable == null) return 0; if (runnable == null) return 0;
return runnable.getGOParams().getOptimizer().getPopulation().getFunctionCalls(); return runnable.getGOParams().getOptimizer().getPopulation().getFunctionCalls();
} }
//
// Matlab getMatlab() { // Matlab getMatlab() {
// return matlab; // return matlab;
// } // }
//
void exportResultPopulationToMatlab(Population pop) { void exportResultPopulationToMatlab(Population pop) {
double[][] solSet;
if ((pop != null) && (pop.size()>0)) { if ((pop != null) && (pop.size()>0)) {
solSet = new double[pop.size()][]; if (isDouble) {
double[][] solSet = new double[pop.size()][];
for (int i=0; i<pop.size(); i++) { for (int i=0; i<pop.size(); i++) {
solSet[i]=((InterfaceDataTypeDouble)pop.getEAIndividual(i)).getDoubleData(); solSet[i]=((InterfaceDataTypeDouble)pop.getEAIndividual(i)).getDoubleData();
} }
handler.setSolutionSet(solSet); handler.setSolutionSet(solSet);
} else { } else {
handler.setSolutionSet(null); int[][] solSet = new int[pop.size()][];
for (int i=0; i<pop.size(); i++) {
solSet[i]=((InterfaceDataTypeInteger)pop.getEAIndividual(i)).getIntegerData();
}
handler.setSolutionSet(solSet);
}
} else {
if (isDouble) handler.setSolutionSet((double[][])null);
else handler.setSolutionSet((int[][])null);
} }
// String resStr;
// if ((pop == null) || (pop.size() == 0)) resStr = "[]";
// else {
// StringBuffer sb = new StringBuffer();
// sb.append("[");
// for (int i=0; i<pop.size(); i++) {
// sb.append(AbstractEAIndividual.getDefaultDataString(pop.getEAIndividual(i), " "));
// if (i<pop.size()-1) sb.append(";");
// }
// sb.append("]");
// resStr = sb.toString();
// }
// log("result array was " + resStr + "\n");
// try {
// String cmd = jmInterface + "= setResultArrayJE(" + jmInterface + ", " + resStr + ")";
// log("trying cmd: "+ cmd + "\n");
// matlab.eval(cmd);
// } catch (Exception e) {
// log("Exception when exporting result to Matlab! "+e.getMessage());
// }
} }
void exportResultToMatlab(double[] result) { void exportResultToMatlab(OptimizerRunnable runnable) {
handler.setSolution(result); if (isDouble) handler.setSolution(runnable.getDoubleSolution());
// String resStr; else handler.setSolution(runnable.getIntegerSolution());
// if (result == null) resStr = "[]";
// else resStr = BeanInspector.toString(result);
// log("result was " + resStr + "\n");
// try {
// String cmd = jmInterface + "= setResultJE(" + jmInterface + ", " + resStr + ")";
// log("trying cmd: "+ cmd + "\n");
// matlab.eval(cmd);
// } catch (Exception e) {
// log("Exception when exporting result to Matlab! "+e.getMessage());
// }
} }
// void exportResultToMatlab(double[] result) {
// handler.setSolution(result);
// }
/** /**
* To be called by the executing thread to inform that the thread is finished. * To be called by the executing thread to inform that the thread is finished.
* We * We
@ -391,9 +344,12 @@ public class MatlabProblem extends AbstractProblemDouble implements InterfaceTex
handler.setFinished(true); handler.setFinished(true);
} }
public double[] getIntermediateResult() { public Object getIntermediateResult() {
if (runnable == null) return null; if (runnable == null) return null;
else return runnable.getDoubleSolution(); else {
if (isDouble) return runnable.getDoubleSolution();
else return runnable.getIntegerSolution();
}
} }
/** /**
@ -421,57 +377,43 @@ public class MatlabProblem extends AbstractProblemDouble implements InterfaceTex
print(str); print(str);
print("\n"); print("\n");
} }
//
// public double[] eval(double[] x) {
// log("evaluating " + BeanInspector.toString(x) + "\n");
// double[] res = handler.requestEval(this, x);
// return res;
// }
@Override
public void evaluate(AbstractEAIndividual indy) {
log("evaluating " + BeanInspector.toString(indy) + "\n");
double[] res = handler.requestEval(this, AbstractEAIndividual.getIndyData(indy));
indy.SetFitness(res);
// System.err.println("evaluated to " + BeanInspector.toString(res));
} }
//////////////////////////// @Override
public void initPopulation(Population population) {
AbstractEAIndividual tmpIndy;
population.clear();
initTemplate();
class WaitForEvARunnable implements Runnable { for (int i = 0; i < population.getPopulationSize(); i++) {
OptimizerRunnable runnable; tmpIndy = (AbstractEAIndividual)((AbstractEAIndividual)this.m_Template).clone();
MatlabProblem mp; tmpIndy.init(this);
// System.err.println("initPopulation: " + AbstractEAIndividual.getDefaultDataString(tmpIndy) + " , " + tmpIndy.getStringRepresentation());
public WaitForEvARunnable(OptimizerRunnable runnable, MatlabProblem mp) { population.add(tmpIndy);
this.runnable = runnable; }
this.mp = mp; // population init must be last
// it set's fitcalls and generation to zero
population.init();
} }
public void run() { public String getStringRepresentationForProblem(InterfaceOptimizer opt) {
if (runnable != null) { StringBuffer sb = new StringBuffer(200);
mp.log("\nStarting optimize runnable!\n"); sb.append("A general Matlab problem");
sb.append(this.getName());
synchronized (runnable) { //sb.append("\n");
try { return sb.toString();
// whole optimization thread goes in here
new Thread(runnable).start();
mp.log("Starting optimize thread done!\n");
runnable.wait();
// wait for the runnable to finish
mp.log("After wait!\n");
} catch (InterruptedException e) {
e.printStackTrace();
mp.log("WaitForEvARunnable was interrupted with " + e.getMessage());
} }
} }
try {
mp.log("runnable.getSolution: " + BeanInspector.toString(runnable.getDoubleSolution()));
mp.log("\ngetAllSols best: " + AbstractEAIndividual.getDefaultDataString(runnable.getGOParams().getOptimizer().getAllSolutions().getSolutions().getBestEAIndividual()));
mp.log("\n");
// write results back to matlab
mp.exportResultToMatlab(runnable.getDoubleSolution());
mp.exportResultPopulationToMatlab(runnable.getSolutionSet());
System.out.println("Optimization finished: " + mp.getInfoString());
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
mp.log("error in callback: " + e.getMessage() + " " + sw.toString() + "\n");
}
} else {
System.err.println("Invalid optimization call.");
mp.log("invalid call, no optimization started.\n");
mp.exportResultToMatlab(null);
mp.exportResultPopulationToMatlab(null);
}
mp.notifyFinished();
mp.log("notified finish...");
}
}

View File

@ -0,0 +1,60 @@
package eva2.server.go.problems;
import java.io.PrintWriter;
import java.io.StringWriter;
import eva2.OptimizerRunnable;
import eva2.gui.BeanInspector;
import eva2.server.go.individuals.AbstractEAIndividual;
class WaitForEvARunnable implements Runnable {
OptimizerRunnable runnable;
MatlabProblem mp;
public WaitForEvARunnable(OptimizerRunnable runnable, MatlabProblem mp) {
this.runnable = runnable;
this.mp = mp;
}
public void run() {
if (runnable != null) {
mp.log("\nStarting optimize runnable!\n");
synchronized (runnable) {
try {
// whole optimization thread goes in here
new Thread(runnable).start();
mp.log("Starting optimize thread done!\n");
runnable.wait();
// wait for the runnable to finish
mp.log("After wait!\n");
} catch (InterruptedException e) {
e.printStackTrace();
mp.log("WaitForEvARunnable was interrupted with " + e.getMessage());
}
}
try {
mp.log("runnable.getDoubleSolution: " + BeanInspector.toString(runnable.getDoubleSolution()));
mp.log("runnable.getIntegerSolution: " + BeanInspector.toString(runnable.getIntegerSolution()));
mp.log("\ngetAllSols best: " + AbstractEAIndividual.getDefaultDataString(runnable.getGOParams().getOptimizer().getAllSolutions().getSolutions().getBestEAIndividual()));
mp.log("\n");
// write results back to matlab
mp.exportResultToMatlab(runnable);
mp.exportResultPopulationToMatlab(runnable.getSolutionSet());
System.out.println("Optimization finished: " + mp.getInfoString());
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
mp.log("error in callback: " + e.getMessage() + " " + sw.toString() + "\n");
}
} else {
System.err.println("Invalid optimization call.");
mp.log("invalid call, no optimization started.\n");
mp.exportResultToMatlab(null);
mp.exportResultPopulationToMatlab(null);
}
mp.notifyFinished();
mp.log("notified finish...");
}
}

View File

@ -9,9 +9,13 @@ import eva2.server.go.populations.SolutionSet;
import eva2.server.go.problems.B1Problem; import eva2.server.go.problems.B1Problem;
import eva2.server.go.problems.InterfaceOptimizationProblem; import eva2.server.go.problems.InterfaceOptimizationProblem;
/** The simple random or Monte-Carlo search, simple but useful /**
* The simple random or Monte-Carlo search, simple but useful
* to evaluate the complexity of the search space. * to evaluate the complexity of the search space.
* This implements a Random Walk Search. * This implements a Random Walk Search using the initialization
* method of the problem instance, meaning that the random characteristics
* may be problem dependent.
*
* Copyright: Copyright (c) 2003 * Copyright: Copyright (c) 2003
* Company: University of Tuebingen, Computer Architecture * Company: University of Tuebingen, Computer Architecture
* @author Felix Streichert * @author Felix Streichert
@ -71,7 +75,9 @@ public class MonteCarloSearch implements InterfaceOptimizer, java.io.Serializabl
} }
} }
/** This method will optimize /**
* This method will optimize without specific operators, by just calling the problem method
* for population initialization.
*/ */
public void optimize() { public void optimize() {
Population original = (Population)this.m_Population.clone(); Population original = (Population)this.m_Population.clone();