Below is an example of task implementation, for the k-coloring optimization problem.
package com.decisionbrain.kcoloringworker;
import com.decisionbrain.kcoloringworker.model.Coloration;
import com.decisionbrain.kcoloringworker.model.Map;
import com.decisionbrain.optimserver.common.parameter.Parameter;
import com.decisionbrain.optimserver.worker.api.ExecutionContext;
import com.decisionbrain.optimserver.worker.api.Task;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import ilog.concert.IloException;
import ilog.concert.IloIntVar;
import ilog.cp.IloCP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class KColoringTask implements Task {
static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private static final Logger LOGGER = LoggerFactory.getLogger(KColoringTask.class);
@Override
public void execute(Parameter input, Parameter output, ExecutionContext context) {
// parse input k: the number of colors to be used for the coloration
int k = Integer.parseInt(new String(input.get("k")));
// create example map to be colored
Map exampleMap = Map.createExampleMap();
// create coloration to be filled in
Coloration coloration = new Coloration();
IloCP solver = new IloCP();
solver.setOut(new Utils.Log4jInfoStream(LOGGER));
solver.setWarning(new Utils.Log4jWarnStream(LOGGER));
solver.setError(new Utils.Log4jErrorStream(LOGGER));
try {
// create variables
for(String country : exampleMap.getCountries()) {
solver.add(solver.intVar(1, k, country));
}
// create constraints
for(String country : exampleMap.getCountries()) {
for(String adjacentCountry : exampleMap.getAdjacentCountries(country)) {
solver.add(solver.neq(solver.getIloIntVar(country), solver.getIloIntVar(adjacentCountry)));
}
}
solver.startNewSearch();
int nbSolutions = 0;
while(!context.shouldAbort() && solver.next()) { // stop if the user asked for job abortion
nbSolutions++;
}
solver.endSearch();
if(nbSolutions > 0) {
// retrieve solution
IloIntVar[] vars = solver.getAllIloIntVars();
for (IloIntVar var : vars) {
coloration.setColor(var.getName(), (int) solver.getValue(var));
}
}
} catch (IloException e) {
LOGGER.warn("Error during model creation or resolution: ", e);
}
solver.end();
// send coloration output
LOGGER.info("Coloration found: {}", coloration);
try {
output.emit("coloration", OBJECT_MAPPER.writeValueAsBytes(coloration));
} catch (JsonProcessingException e) {
LOGGER.error("Error when serializing coloration output: ", e);
}
}
}