reindent java code

This commit is contained in:
Laurent Perron
2018-11-10 23:43:32 +01:00
parent 333cf82f0f
commit 837cdbbbc8
22 changed files with 292 additions and 325 deletions

View File

@@ -48,12 +48,10 @@ class Pair<K, V> {
public class CapacitatedVehicleRoutingProblemWithTimeWindows {
static {
System.loadLibrary("jniortools");
}
static { System.loadLibrary("jniortools"); }
private static Logger logger =
Logger.getLogger(CapacitatedVehicleRoutingProblemWithTimeWindows.class.getName());
private static Logger logger = Logger.getLogger(
CapacitatedVehicleRoutingProblemWithTimeWindows.class.getName());
// Locations representing either an order location or a vehicle route
// start/end.
@@ -103,13 +101,9 @@ public class CapacitatedVehicleRoutingProblemWithTimeWindows {
* @param penaltyMin minimum pernalty cost if order is dropped.
* @param penaltyMax maximum pernalty cost if order is dropped.
*/
private void buildOrders(int numberOfOrders,
int xMax, int yMax,
int demandMax,
int timeWindowMin,
int timeWindowMax,
int timeWindowWidth,
int penaltyMin,
private void buildOrders(int numberOfOrders, int xMax, int yMax,
int demandMax, int timeWindowMin, int timeWindowMax,
int timeWindowWidth, int penaltyMin,
int penaltyMax) {
logger.info("Building orders.");
for (int order = 0; order < numberOfOrders; ++order) {
@@ -118,9 +112,13 @@ public class CapacitatedVehicleRoutingProblemWithTimeWindows {
orderDemands.add(randomGenerator.nextInt(demandMax + 1));
/** @todo 1) Specify deliver duration for each shipment*/
orderDurations.add(2); // in minutes
int timeWindowStart = randomGenerator.nextInt(timeWindowMax - timeWindowMin) + timeWindowMin;
orderTimeWindows.add(Pair.of(timeWindowStart, timeWindowStart + timeWindowWidth));
orderPenalties.add(randomGenerator.nextInt(penaltyMax - penaltyMin + 1) + penaltyMin);
int timeWindowStart =
randomGenerator.nextInt(timeWindowMax - timeWindowMin) +
timeWindowMin;
orderTimeWindows.add(
Pair.of(timeWindowStart, timeWindowStart + timeWindowWidth));
orderPenalties.add(randomGenerator.nextInt(penaltyMax - penaltyMin + 1) +
penaltyMin);
}
}
@@ -137,11 +135,8 @@ public class CapacitatedVehicleRoutingProblemWithTimeWindows {
* @param costCoefficientMax maximum cost per distance unit of a vehicle
* (mimimum is 1),
*/
private void buildFleet(int numberOfVehicles,
int xMax, int yMax,
int startTime,
int endTime,
int capacity,
private void buildFleet(int numberOfVehicles, int xMax, int yMax,
int startTime, int endTime, int capacity,
int costCoefficientMax) {
logger.info("Building fleet.");
vehicleCapacity = capacity;
@@ -156,7 +151,8 @@ public class CapacitatedVehicleRoutingProblemWithTimeWindows {
randomGenerator.nextInt(yMax + 1)));
vehicleStartTime.add(startTime);
vehicleEndTime.add(endTime);
vehicleCostCoefficients.add(randomGenerator.nextInt(costCoefficientMax) + 1);
vehicleCostCoefficients.add(randomGenerator.nextInt(costCoefficientMax) +
1);
}
}
@@ -165,83 +161,84 @@ public class CapacitatedVehicleRoutingProblemWithTimeWindows {
*/
private void solve(final int numberOfOrders, final int numberOfVehicles) {
logger.info("Creating model with " + numberOfOrders + " orders and " +
numberOfVehicles + " vehicles.");
numberOfVehicles + " vehicles.");
// Finalizing model
final int numberOfLocations = locations.size();
RoutingModel model =
new RoutingModel(numberOfLocations, numberOfVehicles,
vehicleStarts, vehicleEnds);
RoutingModel model = new RoutingModel(numberOfLocations, numberOfVehicles,
vehicleStarts, vehicleEnds);
// Setting up dimensions
final int bigNumber = 100000;
NodeEvaluator2 timeCallback = new NodeEvaluator2(){
@Override
public long run(int firstIndex, int secondIndex) {
try {
Pair<Integer, Integer> firstLocation = locations.get(firstIndex);
Pair<Integer, Integer> secondLocation = locations.get(secondIndex);
Integer distance = 0;
Integer duration = 0;
distance = Math.abs(firstLocation.first - secondLocation.first) +
Math.abs(firstLocation.second - secondLocation.second);
// Deal with Order duration shipment
if (firstIndex < numberOfOrders) {
// shipment duration
duration += orderDurations.get(firstIndex);
}
return distance + duration;
} catch (Throwable throwed) {
logger.warning(throwed.getMessage());
return 0;
NodeEvaluator2 timeCallback = new NodeEvaluator2() {
@Override
public long run(int firstIndex, int secondIndex) {
try {
Pair<Integer, Integer> firstLocation = locations.get(firstIndex);
Pair<Integer, Integer> secondLocation = locations.get(secondIndex);
Integer distance = 0;
Integer duration = 0;
distance = Math.abs(firstLocation.first - secondLocation.first) +
Math.abs(firstLocation.second - secondLocation.second);
// Deal with Order duration shipment
if (firstIndex < numberOfOrders) {
// shipment duration
duration += orderDurations.get(firstIndex);
}
return distance + duration;
} catch (Throwable throwed) {
logger.warning(throwed.getMessage());
return 0;
}
};
}
};
model.addDimension(timeCallback, bigNumber, bigNumber, false, "time");
NodeEvaluator2 demandCallback = new NodeEvaluator2(){
@Override
public long run(int firstIndex, int secondIndex) {
try {
if (firstIndex < numberOfOrders) {
return orderDemands.get(firstIndex);
}
return 0;
} catch (Throwable throwed) {
logger.warning(throwed.getMessage());
return 0;
NodeEvaluator2 demandCallback = new NodeEvaluator2() {
@Override
public long run(int firstIndex, int secondIndex) {
try {
if (firstIndex < numberOfOrders) {
return orderDemands.get(firstIndex);
}
return 0;
} catch (Throwable throwed) {
logger.warning(throwed.getMessage());
return 0;
}
};
}
};
model.addDimension(demandCallback, 0, vehicleCapacity, true, "capacity");
// Setting up vehicles
for (int vehicle = 0; vehicle < numberOfVehicles; ++vehicle) {
final int costCoefficient = vehicleCostCoefficients.get(vehicle);
NodeEvaluator2 manhattanCostCallback = new NodeEvaluator2() {
@Override
public long run(int firstIndex, int secondIndex) {
try {
Pair<Integer, Integer> firstLocation = locations.get(firstIndex);
Pair<Integer, Integer> secondLocation = locations.get(secondIndex);
return costCoefficient *
(Math.abs(firstLocation.first - secondLocation.first) +
Math.abs(firstLocation.second - secondLocation.second));
} catch (Throwable throwed) {
logger.warning(throwed.getMessage());
return 0;
}
@Override
public long run(int firstIndex, int secondIndex) {
try {
Pair<Integer, Integer> firstLocation = locations.get(firstIndex);
Pair<Integer, Integer> secondLocation = locations.get(secondIndex);
return costCoefficient *
(Math.abs(firstLocation.first - secondLocation.first) +
Math.abs(firstLocation.second - secondLocation.second));
} catch (Throwable throwed) {
logger.warning(throwed.getMessage());
return 0;
}
};
}
};
model.setArcCostEvaluatorOfVehicle(manhattanCostCallback, vehicle);
model.cumulVar(model.start(vehicle), "time").setMin(vehicleStartTime.get(vehicle));
model.cumulVar(model.end(vehicle), "time").setMax(vehicleEndTime.get(vehicle));
model.cumulVar(model.start(vehicle), "time")
.setMin(vehicleStartTime.get(vehicle));
model.cumulVar(model.end(vehicle), "time")
.setMax(vehicleEndTime.get(vehicle));
}
// Setting up orders
for (int order = 0; order < numberOfOrders; ++order) {
model.cumulVar(model.nodeToIndex(order), "time").setRange(
orderTimeWindows.get(order).first,
orderTimeWindows.get(order).second);
model.cumulVar(model.nodeToIndex(order), "time")
.setRange(orderTimeWindows.get(order).first,
orderTimeWindows.get(order).second);
int[] orders = {order};
model.addDisjunction(orders, orderPenalties.get(order));
}
@@ -249,9 +246,10 @@ public class CapacitatedVehicleRoutingProblemWithTimeWindows {
// Solving
RoutingSearchParameters parameters =
RoutingSearchParameters.newBuilder()
.mergeFrom(RoutingModel.defaultSearchParameters())
.setFirstSolutionStrategy(FirstSolutionStrategy.Value.PATH_CHEAPEST_ARC)
.build();
.mergeFrom(RoutingModel.defaultSearchParameters())
.setFirstSolutionStrategy(
FirstSolutionStrategy.Value.PATH_CHEAPEST_ARC)
.build();
logger.info("Search");
Assignment solution = model.solveWithParameters(parameters);
@@ -277,19 +275,19 @@ public class CapacitatedVehicleRoutingProblemWithTimeWindows {
route += "/!\\Empty Route/!\\ ";
}
{
for (;
!model.isEnd(order);
order = solution.value(model.nextVar(order))) {
for (; !model.isEnd(order);
order = solution.value(model.nextVar(order))) {
IntVar load = model.cumulVar(order, "capacity");
IntVar time = model.cumulVar(order, "time");
route += order + " Load(" + solution.value(load) + ") " +
"Time(" + solution.min(time) + ", " + solution.max(time) +
") -> ";
route += order + " Load(" + solution.value(load) + ") "
+ "Time(" + solution.min(time) + ", " +
solution.max(time) + ") -> ";
}
IntVar load = model.cumulVar(order, "capacity");
IntVar time = model.cumulVar(order, "time");
route += order + " Load(" + solution.value(load) + ") " +
"Time(" + solution.min(time) + ", " + solution.max(time) + ")";
route += order + " Load(" + solution.value(load) + ") "
+ "Time(" + solution.min(time) + ", " + solution.max(time) +
")";
}
output += route + "\n";
}
@@ -320,21 +318,9 @@ public class CapacitatedVehicleRoutingProblemWithTimeWindows {
final int vehicles = 20;
final int capacity = 50;
problem.buildOrders(orders,
xMax,
yMax,
demandMax,
timeWindowMin,
timeWindowMax,
timeWindowWidth,
penaltyMin,
penaltyMax);
problem.buildFleet(vehicles,
xMax,
yMax,
startTime,
endTime,
capacity,
problem.buildOrders(orders, xMax, yMax, demandMax, timeWindowMin,
timeWindowMax, timeWindowWidth, penaltyMin, penaltyMax);
problem.buildFleet(vehicles, xMax, yMax, startTime, endTime, capacity,
costCoefficientMax);
problem.solve(orders, vehicles);
}

View File

@@ -21,10 +21,7 @@ import com.google.ortools.graph.MinCostFlow;
public class FlowExample {
static {
System.loadLibrary("jniortools");
}
static { System.loadLibrary("jniortools"); }
private static void solveMinCostFlow() {
System.out.println("Min Cost Flow Problem - Simple interface");
@@ -38,8 +35,8 @@ public class FlowExample {
MinCostFlow minCostFlow = new MinCostFlow();
for (int source = 0; source < numSources; ++source) {
for (int target = 0; target < numTargets; ++target) {
minCostFlow.addArcWithCapacityAndUnitCost(
source, numSources + target, 1, costs[source][target]);
minCostFlow.addArcWithCapacityAndUnitCost(source, numSources + target,
1, costs[source][target]);
}
}
for (int node = 0; node < numSources; ++node) {
@@ -51,9 +48,9 @@ public class FlowExample {
System.out.println("total flow = " + totalFlowCost + "/" + expectedCost);
for (int i = 0; i < minCostFlow.getNumArcs(); ++i) {
if (minCostFlow.getFlow(i) > 0) {
System.out.println("From source " + minCostFlow.getTail(i)
+ " to target " + minCostFlow.getHead(i) + ": cost "
+ minCostFlow.getUnitCost(i));
System.out.println("From source " + minCostFlow.getTail(i) +
" to target " + minCostFlow.getHead(i) +
": cost " + minCostFlow.getUnitCost(i));
}
}
} else {
@@ -72,11 +69,12 @@ public class FlowExample {
maxFlow.addArcWithCapacity(tails[i], heads[i], capacities[i]);
}
if (maxFlow.solve(0, 5) == MaxFlow.Status.OPTIMAL) {
System.out.println("Total flow " + maxFlow.getOptimalFlow() + "/" + expectedTotalFlow);
System.out.println("Total flow " + maxFlow.getOptimalFlow() + "/" +
expectedTotalFlow);
for (int i = 0; i < maxFlow.getNumArcs(); ++i) {
System.out.println("From source " + maxFlow.getTail(i)
+ " to target " + maxFlow.getHead(i) + ": "
+ maxFlow.getFlow(i) + " / " + maxFlow.getCapacity(i));
System.out.println("From source " + maxFlow.getTail(i) + " to target " +
maxFlow.getHead(i) + ": " + maxFlow.getFlow(i) +
" / " + maxFlow.getCapacity(i));
}
// TODO(user): Our SWIG configuration does not currently handle these
// functions correctly in Java:

View File

@@ -24,12 +24,12 @@ import com.google.ortools.linearsolver.MPVariable;
public class IntegerProgramming {
static { System.loadLibrary("jniortools"); }
private static MPSolver createSolver (String solverType) {
private static MPSolver createSolver(String solverType) {
try {
return new MPSolver("IntegerProgrammingExample",
MPSolver.OptimizationProblemType.valueOf(solverType));
} catch (java.lang.IllegalArgumentException e) {
System.err.println("Bad solver type: " + e);
System.err.println("Bad solver type: " + e);
return null;
}
}
@@ -71,22 +71,25 @@ public class IntegerProgramming {
return;
}
System.out.println("Problem solved in " + solver.wallTime() + " milliseconds");
System.out.println("Problem solved in " + solver.wallTime() +
" milliseconds");
// The objective value of the solution.
System.out.println("Optimal objective value = " + solver.objective().value());
System.out.println("Optimal objective value = " +
solver.objective().value());
// The value of each variable in the solution.
System.out.println("x1 = " + x1.solutionValue());
System.out.println("x2 = " + x2.solutionValue());
System.out.println("Advanced usage:");
System.out.println("Problem solved in " + solver.nodes() + " branch-and-bound nodes");
System.out.println("Problem solved in " + solver.nodes() +
" branch-and-bound nodes");
}
public static void main(String[] args) throws Exception {
System.out.println("---- Integer programming example with SCIP (recommended) ----");
System.out.println(
"---- Integer programming example with SCIP (recommended) ----");
runIntegerProgrammingExample("SCIP_MIXED_INTEGER_PROGRAMMING");
System.out.println("---- Integer programming example with CBC ----");
runIntegerProgrammingExample("CBC_MIXED_INTEGER_PROGRAMMING");

View File

@@ -22,21 +22,20 @@ public class Knapsack {
static { System.loadLibrary("jniortools"); }
private static void solve() {
KnapsackSolver solver = new KnapsackSolver(
KnapsackSolver.SolverType.KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER, "test");
final long[] profits = {360, 83, 59, 130, 431, 67, 230, 52, 93,
125, 670, 892, 600, 38, 48, 147, 78, 256,
63, 17, 120, 164, 432, 35, 92, 110, 22,
42, 50, 323, 514, 28, 87, 73, 78, 15,
26, 78, 210, 36, 85, 189, 274, 43, 33,
10, 19, 389, 276, 312};
KnapsackSolver solver =
new KnapsackSolver(KnapsackSolver.SolverType
.KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER,
"test");
final long[] profits = {360, 83, 59, 130, 431, 67, 230, 52, 93, 125,
670, 892, 600, 38, 48, 147, 78, 256, 63, 17,
120, 164, 432, 35, 92, 110, 22, 42, 50, 323,
514, 28, 87, 73, 78, 15, 26, 78, 210, 36,
85, 189, 274, 43, 33, 10, 19, 389, 276, 312};
final long[][] weights = {{7, 0, 30, 22, 80, 94, 11, 81, 70,
64, 59, 18, 0, 36, 3, 8, 15, 42,
9, 0, 42, 47, 52, 32, 26, 48, 55,
6, 29, 84, 2, 4, 18, 56, 7, 29,
93, 44, 71, 3, 86, 66, 31, 65, 0,
79, 20, 65, 52, 13}};
final long[][] weights = {
{7, 0, 30, 22, 80, 94, 11, 81, 70, 64, 59, 18, 0, 36, 3, 8, 15,
42, 9, 0, 42, 47, 52, 32, 26, 48, 55, 6, 29, 84, 2, 4, 18, 56,
7, 29, 93, 44, 71, 3, 86, 66, 31, 65, 0, 79, 20, 65, 52, 13}};
final long[] capacities = {850};
@@ -51,7 +50,5 @@ public class Knapsack {
optimalProfit);
}
public static void main(String[] args) throws Exception {
Knapsack.solve();
}
public static void main(String[] args) throws Exception { Knapsack.solve(); }
}

View File

@@ -22,18 +22,15 @@ import com.google.ortools.graph.LinearSumAssignment;
public class LinearAssignmentAPI {
static {
System.loadLibrary("jniortools");
}
static { System.loadLibrary("jniortools"); }
private static void runAssignmentOn4x4Matrix() {
final int numSources = 4;
final int numTargets = 4;
final int[][] cost = {{ 90, 76, 75, 80 },
{ 35, 85, 55, 65 },
{ 125, 95, 90, 105 },
{ 45, 110, 95, 115 }};
final int[][] cost = {{90, 76, 75, 80},
{35, 85, 55, 65},
{125, 95, 90, 105},
{45, 110, 95, 115}};
final int expectedCost = cost[0][3] + cost[1][2] + cost[2][1] + cost[3][0];
LinearSumAssignment assignment = new LinearSumAssignment();
@@ -44,11 +41,12 @@ public class LinearAssignmentAPI {
}
if (assignment.solve() == LinearSumAssignment.Status.OPTIMAL) {
System.out.println("Total cost = " + assignment.getOptimalCost() + "/" + expectedCost);
System.out.println("Total cost = " + assignment.getOptimalCost() + "/" +
expectedCost);
for (int node = 0; node < assignment.getNumNodes(); ++node) {
System.out.println("Left node " + node
+ " assigned to right node " + assignment.getRightMate(node)
+ " with cost " + assignment.getAssignmentCost(node));
System.out.println("Left node " + node + " assigned to right node " +
assignment.getRightMate(node) + " with cost " +
assignment.getAssignmentCost(node));
}
} else {
System.out.println("No solution found.");

View File

@@ -24,7 +24,7 @@ import com.google.ortools.linearsolver.MPVariable;
public class LinearProgramming {
static { System.loadLibrary("jniortools"); }
private static MPSolver createSolver (String solverType) {
private static MPSolver createSolver(String solverType) {
try {
return new MPSolver("LinearProgrammingExample",
MPSolver.OptimizationProblemType.valueOf(solverType));
@@ -95,10 +95,12 @@ public class LinearProgramming {
return;
}
System.out.println("Problem solved in " + solver.wallTime() + " milliseconds");
System.out.println("Problem solved in " + solver.wallTime() +
" milliseconds");
// The objective value of the solution.
System.out.println("Optimal objective value = " + solver.objective().value());
System.out.println("Optimal objective value = " +
solver.objective().value());
// The value of each variable in the solution.
System.out.println("x1 = " + x1.solutionValue());
@@ -108,7 +110,8 @@ public class LinearProgramming {
final double[] activities = solver.computeConstraintActivities();
System.out.println("Advanced usage:");
System.out.println("Problem solved in " + solver.iterations() + " iterations");
System.out.println("Problem solved in " + solver.iterations() +
" iterations");
System.out.println("x1: reduced cost = " + x1.reducedCost());
System.out.println("x2: reduced cost = " + x2.reducedCost());
System.out.println("x3: reduced cost = " + x3.reducedCost());
@@ -121,7 +124,8 @@ public class LinearProgramming {
}
public static void main(String[] args) throws Exception {
System.out.println("---- Linear programming example with GLOP (recommended) ----");
System.out.println(
"---- Linear programming example with GLOP (recommended) ----");
runLinearProgrammingExample("GLOP_LINEAR_PROGRAMMING", true);
System.out.println("---- Linear programming example with CLP ----");
runLinearProgrammingExample("CLP_LINEAR_PROGRAMMING", false);

View File

@@ -30,16 +30,10 @@ import com.google.ortools.constraintsolver.Solver;
*/
public class LsApi {
static {
System.loadLibrary("jniortools");
}
static { System.loadLibrary("jniortools"); }
static class OneVarLns extends BaseLns {
public OneVarLns(IntVar[] vars) {
super(vars);
}
public OneVarLns(IntVar[] vars) { super(vars); }
@Override
public void initFragments() {
@@ -133,10 +127,11 @@ public class LsApi {
IntVar[] vars = solver.makeIntVarArray(4, 0, 4, "vars");
IntVar sumVar = solver.makeSum(vars).var();
OptimizeVar obj = solver.makeMinimize(sumVar, 1);
DecisionBuilder db =
solver.makePhase(vars, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MAX_VALUE);
DecisionBuilder db = solver.makePhase(vars, Solver.CHOOSE_FIRST_UNBOUND,
Solver.ASSIGN_MAX_VALUE);
OneVarLns oneVarLns = new OneVarLns(vars);
LocalSearchPhaseParameters lsParams = solver.makeLocalSearchPhaseParameters(oneVarLns, db);
LocalSearchPhaseParameters lsParams =
solver.makeLocalSearchPhaseParameters(oneVarLns, db);
DecisionBuilder ls = solver.makeLocalSearchPhase(vars, db, lsParams);
SolutionCollector collector = solver.makeLastSolutionCollector();
collector.addObjective(sumVar);
@@ -151,10 +146,11 @@ public class LsApi {
IntVar[] vars = solver.makeIntVarArray(4, 0, 4, "vars");
IntVar sumVar = solver.makeSum(vars).var();
OptimizeVar obj = solver.makeMinimize(sumVar, 1);
DecisionBuilder db =
solver.makePhase(vars, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MAX_VALUE);
DecisionBuilder db = solver.makePhase(vars, Solver.CHOOSE_FIRST_UNBOUND,
Solver.ASSIGN_MAX_VALUE);
MoveOneVar moveOneVar = new MoveOneVar(vars);
LocalSearchPhaseParameters lsParams = solver.makeLocalSearchPhaseParameters(moveOneVar, db);
LocalSearchPhaseParameters lsParams =
solver.makeLocalSearchPhaseParameters(moveOneVar, db);
DecisionBuilder ls = solver.makeLocalSearchPhase(vars, db, lsParams);
SolutionCollector collector = solver.makeLastSolutionCollector();
collector.addObjective(sumVar);
@@ -169,8 +165,8 @@ public class LsApi {
IntVar[] vars = solver.makeIntVarArray(4, 0, 4, "vars");
IntVar sumVar = solver.makeSum(vars).var();
OptimizeVar obj = solver.makeMinimize(sumVar, 1);
DecisionBuilder db =
solver.makePhase(vars, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MAX_VALUE);
DecisionBuilder db = solver.makePhase(vars, Solver.CHOOSE_FIRST_UNBOUND,
Solver.ASSIGN_MAX_VALUE);
MoveOneVar moveOneVar = new MoveOneVar(vars);
SumFilter filter = new SumFilter(vars);
IntVarLocalSearchFilter[] filters = new IntVarLocalSearchFilter[1];

View File

@@ -22,12 +22,10 @@ import java.util.logging.Logger;
*
*/
public class RabbitsPheasants {
private static Logger logger = Logger.getLogger(RabbitsPheasants.class.getName());
static {
System.loadLibrary("jniortools");
}
private static Logger logger =
Logger.getLogger(RabbitsPheasants.class.getName());
static { System.loadLibrary("jniortools"); }
/**
* Solves the rabbits + pheasants problem. We are seing 20 heads
@@ -43,12 +41,15 @@ public class RabbitsPheasants {
Solver solver = new Solver("RabbitsPheasants", parameters);
IntVar rabbits = solver.makeIntVar(0, 100, "rabbits");
IntVar pheasants = solver.makeIntVar(0, 100, "pheasants");
solver.addConstraint(solver.makeEquality(solver.makeSum(rabbits, pheasants), 20));
solver.addConstraint(
solver.makeEquality(
solver.makeSum(solver.makeProd(rabbits, 4), solver.makeProd(pheasants, 2)), 56));
solver.makeEquality(solver.makeSum(rabbits, pheasants), 20));
solver.addConstraint(
solver.makeEquality(solver.makeSum(solver.makeProd(rabbits, 4),
solver.makeProd(pheasants, 2)),
56));
DecisionBuilder db =
solver.makePhase(rabbits, pheasants, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE);
solver.makePhase(rabbits, pheasants, Solver.CHOOSE_FIRST_UNBOUND,
Solver.ASSIGN_MIN_VALUE);
solver.newSearch(db);
solver.nextSolution();
logger.info(rabbits.toString());

View File

@@ -23,9 +23,7 @@ import com.google.ortools.constraintsolver.FirstSolutionStrategy;
import com.google.ortools.constraintsolver.RoutingSearchParameters;
class Tsp {
static {
System.loadLibrary("jniortools");
}
static { System.loadLibrary("jniortools"); }
static class RandomManhattan extends NodeEvaluator2 {
public RandomManhattan(int size, int seed) {
@@ -55,8 +53,7 @@ class Tsp {
}
}
static void solve(int size, int forbidden, int seed)
{
static void solve(int size, int forbidden, int seed) {
RoutingModel routing = new RoutingModel(size, 1, 0);
// Setting the cost function.
@@ -80,19 +77,16 @@ class Tsp {
}
// Add dummy dimension to test API.
routing.addDimension(
new ConstantCallback(),
size + 1,
size + 1,
true,
"dummy");
routing.addDimension(new ConstantCallback(), size + 1, size + 1, true,
"dummy");
// Solve, returns a solution if any (owned by RoutingModel).
RoutingSearchParameters search_parameters =
RoutingSearchParameters.newBuilder()
.mergeFrom(RoutingModel.defaultSearchParameters())
.setFirstSolutionStrategy(FirstSolutionStrategy.Value.PATH_CHEAPEST_ARC)
.build();
.mergeFrom(RoutingModel.defaultSearchParameters())
.setFirstSolutionStrategy(
FirstSolutionStrategy.Value.PATH_CHEAPEST_ARC)
.build();
Assignment solution = routing.solveWithParameters(search_parameters);
if (solution != null) {
@@ -101,8 +95,7 @@ class Tsp {
// Inspect solution.
// Only one route here; otherwise iterate from 0 to routing.vehicles() - 1
int route_number = 0;
for (long node = routing.start(route_number);
!routing.isEnd(node);
for (long node = routing.start(route_number); !routing.isEnd(node);
node = solution.value(routing.nextVar(node))) {
System.out.print("" + node + " -> ");
}

View File

@@ -24,37 +24,29 @@ class DataProblem {
private int[][] locations_;
public DataProblem() {
locations_ = new int[][] {
{4, 4},
{2, 0}, {8, 0},
{0, 1}, {1, 1},
{5, 2}, {7, 2},
{3, 3}, {6, 3},
{5, 5}, {8, 5},
{1, 6}, {2, 6},
{3, 7}, {6, 7},
{0, 8}, {7, 8}
};
locations_ = new int[][] {{4, 4}, {2, 0}, {8, 0}, {0, 1}, {1, 1}, {5, 2},
{7, 2}, {3, 3}, {6, 3}, {5, 5}, {8, 5}, {1, 6},
{2, 6}, {3, 7}, {6, 7}, {0, 8}, {7, 8}};
// Compute locations in meters using the block dimension defined as follow
// Manhattan average block: 750ft x 264ft -> 228m x 80m
// here we use: 114m x 80m city block
// src: https://nyti.ms/2GDoRIe "NY Times: Know Your distance"
int[] cityBlock = {228/2, 80};
for (int i=0; i < locations_.length; i++) {
int[] cityBlock = {228 / 2, 80};
for (int i = 0; i < locations_.length; i++) {
locations_[i][0] = locations_[i][0] * cityBlock[0];
locations_[i][1] = locations_[i][1] * cityBlock[1];
}
}
/// @brief Gets the number of vehicles.
public int getVehicleNumber() { return 4;}
public int getVehicleNumber() { return 4; }
/// @brief Gets the locations.
public int[][] getLocations() { return locations_;}
public int[][] getLocations() { return locations_; }
/// @brief Gets the number of locations.
public int getLocationNumber() { return locations_.length;}
public int getLocationNumber() { return locations_.length; }
/// @brief Gets the depot NodeIndex.
public int getDepot() { return 0;}
public int getDepot() { return 0; }
}
/// @brief Manhattan distance implemented as a callback.
@@ -72,9 +64,10 @@ class ManhattanDistance extends NodeEvaluator2 {
if (fromNode == toNode)
distances_[fromNode][toNode] = 0;
else
distances_[fromNode][toNode] =
abs(data.getLocations()[toNode][0] - data.getLocations()[fromNode][0]) +
abs(data.getLocations()[toNode][1] - data.getLocations()[fromNode][1]);
distances_[fromNode][toNode] = abs(data.getLocations()[toNode][0] -
data.getLocations()[fromNode][0]) +
abs(data.getLocations()[toNode][1] -
data.getLocations()[fromNode][1]);
}
}
}
@@ -87,19 +80,16 @@ class ManhattanDistance extends NodeEvaluator2 {
}
class Vrp {
static {
System.loadLibrary("jniortools");
}
static { System.loadLibrary("jniortools"); }
/// @brief Add Global Span constraint.
static void addDistanceDimension(RoutingModel routing, DataProblem data) {
String distance = "Distance";
routing.addDimension(
new ManhattanDistance(data),
0, // null slack
3000, // maximum distance per vehicle
true, // start cumul to zero
distance);
routing.addDimension(new ManhattanDistance(data),
0, // null slack
3000, // maximum distance per vehicle
true, // start cumul to zero
distance);
RoutingDimension distanceDimension = routing.getDimensionOrDie(distance);
// Try to minimize the max distance among vehicles.
// /!\ It doesn't mean the standard deviation is minimized
@@ -107,20 +97,15 @@ class Vrp {
}
/// @brief Print the solution
static void printSolution(
DataProblem data,
RoutingModel routing,
Assignment solution)
{
static void printSolution(DataProblem data, RoutingModel routing,
Assignment solution) {
// Solution cost.
System.out.println("Objective : " + solution.objectiveValue());
// Inspect solution.
for (int i=0; i < data.getVehicleNumber(); ++i) {
for (int i = 0; i < data.getVehicleNumber(); ++i) {
System.out.println("Route for Vehicle " + i + ":");
long distance = 0;
for (long index = routing.start(i);
!routing.isEnd(index);)
{
for (long index = routing.start(i); !routing.isEnd(index);) {
System.out.print(routing.indexToNode(index) + " -> ");
long previousIndex = index;
@@ -139,9 +124,7 @@ class Vrp {
// Create Routing Model
RoutingModel routing = new RoutingModel(
data.getLocationNumber(),
data.getVehicleNumber(),
data.getDepot());
data.getLocationNumber(), data.getVehicleNumber(), data.getDepot());
// Setting the cost function.
// [todo]: protect callback from the GC
@@ -151,17 +134,16 @@ class Vrp {
// Setting first solution heuristic (cheapest addition).
RoutingSearchParameters search_parameters =
RoutingSearchParameters.newBuilder()
.mergeFrom(RoutingModel.defaultSearchParameters())
.setFirstSolutionStrategy(FirstSolutionStrategy.Value.PATH_CHEAPEST_ARC)
.build();
RoutingSearchParameters.newBuilder()
.mergeFrom(RoutingModel.defaultSearchParameters())
.setFirstSolutionStrategy(
FirstSolutionStrategy.Value.PATH_CHEAPEST_ARC)
.build();
Assignment solution = routing.solveWithParameters(search_parameters);
printSolution(data, routing, solution);
}
/// @brief Entry point of the program.
public static void main(String[] args) throws Exception {
solve();
}
public static void main(String[] args) throws Exception { solve(); }
}