package org.opt4j.addons; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.StringTokenizer; import org.opt4j.benchmark.DoubleString; import org.opt4j.benchmark.M; import org.opt4j.core.Objective; import org.opt4j.core.Objectives; import org.opt4j.core.problem.Evaluator; import org.opt4j.start.Constant; import com.google.inject.Inject; public class ExternalRuntimeEvaluator implements Evaluator { protected final String command; protected final double upperBound; protected final double lowerBound; protected final List objectives = new ArrayList(); @Inject public ExternalRuntimeEvaluator( @Constant(namespace = ExternalRuntimeEvaluator.class, value = "command") String command, @Constant(namespace = ExternalRuntimeEvaluator.class, value = "lowerBound") double lowerBound, @Constant(namespace = ExternalRuntimeEvaluator.class, value = "upperBound") double upperBound, @Constant(namespace = ExternalRuntimeEvaluator.class, value = "sign") Objective.Sign sign, @M int nObjectives) { this.command = command; this.lowerBound = lowerBound; this.upperBound = upperBound; for (int i = 0; i < nObjectives; i++) { objectives.add(new Objective("objective " + i, sign)); } } @Override public Objectives evaluate(DoubleString doubleString) { String cmd = command.trim(); for (double value : doubleString) { double v = lowerBound + value * (upperBound - lowerBound); cmd += " " + v; } try { Process process = Runtime.getRuntime().exec(cmd); process.waitFor(); String instr = ""; InputStream in = process.getInputStream(); int c; while ((c = in.read()) != -1) { instr += ((char) c); } in.close(); StringTokenizer tokenizer = new StringTokenizer(instr); Objectives objectives = new Objectives(); for (Objective obj : this.objectives) { objectives.add(obj, Double.parseDouble(tokenizer.nextToken())); } return objectives; } catch (Exception e) { throw new RuntimeException(e); } } @Override public Collection getObjectives() { return objectives; } }