Skip to content

Instantly share code, notes, and snippets.

@dhadka
Last active April 4, 2016 15:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhadka/a2db62c209ed1e2d90ef5eb25c9c4110 to your computer and use it in GitHub Desktop.
Save dhadka/a2db62c209ed1e2d90ef5eb25c9c4110 to your computer and use it in GitHub Desktop.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.moeaframework.core.FrameworkException;
import org.moeaframework.core.Problem;
import org.moeaframework.core.Solution;
import org.moeaframework.core.Variable;
import org.moeaframework.core.variable.BinaryVariable;
import org.moeaframework.core.variable.EncodingUtils;
import org.moeaframework.core.variable.Permutation;
import org.moeaframework.core.variable.RealVariable;
import org.moeaframework.problem.ProblemException;
public class MyProblem implements Problem {
private final int populationSize;
private final List<MySolution> solutions;
private final List<MyFuture> futures;
public MyProblem(int populationSize) {
super();
this.populationSize = populationSize;
solutions = new ArrayList<MySolution>();
futures = new ArrayList<MyFuture>();
}
@Override
public int getNumberOfVariables() {
return 11;
}
@Override
public int getNumberOfObjectives() {
return 2;
}
@Override
public int getNumberOfConstraints() {
return 0;
}
@Override
public Solution newSolution() {
Solution solution = new Solution(getNumberOfVariables(),
getNumberOfObjectives(),
getNumberOfConstraints());
for (int i = 0; i < getNumberOfVariables(); i++) {
solution.setVariable(i, EncodingUtils.newReal(0.0, 1.0));
}
return new MySolution(solution);
}
public void evaluateAll() {
try {
// create the input file
System.out.println("Writing input");
PrintWriter writer = null;
try {
writer = new PrintWriter(new File("input.txt"));
for (Solution s : solutions) {
for (int i = 0; i < s.getNumberOfVariables(); i++) {
if (i > 0) {
writer.print(" ");
}
writer.print(encode(s.getVariable(i)));
}
writer.println();
}
} finally {
if (writer != null) {
writer.close();
}
}
// execute your program
System.out.println("Executing program");
// Runs the program redirecting stdin and stdout to files
Process process = new ProcessBuilder("myprogram.exe")
.redirectInput(new File("input.txt"))
.redirectOutput(new File("output.txt"))
.start();
// Runs the program with two arguments indicating the input and output files
//Process process = new ProcessBuilder("myprogram.exe", "input.txt", "output.txt")
// .start();
try {
process.waitFor();
} catch (InterruptedException e) {
throw new FrameworkException(e);
}
// read the solutions
System.out.println("Reading output");
BufferedReader reader = null;
String line = null;
int index = 0;
try {
reader = new BufferedReader(new FileReader(new File("output.txt")));
while ((line = reader.readLine()) != null) {
String[] tokens = line.split("\\s+");
Solution s = solutions.get(index);
for (int i = 0; i < s.getNumberOfObjectives(); i++) {
s.setObjective(i, Double.parseDouble(tokens[i]));
}
for (int i = 0; i < s.getNumberOfConstraints(); i++) {
s.setConstraint(i, Double.parseDouble(tokens[i+s.getNumberOfObjectives()]));
}
futures.get(index).isDone = true;
index++;
}
} finally {
if (reader != null) {
reader.close();
}
}
System.out.println("Returning");
} catch (IOException e) {
throw new FrameworkException(e);
}
}
@Override
public void evaluate(Solution solution) {
if (solution instanceof MySolution) {
MySolution mySolution = (MySolution)solution;
MyFuture future = new MyFuture(mySolution);
mySolution.setFuture(future);
solutions.add(mySolution);
futures.add(future);
if (solutions.size() >= populationSize) {
evaluateAll();
solutions.clear();
futures.clear();
}
} else {
throw new ProblemException(this, "requires MySolution");
}
}
/**
* Convert the variable into a string.
*/
private String encode(Variable variable) throws IOException {
StringBuilder sb = new StringBuilder();
if (variable instanceof RealVariable) {
RealVariable rv = (RealVariable)variable;
sb.append(rv.getValue());
} else if (variable instanceof BinaryVariable) {
BinaryVariable bv = (BinaryVariable)variable;
for (int i=0; i<bv.getNumberOfBits(); i++) {
sb.append(bv.get(i) ? "1" : "0");
}
} else if (variable instanceof Permutation) {
Permutation p = (Permutation)variable;
for (int i=0; i<p.size(); i++) {
if (i > 0) {
sb.append(',');
}
sb.append(p.get(i));
}
} else {
throw new IOException("unable to serialize variable");
}
return sb.toString();
}
public static class MySolution extends Solution {
private static final long serialVersionUID = 4101855209843150768L;
private transient MyFuture future;
public MySolution(Solution solution) {
super(solution);
}
@Override
public MySolution copy() {
update();
return new MySolution(this);
}
synchronized void setFuture(MyFuture future) {
this.future = future;
}
private synchronized void update() {
if (future != null) {
try {
Solution solution = future.get();
future = null;
setObjectives(solution.getObjectives());
setConstraints(solution.getConstraints());
} catch (Exception e) {
throw new FrameworkException(e);
}
}
}
@Override
public double[] getObjectives() {
update();
return super.getObjectives();
}
@Override
public double getConstraint(int index) {
update();
return super.getConstraint(index);
}
@Override
public double[] getConstraints() {
update();
return super.getConstraints();
}
@Override
public double getObjective(int index) {
update();
return super.getObjective(index);
}
}
public static class MyFuture implements Future<Solution> {
private final Solution solution;
private boolean isDone = false;
public MyFuture(Solution solution) {
super();
this.solution = solution;
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return false;
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public boolean isDone() {
return isDone;
}
@Override
public Solution get() throws InterruptedException, ExecutionException {
while (!isDone) {
Thread.sleep(1000);
}
return solution;
}
@Override
public Solution get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
return get();
}
}
@Override
public String getName() {
return "MyProblem";
}
@Override
public void close() {
// do nothing
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment