repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
or-tools
or-tools-master/examples/contrib/SurvoPuzzle.java
// Copyright 2011 Hakan Kjellerstrand hakank@gmail.com // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.contrib; import com.google.ortools.Loader; import com.google.ortools.constraintsolver.*; import com.google.ortools.constraintsolver.DecisionBuilder; import com.google.ortools.constraintsolver.IntVar; import com.google.ortools.constraintsolver.Solver; import java.io.*; import java.text.*; import java.util.*; public class SurvoPuzzle { /* default problem */ static int default_r = 3; static int default_c = 4; static int[] default_rowsums = {30, 18, 30}; static int[] default_colsums = {27, 16, 10, 25}; static int[][] default_game = {{0, 6, 0, 0}, {8, 0, 0, 0}, {0, 0, 3, 0}}; // for the actual problem static int r; static int c; static int[] rowsums; static int[] colsums; static int[][] game; /** Solves the Survo puzzle problem. See http://www.hakank.org/google_or_tools/survo_puzzle.py */ private static void solve() { Solver solver = new Solver("Survopuzzle"); // // data // System.out.println("Problem:"); for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { System.out.print(game[i][j] + " "); } System.out.println(); } System.out.println(); // // Variables // IntVar[][] x = new IntVar[r][c]; IntVar[] x_flat = new IntVar[r * c]; // for branching for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { x[i][j] = solver.makeIntVar(1, r * c, "x[" + i + "," + j + "]"); x_flat[i * c + j] = x[i][j]; } } // // Constraints // for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { if (game[i][j] > 0) { solver.addConstraint(solver.makeEquality(x[i][j], game[i][j])); } } } solver.addConstraint(solver.makeAllDifferent(x_flat)); // // calculate rowsums and colsums // for (int i = 0; i < r; i++) { IntVar[] row = new IntVar[c]; for (int j = 0; j < c; j++) { row[j] = x[i][j]; } solver.addConstraint(solver.makeEquality(solver.makeSum(row).var(), rowsums[i])); } for (int j = 0; j < c; j++) { IntVar[] col = new IntVar[r]; for (int i = 0; i < r; i++) { col[i] = x[i][j]; } solver.addConstraint(solver.makeEquality(solver.makeSum(col).var(), colsums[j])); } // // Search // DecisionBuilder db = solver.makePhase(x_flat, solver.INT_VAR_SIMPLE, solver.ASSIGN_MIN_VALUE); solver.newSearch(db); int sol = 0; while (solver.nextSolution()) { sol++; System.out.println("Solution #" + sol + ":"); for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { System.out.print(x[i][j].value() + " "); } System.out.println(); } System.out.println(); } solver.endSearch(); // Statistics System.out.println(); System.out.println("Solutions: " + solver.solutions()); System.out.println("Failures: " + solver.failures()); System.out.println("Branches: " + solver.branches()); System.out.println("Wall time: " + solver.wallTime() + "ms"); } /** * readFile() * * <p>Reads a Survo puzzle in the following format r c rowsums olsums data ... * * <p>Example: 3 4 30,18,30 27,16,10,25 0,6,0,0 8,0,0,0 0,0,3,0 */ private static void readFile(String file) { System.out.println("readFile(" + file + ")"); try { BufferedReader inr = new BufferedReader(new FileReader(file)); r = Integer.parseInt(inr.readLine()); c = Integer.parseInt(inr.readLine()); rowsums = new int[r]; colsums = new int[c]; System.out.println("r: " + r + " c: " + c); String[] rowsums_str = inr.readLine().split(",\\s*"); String[] colsums_str = inr.readLine().split(",\\s*"); System.out.println("rowsums:"); for (int i = 0; i < r; i++) { System.out.print(rowsums_str[i] + " "); rowsums[i] = Integer.parseInt(rowsums_str[i]); } System.out.println("\ncolsums:"); for (int j = 0; j < c; j++) { System.out.print(colsums_str[j] + " "); colsums[j] = Integer.parseInt(colsums_str[j]); } System.out.println(); // init the game matrix and read data from file game = new int[r][c]; String str; int line_count = 0; while ((str = inr.readLine()) != null && str.length() > 0) { str = str.trim(); // ignore comments // starting with either # or % if (str.startsWith("#") || str.startsWith("%")) { continue; } String this_row[] = str.split(",\\s*"); for (int j = 0; j < this_row.length; j++) { game[line_count][j] = Integer.parseInt(this_row[j]); } line_count++; } // end while inr.close(); } catch (IOException e) { System.out.println(e); } } // end readFile public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); if (args.length > 0) { String file = args[0]; SurvoPuzzle.readFile(file); } else { r = default_r; c = default_c; game = default_game; rowsums = default_rowsums; colsums = default_colsums; } SurvoPuzzle.solve(); } }
5,865
27.475728
99
java
or-tools
or-tools-master/examples/contrib/ToNum.java
// Copyright 2011 Hakan Kjellerstrand hakank@gmail.com // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.contrib; import com.google.ortools.Loader; import com.google.ortools.constraintsolver.DecisionBuilder; import com.google.ortools.constraintsolver.IntVar; import com.google.ortools.constraintsolver.Solver; import java.io.*; import java.text.*; import java.util.*; public class ToNum { /** * toNum(solver, a, num, base) * <p>channelling between the array a and the number num */ private static void toNum(Solver solver, IntVar[] a, IntVar num, int base) { int len = a.length; IntVar[] tmp = new IntVar[len]; for (int i = 0; i < len; i++) { tmp[i] = solver.makeProd(a[i], (int) Math.pow(base, (len - i - 1))).var(); } solver.addConstraint(solver.makeEquality(solver.makeSum(tmp).var(), num)); } /** * Implements toNum: channeling between a number and an array. See * http://www.hakank.org/google_or_tools/toNum.py */ private static void solve() { Solver solver = new Solver("ToNum"); int n = 5; int base = 10; // // variables // IntVar[] x = solver.makeIntVarArray(n, 0, base - 1, "x"); IntVar num = solver.makeIntVar(0, (int) Math.pow(base, n) - 1, "num"); // // constraints // solver.addConstraint(solver.makeAllDifferent(x)); toNum(solver, x, num, base); // extra constraint (just for fun): // second digit should be 7 // solver.addConstraint(solver.makeEquality(x[1], 7)); // // search // DecisionBuilder db = solver.makePhase(x, solver.CHOOSE_FIRST_UNBOUND, solver.ASSIGN_MIN_VALUE); solver.newSearch(db); // // output // while (solver.nextSolution()) { System.out.print("num: " + num.value() + ": "); for (int i = 0; i < n; i++) { System.out.print(x[i].value() + " "); } System.out.println(); } solver.endSearch(); // Statistics System.out.println(); System.out.println("Solutions: " + solver.solutions()); System.out.println("Failures: " + solver.failures()); System.out.println("Branches: " + solver.branches()); System.out.println("Wall time: " + solver.wallTime() + "ms"); } public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); ToNum.solve(); } }
2,872
28.618557
99
java
or-tools
or-tools-master/examples/contrib/WhoKilledAgatha.java
// Copyright 2011 Hakan Kjellerstrand hakank@gmail.com // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.contrib; import com.google.ortools.Loader; import com.google.ortools.constraintsolver.DecisionBuilder; import com.google.ortools.constraintsolver.IntVar; import com.google.ortools.constraintsolver.Solver; import java.io.*; import java.text.*; import java.util.*; public class WhoKilledAgatha { /** * Implements the Who killed Agatha problem. See * http://www.hakank.org/google_or_tools/who_killed_agatha.py */ private static void solve() { Solver solver = new Solver("WhoKilledAgatha"); // // data // final int n = 3; final int agatha = 0; final int butler = 1; final int charles = 2; String[] names = {"Agatha", "Butler", "Charles"}; // // variables // IntVar the_killer = solver.makeIntVar(0, 2, "the_killer"); IntVar the_victim = solver.makeIntVar(0, 2, "the_victim"); IntVar[] all = new IntVar[2 * n * n]; // for branching IntVar[][] hates = new IntVar[n][n]; IntVar[] hates_flat = new IntVar[n * n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { hates[i][j] = solver.makeIntVar(0, 1, "hates[" + i + "," + j + "]"); hates_flat[i * n + j] = hates[i][j]; all[i * n + j] = hates[i][j]; } } IntVar[][] richer = new IntVar[n][n]; IntVar[] richer_flat = new IntVar[n * n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { richer[i][j] = solver.makeIntVar(0, 1, "richer[" + i + "," + j + "]"); richer_flat[i * n + j] = richer[i][j]; all[(n * n) + (i * n + j)] = richer[i][j]; } } // // constraints // // Agatha, the butler, and Charles live in Dreadsbury Mansion, and // are the only ones to live there. // A killer always hates, and is no richer than his victim. // hates[the_killer, the_victim] == 1 // hates_flat[the_killer * n + the_victim] == 1 solver.addConstraint(solver.makeEquality( solver .makeElement( hates_flat, solver.makeSum(solver.makeProd(the_killer, n).var(), the_victim).var()) .var(), 1)); // richer[the_killer, the_victim] == 0 solver.addConstraint(solver.makeEquality( solver .makeElement( richer_flat, solver.makeSum(solver.makeProd(the_killer, n).var(), the_victim).var()) .var(), 0)); // define the concept of richer: // no one is richer than him-/herself... for (int i = 0; i < n; i++) { solver.addConstraint(solver.makeEquality(richer[i][i], 0)); } // (contd...) if i is richer than j then j is not richer than i // if (i != j) => // ((richer[i,j] = 1) <=> (richer[j,i] = 0)) for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i != j) { IntVar bi = solver.makeIsEqualCstVar(richer[i][j], 1); IntVar bj = solver.makeIsEqualCstVar(richer[j][i], 0); solver.addConstraint(solver.makeEquality(bi, bj)); } } } // Charles hates no one that Agatha hates. // forall i in 0..2: // (hates[agatha, i] = 1) => (hates[charles, i] = 0) for (int i = 0; i < n; i++) { IntVar b1a = solver.makeIsEqualCstVar(hates[agatha][i], 1); IntVar b1b = solver.makeIsEqualCstVar(hates[charles][i], 0); solver.addConstraint(solver.makeLessOrEqual(solver.makeDifference(b1a, b1b).var(), 0)); } // Agatha hates everybody except the butler. solver.addConstraint(solver.makeEquality(hates[agatha][charles], 1)); solver.addConstraint(solver.makeEquality(hates[agatha][agatha], 1)); solver.addConstraint(solver.makeEquality(hates[agatha][butler], 0)); // The butler hates everyone not richer than Aunt Agatha. // forall i in 0..2: // (richer[i, agatha] = 0) => (hates[butler, i] = 1) for (int i = 0; i < n; i++) { IntVar b2a = solver.makeIsEqualCstVar(richer[i][agatha], 0); IntVar b2b = solver.makeIsEqualCstVar(hates[butler][i], 1); solver.addConstraint(solver.makeLessOrEqual(solver.makeDifference(b2a, b2b).var(), 0)); } // The butler hates everyone whom Agatha hates. // forall i : 0..2: // (hates[agatha, i] = 1) => (hates[butler, i] = 1) for (int i = 0; i < n; i++) { IntVar b3a = solver.makeIsEqualCstVar(hates[agatha][i], 1); IntVar b3b = solver.makeIsEqualCstVar(hates[butler][i], 1); solver.addConstraint(solver.makeLessOrEqual(solver.makeDifference(b3a, b3b).var(), 0)); } // Noone hates everyone. // forall i in 0..2: // (sum j in 0..2: hates[i,j]) <= 2 for (int i = 0; i < n; i++) { IntVar[] tmp = new IntVar[n]; for (int j = 0; j < n; j++) { tmp[j] = hates[i][j]; } solver.addConstraint(solver.makeLessOrEqual(solver.makeSum(tmp).var(), 2)); } // Who killed Agatha? solver.addConstraint(solver.makeEquality(the_victim, agatha)); // // search // DecisionBuilder db = solver.makePhase(all, solver.CHOOSE_FIRST_UNBOUND, solver.ASSIGN_MIN_VALUE); solver.newSearch(db); // // output // while (solver.nextSolution()) { System.out.println("the_killer: " + names[(int) the_killer.value()]); } solver.endSearch(); // Statistics System.out.println(); System.out.println("Solutions: " + solver.solutions()); System.out.println("Failures: " + solver.failures()); System.out.println("Branches: " + solver.branches()); System.out.println("Wall time: " + solver.wallTime() + "ms"); } public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); WhoKilledAgatha.solve(); } }
6,372
32.898936
100
java
or-tools
or-tools-master/examples/contrib/Xkcd.java
// Copyright 2011 Hakan Kjellerstrand hakank@gmail.com // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.contrib; import com.google.ortools.Loader; import com.google.ortools.constraintsolver.*; import com.google.ortools.constraintsolver.DecisionBuilder; import com.google.ortools.constraintsolver.IntVar; import com.google.ortools.constraintsolver.Solver; import java.io.*; import java.text.*; import java.util.*; public class Xkcd { /** Solves the xkcd problem. See http://www.hakank.org/google_or_tools/xkcd.py */ private static void solve() { Solver solver = new Solver("Xkcd"); int n = 6; // for price and total: multiplied by 100 to be able to use integers int[] price = {215, 275, 335, 355, 420, 580}; int total = 1505; // // Variables // IntVar[] x = solver.makeIntVarArray(n, 0, 10, "x"); // // Constraints // solver.addConstraint(solver.makeEquality(solver.makeScalProd(x, price).var(), total)); // // Search // DecisionBuilder db = solver.makePhase(x, solver.CHOOSE_FIRST_UNBOUND, solver.ASSIGN_MIN_VALUE); solver.newSearch(db); while (solver.nextSolution()) { System.out.print("x: "); for (int i = 0; i < n; i++) { System.out.print(x[i].value() + " "); } System.out.println(); } solver.endSearch(); // Statistics System.out.println(); System.out.println("Solutions: " + solver.solutions()); System.out.println("Failures: " + solver.failures()); System.out.println("Branches: " + solver.branches()); System.out.println("Wall time: " + solver.wallTime() + "ms"); } public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); Xkcd.solve(); } }
2,279
30.666667
99
java
or-tools
or-tools-master/examples/contrib/YoungTableaux.java
// Copyright 2011 Hakan Kjellerstrand hakank@gmail.com // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.contrib; import com.google.ortools.Loader; import com.google.ortools.constraintsolver.DecisionBuilder; import com.google.ortools.constraintsolver.IntVar; import com.google.ortools.constraintsolver.Solver; import java.io.*; import java.text.*; import java.util.*; public class YoungTableaux { /** * Implements Young tableaux and partitions. See * http://www.hakank.org/google_or_tools/young_tableuax.py */ private static void solve(int n) { Solver solver = new Solver("YoungTableaux"); System.out.println("n: " + n); // // variables // IntVar[][] x = new IntVar[n][n]; IntVar[] x_flat = new IntVar[n * n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { x[i][j] = solver.makeIntVar(1, n + 1, "x[" + i + "," + j + "]"); x_flat[i * n + j] = x[i][j]; } } // partition structure IntVar[] p = solver.makeIntVarArray(n, 0, n + 1, "p"); // // constraints // // 1..n is used exactly once for (int i = 1; i <= n; i++) { solver.addConstraint(solver.makeCount(x_flat, i, 1)); } solver.addConstraint(solver.makeEquality(x[0][0], 1)); // row wise for (int i = 0; i < n; i++) { for (int j = 1; j < n; j++) { solver.addConstraint(solver.makeGreaterOrEqual(x[i][j], x[i][j - 1])); } } // column wise for (int j = 0; j < n; j++) { for (int i = 1; i < n; i++) { solver.addConstraint(solver.makeGreaterOrEqual(x[i][j], x[i - 1][j])); } } // calculate the structure (i.e. the partition) for (int i = 0; i < n; i++) { IntVar[] b = new IntVar[n]; for (int j = 0; j < n; j++) { b[j] = solver.makeIsLessOrEqualCstVar(x[i][j], n); } solver.addConstraint(solver.makeEquality(p[i], solver.makeSum(b).var())); } solver.addConstraint(solver.makeEquality(solver.makeSum(p).var(), n)); for (int i = 1; i < n; i++) { solver.addConstraint(solver.makeGreaterOrEqual(p[i - 1], p[i])); } // // search // DecisionBuilder db = solver.makePhase(x_flat, solver.CHOOSE_FIRST_UNBOUND, solver.ASSIGN_MIN_VALUE); solver.newSearch(db); // // output // while (solver.nextSolution()) { System.out.print("p: "); for (int i = 0; i < n; i++) { System.out.print(p[i].value() + " "); } System.out.println("\nx:"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { long val = x[i][j].value(); if (val <= n) { System.out.print(val + " "); } } if (p[i].value() > 0) { System.out.println(); } } System.out.println(); } solver.endSearch(); // Statistics System.out.println(); System.out.println("Solutions: " + solver.solutions()); System.out.println("Failures: " + solver.failures()); System.out.println("Branches: " + solver.branches()); System.out.println("Wall time: " + solver.wallTime() + "ms"); } public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); int n = 5; if (args.length > 0) { n = Integer.parseInt(args[0]); } YoungTableaux.solve(n); } }
3,897
26.64539
87
java
or-tools
or-tools-master/examples/java/CapacitatedVehicleRoutingProblemWithTimeWindows.java
// // Copyright 2012 Google // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.java; import com.google.ortools.Loader; import com.google.ortools.constraintsolver.Assignment; import com.google.ortools.constraintsolver.FirstSolutionStrategy; import com.google.ortools.constraintsolver.IntVar; import com.google.ortools.constraintsolver.RoutingDimension; import com.google.ortools.constraintsolver.RoutingIndexManager; import com.google.ortools.constraintsolver.RoutingModel; import com.google.ortools.constraintsolver.RoutingSearchParameters; import com.google.ortools.constraintsolver.main; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.function.LongBinaryOperator; import java.util.function.LongUnaryOperator; import java.util.logging.Logger; // A pair class class Pair<K, V> { final K first; final V second; public static <K, V> Pair<K, V> of(K element0, V element1) { return new Pair<K, V>(element0, element1); } public Pair(K element0, V element1) { this.first = element0; this.second = element1; } } /** * Sample showing how to model and solve a capacitated vehicle routing problem with time windows * using the swig-wrapped version of the vehicle routing library in src/constraint_solver. */ public class CapacitatedVehicleRoutingProblemWithTimeWindows { private static Logger logger = Logger.getLogger(CapacitatedVehicleRoutingProblemWithTimeWindows.class.getName()); // Locations representing either an order location or a vehicle route // start/end. private List<Pair<Integer, Integer>> locations = new ArrayList(); // Quantity to be picked up for each order. private List<Integer> orderDemands = new ArrayList(); // Time window in which each order must be performed. private List<Pair<Integer, Integer>> orderTimeWindows = new ArrayList(); // Penalty cost "paid" for dropping an order. private List<Integer> orderPenalties = new ArrayList(); // Capacity of the vehicles. private int vehicleCapacity = 0; // Latest time at which each vehicle must end its tour. private List<Integer> vehicleEndTime = new ArrayList(); // Cost per unit of distance of each vehicle. private List<Integer> vehicleCostCoefficients = new ArrayList(); // Vehicle start and end indices. They have to be implemented as int[] due // to the available SWIG-ed interface. private int vehicleStarts[]; private int vehicleEnds[]; // Random number generator to produce data. private final Random randomGenerator = new Random(0xBEEF); /** * Creates a Manhattan Distance evaluator with 'costCoefficient'. * * @param manager Node Index Manager. * @param costCoefficient The coefficient to apply to the evaluator. */ private LongBinaryOperator buildManhattanCallback( RoutingIndexManager manager, int costCoefficient) { return new LongBinaryOperator() { public long applyAsLong(long firstIndex, long secondIndex) { try { int firstNode = manager.indexToNode(firstIndex); int secondNode = manager.indexToNode(secondIndex); Pair<Integer, Integer> firstLocation = locations.get(firstNode); Pair<Integer, Integer> secondLocation = locations.get(secondNode); return (long) costCoefficient * (Math.abs(firstLocation.first - secondLocation.first) + Math.abs(firstLocation.second - secondLocation.second)); } catch (Throwable throwed) { logger.warning(throwed.getMessage()); return 0; } } }; } /** * Creates order data. Location of the order is random, as well as its demand (quantity), time * window and penalty. * * @param numberOfOrders number of orders to build. * @param xMax maximum x coordinate in which orders are located. * @param yMax maximum y coordinate in which orders are located. * @param demandMax maximum quantity of a demand. * @param timeWindowMax maximum starting time of the order time window. * @param timeWindowWidth duration of the order time window. * @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 timeWindowMax, int timeWindowWidth, int penaltyMin, int penaltyMax) { logger.info("Building orders."); for (int order = 0; order < numberOfOrders; ++order) { locations.add(Pair.of(randomGenerator.nextInt(xMax + 1), randomGenerator.nextInt(yMax + 1))); orderDemands.add(randomGenerator.nextInt(demandMax + 1)); int timeWindowStart = randomGenerator.nextInt(timeWindowMax + 1); orderTimeWindows.add(Pair.of(timeWindowStart, timeWindowStart + timeWindowWidth)); orderPenalties.add(randomGenerator.nextInt(penaltyMax - penaltyMin + 1) + penaltyMin); } } /** * Creates fleet data. Vehicle starting and ending locations are random, as well as vehicle costs * per distance unit. * * @param numberOfVehicles * @param xMax maximum x coordinate in which orders are located. * @param yMax maximum y coordinate in which orders are located. * @param endTime latest end time of a tour of a vehicle. * @param capacity capacity of a vehicle. * @param costCoefficientMax maximum cost per distance unit of a vehicle (mimimum is 1), */ private void buildFleet( int numberOfVehicles, int xMax, int yMax, int endTime, int capacity, int costCoefficientMax) { logger.info("Building fleet."); vehicleCapacity = capacity; vehicleStarts = new int[numberOfVehicles]; vehicleEnds = new int[numberOfVehicles]; for (int vehicle = 0; vehicle < numberOfVehicles; ++vehicle) { vehicleStarts[vehicle] = locations.size(); locations.add(Pair.of(randomGenerator.nextInt(xMax + 1), randomGenerator.nextInt(yMax + 1))); vehicleEnds[vehicle] = locations.size(); locations.add(Pair.of(randomGenerator.nextInt(xMax + 1), randomGenerator.nextInt(yMax + 1))); vehicleEndTime.add(endTime); vehicleCostCoefficients.add(randomGenerator.nextInt(costCoefficientMax) + 1); } } /** Solves the current routing problem. */ private void solve(final int numberOfOrders, final int numberOfVehicles) { logger.info( "Creating model with " + numberOfOrders + " orders and " + numberOfVehicles + " vehicles."); // Finalizing model final int numberOfLocations = locations.size(); RoutingIndexManager manager = new RoutingIndexManager(numberOfLocations, numberOfVehicles, vehicleStarts, vehicleEnds); RoutingModel model = new RoutingModel(manager); // Setting up dimensions final int bigNumber = 100000; final LongBinaryOperator callback = buildManhattanCallback(manager, 1); final String timeStr = "time"; model.addDimension( model.registerTransitCallback(callback), bigNumber, bigNumber, false, timeStr); RoutingDimension timeDimension = model.getMutableDimension(timeStr); LongUnaryOperator demandCallback = new LongUnaryOperator() { public long applyAsLong(long index) { try { int node = manager.indexToNode(index); if (node < numberOfOrders) { return orderDemands.get(node); } return 0; } catch (Throwable throwed) { logger.warning(throwed.getMessage()); return 0; } } }; final String capacityStr = "capacity"; model.addDimension( model.registerUnaryTransitCallback(demandCallback), 0, vehicleCapacity, true, capacityStr); RoutingDimension capacityDimension = model.getMutableDimension(capacityStr); // Setting up vehicles LongBinaryOperator[] callbacks = new LongBinaryOperator[numberOfVehicles]; for (int vehicle = 0; vehicle < numberOfVehicles; ++vehicle) { final int costCoefficient = vehicleCostCoefficients.get(vehicle); callbacks[vehicle] = buildManhattanCallback(manager, costCoefficient); final int vehicleCost = model.registerTransitCallback(callbacks[vehicle]); model.setArcCostEvaluatorOfVehicle(vehicleCost, vehicle); timeDimension.cumulVar(model.end(vehicle)).setMax(vehicleEndTime.get(vehicle)); } // Setting up orders for (int order = 0; order < numberOfOrders; ++order) { timeDimension.cumulVar(order).setRange( orderTimeWindows.get(order).first, orderTimeWindows.get(order).second); long[] orderIndices = {manager.nodeToIndex(order)}; model.addDisjunction(orderIndices, orderPenalties.get(order)); } // Solving RoutingSearchParameters parameters = main.defaultRoutingSearchParameters() .toBuilder() .setFirstSolutionStrategy(FirstSolutionStrategy.Value.ALL_UNPERFORMED) .build(); logger.info("Search"); Assignment solution = model.solveWithParameters(parameters); if (solution != null) { String output = "Total cost: " + solution.objectiveValue() + "\n"; // Dropped orders String dropped = ""; for (int order = 0; order < numberOfOrders; ++order) { if (solution.value(model.nextVar(order)) == order) { dropped += " " + order; } } if (dropped.length() > 0) { output += "Dropped orders:" + dropped + "\n"; } // Routes for (int vehicle = 0; vehicle < numberOfVehicles; ++vehicle) { String route = "Vehicle " + vehicle + ": "; long order = model.start(vehicle); // Empty route has a minimum of two nodes: Start => End if (model.isEnd(solution.value(model.nextVar(order)))) { route += "Empty"; } else { for (; !model.isEnd(order); order = solution.value(model.nextVar(order))) { IntVar load = capacityDimension.cumulVar(order); IntVar time = timeDimension.cumulVar(order); route += order + " Load(" + solution.value(load) + ") " + "Time(" + solution.min(time) + ", " + solution.max(time) + ") -> "; } IntVar load = capacityDimension.cumulVar(order); IntVar time = timeDimension.cumulVar(order); route += order + " Load(" + solution.value(load) + ") " + "Time(" + solution.min(time) + ", " + solution.max(time) + ")"; } output += route + "\n"; } logger.info(output); } } public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); CapacitatedVehicleRoutingProblemWithTimeWindows problem = new CapacitatedVehicleRoutingProblemWithTimeWindows(); final int xMax = 20; final int yMax = 20; final int demandMax = 3; final int timeWindowMax = 24 * 60; final int timeWindowWidth = 4 * 60; final int penaltyMin = 50; final int penaltyMax = 100; final int endTime = 24 * 60; final int costCoefficientMax = 3; final int orders = 100; final int vehicles = 20; final int capacity = 50; problem.buildOrders( orders, xMax, yMax, demandMax, timeWindowMax, timeWindowWidth, penaltyMin, penaltyMax); problem.buildFleet(vehicles, xMax, yMax, endTime, capacity, costCoefficientMax); problem.solve(orders, vehicles); } }
11,816
40.174216
100
java
or-tools
or-tools-master/examples/java/FlowExample.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.java; import com.google.ortools.Loader; import com.google.ortools.graph.MaxFlow; import com.google.ortools.graph.MinCostFlow; /** Sample showing how to model using the flow solver. */ public class FlowExample { private static void solveMinCostFlow() { System.out.println("Min Cost Flow Problem - Simple interface"); final int numSources = 4; final int numTargets = 4; final int[][] costs = { {90, 75, 75, 80}, {35, 85, 55, 65}, {125, 95, 90, 105}, {45, 110, 95, 115}}; final int expectedCost = 275; 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]); } } for (int node = 0; node < numSources; ++node) { minCostFlow.setNodeSupply(node, 1); minCostFlow.setNodeSupply(numSources + node, -1); } if (minCostFlow.solve() == MinCostFlow.Status.OPTIMAL) { final long totalFlowCost = minCostFlow.getOptimalCost(); 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)); } } } else { System.out.println("No solution found"); } } private static void solveMaxFlow() { System.out.println("Max Flow Problem - Simple interface"); final int[] tails = {0, 0, 0, 0, 1, 2, 3, 3, 4}; final int[] heads = {1, 2, 3, 4, 3, 4, 4, 5, 5}; final int[] capacities = {5, 8, 5, 3, 4, 5, 6, 6, 4}; final int expectedTotalFlow = 10; MaxFlow maxFlow = new MaxFlow(); for (int i = 0; i < tails.length; ++i) { maxFlow.addArcWithCapacity(tails[i], heads[i], capacities[i]); } if (maxFlow.solve(0, 5) == MaxFlow.Status.OPTIMAL) { 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)); } // TODO(user): Our SWIG configuration does not currently handle these // functions correctly in Java: // maxFlow.getSourceSideMinCut(...); // maxFlow.getSinkSideMinCut(...); } else { System.out.println("There was an issue with the input."); } } public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); FlowExample.solveMinCostFlow(); FlowExample.solveMaxFlow(); } }
3,468
40.297619
99
java
or-tools
or-tools-master/examples/java/IntegerProgramming.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.java; import com.google.ortools.Loader; import com.google.ortools.linearsolver.MPConstraint; import com.google.ortools.linearsolver.MPObjective; import com.google.ortools.linearsolver.MPSolver; import com.google.ortools.linearsolver.MPVariable; /** Integer programming example that shows how to use the API. */ public class IntegerProgramming { private static void runIntegerProgrammingExample(String solverType) { MPSolver solver = MPSolver.createSolver(solverType); if (solver == null) { System.out.println("Could not create solver " + solverType); return; } double infinity = java.lang.Double.POSITIVE_INFINITY; // x1 and x2 are integer non-negative variables. MPVariable x1 = solver.makeIntVar(0.0, infinity, "x1"); MPVariable x2 = solver.makeIntVar(0.0, infinity, "x2"); // Minimize x1 + 2 * x2. MPObjective objective = solver.objective(); objective.setCoefficient(x1, 1); objective.setCoefficient(x2, 2); // 2 * x2 + 3 * x1 >= 17. MPConstraint ct = solver.makeConstraint(17, infinity); ct.setCoefficient(x1, 3); ct.setCoefficient(x2, 2); final MPSolver.ResultStatus resultStatus = solver.solve(); // Check that the problem has an optimal solution. if (resultStatus != MPSolver.ResultStatus.OPTIMAL) { System.err.println("The problem does not have an optimal solution!"); return; } // Verify that the solution satisfies all constraints (when using solvers // others than GLOP_LINEAR_PROGRAMMING, this is highly recommended!). if (!solver.verifySolution(/*tolerance=*/1e-7, /* log_errors= */ true)) { System.err.println("The solution returned by the solver violated the" + " problem constraints by at least 1e-7"); return; } System.out.println("Problem solved in " + solver.wallTime() + " milliseconds"); // The objective value of the solution. 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"); } public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); System.out.println("---- Integer programming example with SCIP (recommended) ----"); runIntegerProgrammingExample("SCIP"); System.out.println("---- Integer programming example with CBC ----"); runIntegerProgrammingExample("CBC"); System.out.println("---- Integer programming example with CP-SAT ----"); runIntegerProgrammingExample("SAT"); } }
3,369
39.60241
90
java
or-tools
or-tools-master/examples/java/LinearAssignmentAPI.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.java; import com.google.ortools.Loader; import com.google.ortools.graph.LinearSumAssignment; /** * Test assignment on a 4x4 matrix. Example taken from * http://www.ee.oulu.fi/~mpa/matreng/eem1_2-1.htm with kCost[0][1] * modified so the optimum solution is unique. */ public class LinearAssignmentAPI { 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 expectedCost = cost[0][3] + cost[1][2] + cost[2][1] + cost[3][0]; LinearSumAssignment assignment = new LinearSumAssignment(); for (int source = 0; source < numSources; ++source) { for (int target = 0; target < numTargets; ++target) { assignment.addArcWithCost(source, target, cost[source][target]); } } if (assignment.solve() == LinearSumAssignment.Status.OPTIMAL) { 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)); } } else { System.out.println("No solution found."); } } public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); LinearAssignmentAPI.runAssignmentOn4x4Matrix(); } }
2,137
38.592593
98
java
or-tools
or-tools-master/examples/java/LinearProgramming.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.java; import com.google.ortools.Loader; import com.google.ortools.linearsolver.MPConstraint; import com.google.ortools.linearsolver.MPObjective; import com.google.ortools.linearsolver.MPSolver; import com.google.ortools.linearsolver.MPVariable; /** * Linear programming example that shows how to use the API. */ public class LinearProgramming { private static void runLinearProgrammingExample(String solverType, boolean printModel) { MPSolver solver = MPSolver.createSolver(solverType); if (solver == null) { System.out.println("Could not create solver " + solverType); return; } double infinity = java.lang.Double.POSITIVE_INFINITY; // x1, x2 and x3 are continuous non-negative variables. MPVariable x1 = solver.makeNumVar(0.0, infinity, "x1"); MPVariable x2 = solver.makeNumVar(0.0, infinity, "x2"); MPVariable x3 = solver.makeNumVar(0.0, infinity, "x3"); // Maximize 10 * x1 + 6 * x2 + 4 * x3. MPObjective objective = solver.objective(); objective.setCoefficient(x1, 10); objective.setCoefficient(x2, 6); objective.setCoefficient(x3, 4); objective.setMaximization(); // x1 + x2 + x3 <= 100. MPConstraint c0 = solver.makeConstraint(-infinity, 100.0); c0.setCoefficient(x1, 1); c0.setCoefficient(x2, 1); c0.setCoefficient(x3, 1); // 10 * x1 + 4 * x2 + 5 * x3 <= 600. MPConstraint c1 = solver.makeConstraint(-infinity, 600.0); c1.setCoefficient(x1, 10); c1.setCoefficient(x2, 4); c1.setCoefficient(x3, 5); // 2 * x1 + 2 * x2 + 6 * x3 <= 300. MPConstraint c2 = solver.makeConstraint(-infinity, 300.0); c2.setCoefficient(x1, 2); c2.setCoefficient(x2, 2); c2.setCoefficient(x3, 6); System.out.println("Number of variables = " + solver.numVariables()); System.out.println("Number of constraints = " + solver.numConstraints()); if (printModel) { String model = solver.exportModelAsLpFormat(); System.out.println(model); } final MPSolver.ResultStatus resultStatus = solver.solve(); // Check that the problem has an optimal solution. if (resultStatus != MPSolver.ResultStatus.OPTIMAL) { System.err.println("The problem does not have an optimal solution!"); return; } // Verify that the solution satisfies all constraints (when using solvers // others than GLOP_LINEAR_PROGRAMMING, this is highly recommended!). if (!solver.verifySolution(/*tolerance=*/1e-7, /* log_errors= */ true)) { System.err.println("The solution returned by the solver violated the" + " problem constraints by at least 1e-7"); return; } System.out.println("Problem solved in " + solver.wallTime() + " milliseconds"); // The objective value of the solution. 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("x3 = " + x3.solutionValue()); final double[] activities = solver.computeConstraintActivities(); System.out.println("Advanced usage:"); 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()); System.out.println("c0: dual value = " + c0.dualValue()); System.out.println(" activity = " + activities[c0.index()]); System.out.println("c1: dual value = " + c1.dualValue()); System.out.println(" activity = " + activities[c1.index()]); System.out.println("c2: dual value = " + c2.dualValue()); System.out.println(" activity = " + activities[c2.index()]); } public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); System.out.println("---- Linear programming example with GLOP (recommended) ----"); runLinearProgrammingExample("GLOP", true); System.out.println("---- Linear programming example with CLP ----"); runLinearProgrammingExample("CLP", false); } }
4,829
39.588235
90
java
or-tools
or-tools-master/examples/java/RabbitsPheasants.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.java; import com.google.ortools.Loader; import com.google.ortools.constraintsolver.ConstraintSolverParameters; import com.google.ortools.constraintsolver.DecisionBuilder; import com.google.ortools.constraintsolver.IntVar; import com.google.ortools.constraintsolver.Solver; import java.util.logging.Logger; /** Sample showing how to model using the constraint programming solver.*/ public class RabbitsPheasants { private static Logger logger = Logger.getLogger(RabbitsPheasants.class.getName()); /** * Solves the rabbits + pheasants problem. We are seing 20 heads * and 56 legs. How many rabbits and how many pheasants are we thus * seeing? */ private static void solve(boolean traceSearch) { ConstraintSolverParameters parameters = ConstraintSolverParameters.newBuilder() .mergeFrom(Solver.defaultSolverParameters()) .setTraceSearch(traceSearch) .build(); 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)); DecisionBuilder db = solver.makePhase(rabbits, pheasants, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); solver.newSearch(db); solver.nextSolution(); logger.info(rabbits.toString()); logger.info(pheasants.toString()); solver.endSearch(); } public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); boolean traceSearch = args.length > 0 && args[1].equals("--trace"); RabbitsPheasants.solve(traceSearch); } }
2,548
43.719298
99
java
or-tools
or-tools-master/examples/java/RandomTsp.java
// Copyright 2010-2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.java; import com.google.ortools.Loader; import com.google.ortools.constraintsolver.Assignment; import com.google.ortools.constraintsolver.FirstSolutionStrategy; import com.google.ortools.constraintsolver.RoutingIndexManager; import com.google.ortools.constraintsolver.RoutingModel; import com.google.ortools.constraintsolver.RoutingSearchParameters; import com.google.ortools.constraintsolver.main; // import java.io.*; // import java.text.*; // import java.util.*; import java.util.Random; import java.util.function.LongBinaryOperator; import java.util.function.LongUnaryOperator; import java.util.logging.Logger; public class RandomTsp { private static Logger logger = Logger.getLogger(RandomTsp.class.getName()); static class RandomManhattan implements LongBinaryOperator { public RandomManhattan(RoutingIndexManager manager, int size, int seed) { this.xs = new int[size]; this.ys = new int[size]; this.indexManager = manager; Random generator = new Random(seed); for (int i = 0; i < size; ++i) { xs[i] = generator.nextInt(1000); ys[i] = generator.nextInt(1000); } } public long applyAsLong(long firstIndex, long secondIndex) { int firstNode = indexManager.indexToNode(firstIndex); int secondNode = indexManager.indexToNode(secondIndex); return Math.abs(xs[firstNode] - xs[secondNode]) + Math.abs(ys[firstNode] - ys[secondNode]); } private int[] xs; private int[] ys; private RoutingIndexManager indexManager; } static class ConstantCallback implements LongUnaryOperator { public long applyAsLong(long index) { return 1; } } static void solve(int size, int forbidden, int seed) { RoutingIndexManager manager = new RoutingIndexManager(size, 1, 0); RoutingModel routing = new RoutingModel(manager); // Setting the cost function. // Put a permanent callback to the distance accessor here. The callback // has the following signature: ResultCallback2<int64_t, int64_t, int64_t>. // The two arguments are the from and to node inidices. LongBinaryOperator distances = new RandomManhattan(manager, size, seed); routing.setArcCostEvaluatorOfAllVehicles(routing.registerTransitCallback(distances)); // Forbid node connections (randomly). Random randomizer = new Random(); long forbidden_connections = 0; while (forbidden_connections < forbidden) { long from = randomizer.nextInt(size - 1); long to = randomizer.nextInt(size - 1) + 1; if (routing.nextVar(from).contains(to)) { logger.info("Forbidding connection " + from + " -> " + to); routing.nextVar(from).removeValue(to); ++forbidden_connections; } } // Add dummy dimension to test API. routing.addDimension(routing.registerUnaryTransitCallback(new ConstantCallback()), size + 1, size + 1, true, "dummy"); // Solve, returns a solution if any (owned by RoutingModel). RoutingSearchParameters search_parameters = RoutingSearchParameters.newBuilder() .mergeFrom(main.defaultRoutingSearchParameters()) .setFirstSolutionStrategy(FirstSolutionStrategy.Value.PATH_CHEAPEST_ARC) .build(); Assignment solution = routing.solveWithParameters(search_parameters); if (solution != null) { // Solution cost. logger.info("Objective : " + solution.objectiveValue()); // Inspect solution. // Only one route here; otherwise iterate from 0 to routing.vehicles() - 1 int route_number = 0; String route = ""; for (long node = routing.start(route_number); !routing.isEnd(node); node = solution.value(routing.nextVar(node))) { route += "" + node + " -> "; } logger.info(route + "0"); } } public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); int size = 10; if (args.length > 0) { size = Integer.parseInt(args[0]); } int forbidden = 0; if (args.length > 1) { forbidden = Integer.parseInt(args[1]); } int seed = 0; if (args.length > 2) { seed = Integer.parseInt(args[2]); } solve(size, forbidden, seed); } }
4,843
35.149254
97
java
or-tools
or-tools-master/examples/tests/ConstraintSolverTest.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.constraintsolver; import static com.google.common.truth.Truth.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.collect.Iterables; import com.google.ortools.Loader; import com.google.ortools.constraintsolver.ConstraintSolverParameters; import com.google.ortools.constraintsolver.RegularLimitParameters; import java.util.ArrayList; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.function.Supplier; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** Tests the Constraint solver java interface. */ public final class ConstraintSolverTest { @BeforeEach public void setUp() { Loader.loadNativeLibraries(); } @Test public void testSolverCtor() { final Solver solver = new Solver("TestSolver"); assertNotNull(solver); assertEquals("TestSolver", solver.model_name()); assertNotNull(solver.toString()); } @Test public void testIntVar() { final Solver solver = new Solver("Solver"); final IntVar var = solver.makeIntVar(3, 11, "IntVar"); assertEquals(3, var.min()); assertEquals(11, var.max()); } @Test public void testIntVarArray() { final Solver solver = new Solver("Solver"); final IntVar[] vars = solver.makeIntVarArray(7, 3, 5, "vars"); assertThat(vars).hasLength(7); for (IntVar var : vars) { assertEquals(3, var.min()); assertEquals(5, var.max()); } } @Test public void testRabbitsPheasants() { final Solver solver = new Solver("testRabbitsPheasants"); final IntVar rabbits = solver.makeIntVar(0, 100, "rabbits"); final 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)); final DecisionBuilder db = solver.makePhase(rabbits, pheasants, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); solver.newSearch(db); solver.nextSolution(); assertEquals(8, rabbits.value()); assertEquals(12, pheasants.value()); solver.endSearch(); } // A Decision builder that does nothing. static class DummyDecisionBuilder extends JavaDecisionBuilder { @Override public Decision next(Solver solver) throws Solver.FailException { System.out.println("In Dummy Decision Builder"); return null; } @Override public String toString() { return "DummyDecisionBuilder"; } } @Test public void testDummyDecisionBuilder() { final Solver solver = new Solver("testDummyDecisionBuilder"); final DecisionBuilder db = new DummyDecisionBuilder(); assertTrue(solver.solve(db)); } /** * A decision builder that fails. */ static class FailDecisionBuilder extends JavaDecisionBuilder { @Override public Decision next(Solver solver) throws Solver.FailException { System.out.println("In Fail Decision Builder"); solver.fail(); return null; } } @Test public void testFailDecisionBuilder() { final Solver solver = new Solver("testFailDecisionBuilder"); final DecisionBuilder db = new FailDecisionBuilder(); assertFalse(solver.solve(db)); } /** Golomb Ruler test */ @Test public void testGolombRuler() { final int m = 8; final Solver solver = new Solver("GR " + m); final IntVar[] ticks = solver.makeIntVarArray(m, 0, (1 << (m + 1)) - 1, "ticks"); solver.addConstraint(solver.makeEquality(ticks[0], 0)); for (int i = 0; i < ticks.length - 1; i++) { solver.addConstraint(solver.makeLess(ticks[i], ticks[i + 1])); } final ArrayList<IntVar> diff = new ArrayList<>(); for (int i = 0; i < m - 1; i++) { for (int j = i + 1; j < m; j++) { diff.add(solver.makeDifference(ticks[j], ticks[i]).var()); } } solver.addConstraint(solver.makeAllDifferent(diff.toArray(new IntVar[0]), true)); // break symetries if (m > 2) { solver.addConstraint(solver.makeLess(diff.get(0), Iterables.getLast(diff))); } final OptimizeVar opt = solver.makeMinimize(ticks[m - 1], 1); final DecisionBuilder db = solver.makePhase(ticks, Solver.CHOOSE_MIN_SIZE_LOWEST_MIN, Solver.ASSIGN_MIN_VALUE); final SearchMonitor log = solver.makeSearchLog(10000, opt); assertTrue(solver.solve(db, opt, log)); assertEquals(34, opt.best()); } @Test public void testElementFunction() { final Solver solver = new Solver("testElementFunction"); final IntVar index = solver.makeIntVar(0, 10, "index"); final IntExpr element = solver.makeElement((long x) -> x * 2, index); assertEquals(0, element.min()); assertEquals(20, element.max()); } @Test public void testSolverParameters() { final ConstraintSolverParameters parameters = Solver.defaultSolverParameters().toBuilder().setTraceSearch(true).build(); final Solver solver = new Solver("testSolverParameters", parameters); final ConstraintSolverParameters stored = solver.parameters(); assertTrue(stored.getTraceSearch()); } @Test public void testRegularLimitParameters() { final Solver solver = new Solver("testRegularLimitParameters"); final RegularLimitParameters protoLimit = solver.makeDefaultRegularLimitParameters().toBuilder().setFailures(20000).build(); assertEquals(20000, protoLimit.getFailures()); final SearchLimit limit = solver.makeLimit(protoLimit); assertNotNull(limit); } // verify Closure in Decision. @Test public void testClosureDecision() { final StringProperty call = new StringProperty(""); final Solver solver = new Solver("ClosureDecisionTest"); final Decision decision = solver.makeDecision( (Solver s) -> call.setValue("Apply"), (Solver s) -> call.setValue("Refute")); System.gc(); decision.apply(solver); assertEquals("Apply", call.toString()); decision.refute(solver); assertEquals("Refute", call.toString()); } @Test public void testSolverInClosureDecision() { final Solver solver = new Solver("SolverTestName"); final String modelName = solver.model_name(); // Lambda can only capture final or implicit final. final AtomicInteger countApply = new AtomicInteger(0); final AtomicInteger countRefute = new AtomicInteger(0); assertEquals(0, countApply.intValue()); assertEquals(0, countRefute.intValue()); final Decision decision = solver.makeDecision( (Solver s) -> { assertEquals(s.model_name(), modelName); countApply.addAndGet(1); }, (Solver s) -> { assertEquals(s.model_name(), modelName); countRefute.addAndGet(1); }); System.gc(); // verify lambda are kept alive decision.apply(solver); assertEquals(1, countApply.intValue()); assertEquals(0, countRefute.intValue()); decision.refute(solver); assertEquals(1, countApply.intValue()); assertEquals(1, countRefute.intValue()); } // A Decision builder that does nothing public static class ActionDecisionBuilder extends JavaDecisionBuilder { Consumer<Solver> apply; Consumer<Solver> refute; boolean passed; public ActionDecisionBuilder(Consumer<Solver> a, Consumer<Solver> r) { apply = a; refute = r; passed = false; } @Override public Decision next(Solver solver) throws Solver.FailException { if (passed) { return null; } passed = true; return solver.makeDecision(apply, refute); } @Override public String toString() { return "ActionDecisionBuilder"; } } // Tests the ActionDecisionBuilder. @Test public void testActionDecisionBuilder() { final Solver solver = new Solver("testActionDecisionBuilder"); // Lambda can only capture final or implicit final final AtomicInteger countApply = new AtomicInteger(0); final AtomicInteger countRefute = new AtomicInteger(0); assertEquals(0, countApply.intValue()); assertEquals(0, countRefute.intValue()); final DecisionBuilder db = new ActionDecisionBuilder( (Solver s) -> countApply.addAndGet(1), (Solver s) -> countRefute.addAndGet(1)); solver.newSearch(db); assertTrue(solver.nextSolution()); assertEquals(1, countApply.intValue()); assertEquals(0, countRefute.intValue()); assertTrue(solver.nextSolution()); assertEquals(1, countApply.intValue()); assertEquals(1, countRefute.intValue()); solver.endSearch(); } // ----- LocalSearch Test ----- private static class MoveOneVar extends IntVarLocalSearchOperator { public MoveOneVar(IntVar[] variables) { super(variables); variableIndex = 0; moveUp = false; } @Override protected boolean oneNeighbor() { long currentValue = oldValue(variableIndex); if (moveUp) { setValue(variableIndex, currentValue + 1); variableIndex = (variableIndex + 1) % size(); } else { setValue(variableIndex, currentValue - 1); } moveUp = !moveUp; return true; } @Override public void onStart() {} // Index of the next variable to try to restore private long variableIndex; // Direction of the modification. private boolean moveUp; } @Test public void testSolver() { final Solver solver = new Solver("Solver"); final IntVar[] vars = solver.makeIntVarArray(4, 0, 4, "vars"); final IntVar sumVar = solver.makeSum(vars).var(); final OptimizeVar obj = solver.makeMinimize(sumVar, 1); final DecisionBuilder db = solver.makePhase(vars, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MAX_VALUE); final MoveOneVar moveOneVar = new MoveOneVar(vars); final LocalSearchPhaseParameters lsParams = solver.makeLocalSearchPhaseParameters(sumVar, moveOneVar, db); final DecisionBuilder ls = solver.makeLocalSearchPhase(vars, db, lsParams); final SolutionCollector collector = solver.makeLastSolutionCollector(); collector.addObjective(sumVar); final SearchMonitor log = solver.makeSearchLog(1000, obj); assertTrue(solver.solve(ls, collector, obj, log)); } private static class SumFilter extends IntVarLocalSearchFilter { public SumFilter(IntVar[] vars) { super(vars); sum = 0; } @Override protected void onSynchronize(Assignment unusedDelta) { sum = 0; for (int index = 0; index < size(); ++index) { sum += value(index); } } @Override public boolean accept(Assignment delta, Assignment unusedDeltadelta, long unusedObjectiveMin, long unusedObjectiveMax) { AssignmentIntContainer solutionDelta = delta.intVarContainer(); int solutionDeltaSize = solutionDelta.size(); for (int i = 0; i < solutionDeltaSize; ++i) { if (!solutionDelta.element(i).activated()) { return true; } } long newSum = sum; for (int index = 0; index < solutionDeltaSize; ++index) { int touchedVar = index(solutionDelta.element(index).var()); long oldValue = value(touchedVar); long newValue = solutionDelta.element(index).value(); newSum += newValue - oldValue; } return newSum < sum; } private long sum; } private static class StringProperty { public StringProperty(String initialValue) { value = initialValue; } public void setValue(String newValue) { value = newValue; } @Override public String toString() { return value; } private String value; } @Test public void testSolverWithLocalSearchFilter() { final Solver solver = new Solver("Solver"); final IntVar[] vars = solver.makeIntVarArray(4, 0, 4, "vars"); final IntVar sumVar = solver.makeSum(vars).var(); final OptimizeVar obj = solver.makeMinimize(sumVar, 1); final 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]; filters[0] = filter; LocalSearchFilterManager filterManager = new LocalSearchFilterManager(filters); LocalSearchPhaseParameters lsParams = solver.makeLocalSearchPhaseParameters(sumVar, moveOneVar, db, null, filterManager); DecisionBuilder ls = solver.makeLocalSearchPhase(vars, db, lsParams); SolutionCollector collector = solver.makeLastSolutionCollector(); collector.addObjective(sumVar); SearchMonitor log = solver.makeSearchLog(1000, obj); solver.solve(ls, collector, obj, log); } private static class OneVarLns extends BaseLns { public OneVarLns(IntVar[] vars) { super(vars); } @Override public void initFragments() { index = 0; } @Override public boolean nextFragment() { int size = size(); if (index < size) { appendToFragment(index); ++index; return true; } else { return false; } } private int index; } @Test public void testSolverLns() { final Solver solver = new Solver("Solver"); final IntVar[] vars = solver.makeIntVarArray(4, 0, 4, "vars"); final IntVar sumVar = solver.makeSum(vars).var(); final OptimizeVar obj = solver.makeMinimize(sumVar, 1); final DecisionBuilder db = solver.makePhase(vars, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MAX_VALUE); final OneVarLns oneVarLns = new OneVarLns(vars); final LocalSearchPhaseParameters lsParams = solver.makeLocalSearchPhaseParameters(sumVar, oneVarLns, db); final DecisionBuilder ls = solver.makeLocalSearchPhase(vars, db, lsParams); final SolutionCollector collector = solver.makeLastSolutionCollector(); collector.addObjective(sumVar); final SearchMonitor log = solver.makeSearchLog(1000, obj); solver.solve(ls, collector, obj, log); } // ----- SearchLog Test ----- // TODO(user): Improve search log tests; currently only tests coverage and callback. // note: this is more or less what is done in search_test.cc private static void runSearchLog(SearchMonitor searchlog) { searchlog.enterSearch(); searchlog.exitSearch(); searchlog.acceptSolution(); searchlog.atSolution(); searchlog.beginFail(); searchlog.noMoreSolutions(); searchlog.beginInitialPropagation(); searchlog.endInitialPropagation(); } // Simple Coverage test... @Test public void testSearchLog() { final Solver solver = new Solver("TestSearchLog"); final IntVar var = solver.makeIntVar(1, 1, "Variable"); solver.makeMinimize(var, 1); final SearchMonitor searchlog = solver.makeSearchLog(0); runSearchLog(searchlog); } private static class SearchCount implements Supplier<String> { public SearchCount(AtomicInteger initialCount) { count = initialCount; } @Override public String get() { count.addAndGet(1); return "display callback called..."; } private final AtomicInteger count; } @Test public void testSearchLogWithCallback() { final Solver solver = new Solver("TestSearchLog"); final AtomicInteger count = new AtomicInteger(0); final SearchMonitor searchlog = solver.makeSearchLog(0, // branch period new SearchCount(count)); System.gc(); // verify SearchCount is kept alive by the searchlog runSearchLog(searchlog); assertEquals(1, count.intValue()); } @Test public void testSearchLogWithLambdaCallback() { final Solver solver = new Solver("TestSearchLog"); final AtomicInteger count = new AtomicInteger(0); final SearchMonitor searchlog = solver.makeSearchLog(0, // branch period () -> { count.addAndGet(1); return "display callback called..."; }); System.gc(); // verify lambda is kept alive by the searchlog runSearchLog(searchlog); assertEquals(1, count.intValue()); } @Test public void testSearchLogWithIntVarCallback() { final Solver solver = new Solver("TestSearchLog"); final IntVar var = solver.makeIntVar(1, 1, "Variable"); final AtomicInteger count = new AtomicInteger(0); final SearchMonitor searchlog = solver.makeSearchLog(0, // branch period var, // IntVar to monitor new SearchCount(count)); System.gc(); runSearchLog(searchlog); assertEquals(1, count.intValue()); } @Test public void testSearchLogWithObjectiveCallback() { final Solver solver = new Solver("TestSearchLog"); final IntVar var = solver.makeIntVar(1, 1, "Variable"); final OptimizeVar objective = solver.makeMinimize(var, 1); final AtomicInteger count = new AtomicInteger(0); final SearchMonitor searchlog = solver.makeSearchLog(0, // branch period objective, // objective var to monitor new SearchCount(count)); System.gc(); runSearchLog(searchlog); assertEquals(1, count.intValue()); } }
17,935
32.525234
99
java
or-tools
or-tools-master/examples/tests/CpModelTest.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.sat; import static com.google.common.truth.Truth.assertThat; import static org.junit.jupiter.api.Assertions.assertNotNull; import com.google.ortools.Loader; import com.google.ortools.sat.LinearArgumentProto; import com.google.ortools.util.Domain; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** Tests the CpSolver java interface. */ public final class CpModelTest { @BeforeEach public void setUp() { Loader.loadNativeLibraries(); } @Test public void testCpModel_newIntVar() throws Exception { final CpModel model = new CpModel(); assertNotNull(model); final IntVar x = model.newIntVar(0, 10, "x"); final IntVar y = model.newIntVarFromDomain(Domain.fromValues(new long[] {0, 1, 2, 5}), "y"); final IntVar z = model.newIntVarFromDomain(Domain.fromIntervals(new long[][] {{0, 2}, {5}}), ""); final BoolVar t = model.newBoolVar("t"); final IntVar u = model.newConstant(5); assertThat(x.getName()).isEqualTo("x"); assertThat(y.getName()).isEqualTo("y"); assertThat(z.getName()).isEmpty(); assertThat(t.getName()).isEqualTo("t"); assertThat(u.getName()).isEmpty(); assertThat(x.getDomain().flattenedIntervals()).isEqualTo(new long[] {0, 10}); assertThat(x.toString()).isEqualTo("x(0..10)"); assertThat(y.toString()).isEqualTo("y(0..2, 5)"); assertThat(z.toString()).isEqualTo("var_2(0..2, 5)"); assertThat(t.toString()).isEqualTo("t(0..1)"); assertThat(u.toString()).isEqualTo("5"); } @Test public void testCpModel_newIntervalVar() throws Exception { final CpModel model = new CpModel(); assertNotNull(model); final int horizon = 100; final IntVar startVar = model.newIntVar(0, horizon, "start"); final int duration = 10; final IntervalVar interval = model.newFixedSizeIntervalVar(startVar, duration, "interval"); final LinearExpr startExpr = interval.getStartExpr(); assertThat(startExpr.numElements()).isEqualTo(1); assertThat(startExpr.getOffset()).isEqualTo(0); assertThat(startExpr.getVariableIndex(0)).isEqualTo(startVar.getIndex()); assertThat(startExpr.getCoefficient(0)).isEqualTo(1); final LinearExpr sizeExpr = interval.getSizeExpr(); assertThat(sizeExpr.numElements()).isEqualTo(0); assertThat(sizeExpr.getOffset()).isEqualTo(duration); final LinearExpr endExpr = interval.getEndExpr(); assertThat(endExpr.numElements()).isEqualTo(1); assertThat(endExpr.getOffset()).isEqualTo(duration); assertThat(endExpr.getVariableIndex(0)).isEqualTo(startVar.getIndex()); assertThat(endExpr.getCoefficient(0)).isEqualTo(1); } @Test public void testCpModel_addBoolOr() throws Exception { final CpModel model = new CpModel(); assertNotNull(model); final BoolVar x = model.newBoolVar("x"); final BoolVar y = model.newBoolVar("y"); final BoolVar z = model.newBoolVar("z"); model.addBoolOr(new Literal[] {x, y.not(), z}); assertThat(model.model().getConstraintsCount()).isEqualTo(1); assertThat(model.model().getConstraints(0).hasBoolOr()).isTrue(); assertThat(model.model().getConstraints(0).getBoolOr().getLiteralsCount()).isEqualTo(3); } @Test public void testCpModel_addAtLeastOne() throws Exception { final CpModel model = new CpModel(); assertNotNull(model); final BoolVar x = model.newBoolVar("x"); final BoolVar y = model.newBoolVar("y"); final BoolVar z = model.newBoolVar("z"); model.addAtLeastOne(new Literal[] {x, y.not(), z}); assertThat(model.model().getConstraintsCount()).isEqualTo(1); assertThat(model.model().getConstraints(0).hasBoolOr()).isTrue(); assertThat(model.model().getConstraints(0).getBoolOr().getLiteralsCount()).isEqualTo(3); } @Test public void testCpModel_addAtMostOne() throws Exception { final CpModel model = new CpModel(); assertNotNull(model); final BoolVar x = model.newBoolVar("x"); final BoolVar y = model.newBoolVar("y"); final BoolVar z = model.newBoolVar("z"); model.addAtMostOne(new Literal[] {x, y.not(), z}); assertThat(model.model().getConstraintsCount()).isEqualTo(1); assertThat(model.model().getConstraints(0).hasAtMostOne()).isTrue(); assertThat(model.model().getConstraints(0).getAtMostOne().getLiteralsCount()).isEqualTo(3); } @Test public void testCpModel_addExactlyOne() throws Exception { final CpModel model = new CpModel(); assertNotNull(model); final BoolVar x = model.newBoolVar("x"); final BoolVar y = model.newBoolVar("y"); final BoolVar z = model.newBoolVar("z"); model.addExactlyOne(new Literal[] {x, y.not(), z}); assertThat(model.model().getConstraintsCount()).isEqualTo(1); assertThat(model.model().getConstraints(0).hasExactlyOne()).isTrue(); assertThat(model.model().getConstraints(0).getExactlyOne().getLiteralsCount()).isEqualTo(3); } @Test public void testCpModel_addBoolAnd() throws Exception { final CpModel model = new CpModel(); assertNotNull(model); final BoolVar x = model.newBoolVar("x"); final BoolVar y = model.newBoolVar("y"); final BoolVar z = model.newBoolVar("z"); model.addBoolAnd(new Literal[] {x, y.not(), z}); assertThat(model.model().getConstraintsCount()).isEqualTo(1); assertThat(model.model().getConstraints(0).hasBoolAnd()).isTrue(); assertThat(model.model().getConstraints(0).getBoolAnd().getLiteralsCount()).isEqualTo(3); } @Test public void testCpModel_addBoolXor() throws Exception { final CpModel model = new CpModel(); assertNotNull(model); final BoolVar x = model.newBoolVar("x"); final BoolVar y = model.newBoolVar("y"); final BoolVar z = model.newBoolVar("z"); model.addBoolXor(new Literal[] {x, y.not(), z}); assertThat(model.model().getConstraintsCount()).isEqualTo(1); assertThat(model.model().getConstraints(0).hasBoolXor()).isTrue(); assertThat(model.model().getConstraints(0).getBoolXor().getLiteralsCount()).isEqualTo(3); } @Test public void testCpModel_addImplication() throws Exception { final CpModel model = new CpModel(); assertNotNull(model); final BoolVar x = model.newBoolVar("x"); final BoolVar y = model.newBoolVar("y"); model.addImplication(x, y); assertThat(model.model().getConstraintsCount()).isEqualTo(1); assertThat(model.model().getConstraints(0).hasBoolOr()).isTrue(); assertThat(model.model().getConstraints(0).getBoolOr().getLiteralsCount()).isEqualTo(2); } @Test public void testCpModel_addLinear() throws Exception { final CpModel model = new CpModel(); assertNotNull(model); final BoolVar x = model.newBoolVar("x"); final BoolVar y = model.newBoolVar("y"); model.addEquality(LinearExpr.newBuilder().add(x).add(y), 1); assertThat(model.model().getConstraintsCount()).isEqualTo(1); assertThat(model.model().getConstraints(0).hasLinear()).isTrue(); assertThat(model.model().getConstraints(0).getLinear().getVarsCount()).isEqualTo(2); final BoolVar b = model.newBoolVar("b"); model.addEquality(LinearExpr.newBuilder().add(x).add(y), 2).onlyEnforceIf(b.not()); assertThat(model.model().getConstraintsCount()).isEqualTo(2); assertThat(model.model().getConstraints(1).hasLinear()).isTrue(); assertThat(model.model().getConstraints(1).getEnforcementLiteralCount()).isEqualTo(1); assertThat(model.model().getConstraints(1).getEnforcementLiteral(0)).isEqualTo(-3); final BoolVar c = model.newBoolVar("c"); model.addEquality(LinearExpr.newBuilder().add(x).add(y), 3).onlyEnforceIf(new Literal[] {b, c}); assertThat(model.model().getConstraintsCount()).isEqualTo(3); assertThat(model.model().getConstraints(2).hasLinear()).isTrue(); assertThat(model.model().getConstraints(2).getEnforcementLiteralCount()).isEqualTo(2); assertThat(model.model().getConstraints(2).getEnforcementLiteral(0)).isEqualTo(2); assertThat(model.model().getConstraints(2).getEnforcementLiteral(1)).isEqualTo(3); } @Test public void testLinearExpr_addEquality_literal() { final CpModel model = new CpModel(); assertNotNull(model); final Literal x = model.newBoolVar("x"); final Literal y = model.newBoolVar("y").not(); model.addEquality(x, y); } @Test public void testCpModel_addMinEquality() throws Exception { final CpModel model = new CpModel(); assertNotNull(model); final BoolVar x = model.newBoolVar("x"); final BoolVar y = model.newBoolVar("y"); final BoolVar t = model.newBoolVar("t"); model.addMinEquality(t, new IntVar[] {x, y}); assertThat(model.model().getConstraintsCount()).isEqualTo(1); assertThat(model.model().getConstraints(0).hasLinMax()).isTrue(); LinearArgumentProto ct = model.model().getConstraints(0).getLinMax(); assertThat(ct.getTarget().getVarsCount()).isEqualTo(1); assertThat(ct.getTarget().getVars(0)).isEqualTo(2); assertThat(ct.getTarget().getCoeffs(0)).isEqualTo(-1); assertThat(ct.getExprsCount()).isEqualTo(2); assertThat(ct.getExprs(0).getVarsCount()).isEqualTo(1); assertThat(ct.getExprs(0).getVars(0)).isEqualTo(0); assertThat(ct.getExprs(0).getCoeffs(0)).isEqualTo(-1); assertThat(ct.getExprs(1).getVarsCount()).isEqualTo(1); assertThat(ct.getExprs(1).getVars(0)).isEqualTo(1); assertThat(ct.getExprs(1).getCoeffs(0)).isEqualTo(-1); } @Test public void testCpModel_addMaxEquality() throws Exception { final CpModel model = new CpModel(); assertNotNull(model); final BoolVar x = model.newBoolVar("x"); final BoolVar y = model.newBoolVar("y"); final BoolVar t = model.newBoolVar("t"); model.addMaxEquality(t, new IntVar[] {x, y}); assertThat(model.model().getConstraintsCount()).isEqualTo(1); assertThat(model.model().getConstraints(0).hasLinMax()).isTrue(); LinearArgumentProto ct = model.model().getConstraints(0).getLinMax(); assertThat(ct.getTarget().getVarsCount()).isEqualTo(1); assertThat(ct.getTarget().getVars(0)).isEqualTo(2); assertThat(ct.getTarget().getCoeffs(0)).isEqualTo(1); assertThat(ct.getExprsCount()).isEqualTo(2); assertThat(ct.getExprs(0).getVarsCount()).isEqualTo(1); assertThat(ct.getExprs(0).getVars(0)).isEqualTo(0); assertThat(ct.getExprs(0).getCoeffs(0)).isEqualTo(1); assertThat(ct.getExprs(1).getVarsCount()).isEqualTo(1); assertThat(ct.getExprs(1).getVars(0)).isEqualTo(1); assertThat(ct.getExprs(1).getCoeffs(0)).isEqualTo(1); } @Test public void testCpModel_addMinExprEquality() throws Exception { final CpModel model = new CpModel(); assertNotNull(model); final IntVar x = model.newBoolVar("x"); final IntVar t = model.newBoolVar("t"); model.addMinEquality(LinearExpr.newBuilder().addTerm(t, -3), new LinearExpr[] { LinearExpr.newBuilder().addTerm(x, 2).add(1).build(), LinearExpr.constant(5)}); assertThat(model.model().getConstraintsCount()).isEqualTo(1); assertThat(model.model().getConstraints(0).hasLinMax()).isTrue(); LinearArgumentProto ct = model.model().getConstraints(0).getLinMax(); assertThat(ct.getTarget().getVarsCount()).isEqualTo(1); assertThat(ct.getTarget().getVars(0)).isEqualTo(1); assertThat(ct.getTarget().getCoeffs(0)).isEqualTo(3); assertThat(ct.getExprsCount()).isEqualTo(2); assertThat(ct.getExprs(0).getVarsCount()).isEqualTo(1); assertThat(ct.getExprs(0).getVars(0)).isEqualTo(0); assertThat(ct.getExprs(0).getCoeffs(0)).isEqualTo(-2); assertThat(ct.getExprs(0).getOffset()).isEqualTo(-1); assertThat(ct.getExprs(1).getVarsCount()).isEqualTo(0); assertThat(ct.getExprs(1).getOffset()).isEqualTo(-5); } @Test public void testCpModel_addAbsEquality() throws Exception { final CpModel model = new CpModel(); assertNotNull(model); final IntVar x = model.newBoolVar("x"); final IntVar t = model.newBoolVar("t"); model.addAbsEquality( LinearExpr.newBuilder().addTerm(t, -3), LinearExpr.newBuilder().addTerm(x, 2).add(1)); assertThat(model.model().getConstraintsCount()).isEqualTo(1); assertThat(model.model().getConstraints(0).hasLinMax()).isTrue(); LinearArgumentProto ct = model.model().getConstraints(0).getLinMax(); assertThat(ct.getTarget().getVarsCount()).isEqualTo(1); assertThat(ct.getTarget().getVars(0)).isEqualTo(1); assertThat(ct.getTarget().getCoeffs(0)).isEqualTo(-3); assertThat(ct.getExprsCount()).isEqualTo(2); assertThat(ct.getExprs(0).getVarsCount()).isEqualTo(1); assertThat(ct.getExprs(0).getVars(0)).isEqualTo(0); assertThat(ct.getExprs(0).getCoeffs(0)).isEqualTo(2); assertThat(ct.getExprs(0).getOffset()).isEqualTo(1); assertThat(ct.getExprs(1).getVarsCount()).isEqualTo(1); assertThat(ct.getExprs(1).getVars(0)).isEqualTo(0); assertThat(ct.getExprs(1).getCoeffs(0)).isEqualTo(-2); assertThat(ct.getExprs(1).getOffset()).isEqualTo(-1); } @Test public void testCpModel_addCircuit() throws Exception { final CpModel model = new CpModel(); assertNotNull(model); final Literal x1 = model.newBoolVar("x1"); final Literal x2 = model.newBoolVar("x2"); final Literal x3 = model.newBoolVar("x3"); CircuitConstraint circuit = model.addCircuit(); circuit.addArc(0, 1, x1); circuit.addArc(1, 2, x2.not()); circuit.addArc(2, 0, x3); assertThat(model.model().getConstraintsCount()).isEqualTo(1); assertThat(model.model().getConstraints(0).hasCircuit()).isTrue(); assertThat(model.model().getConstraints(0).getCircuit().getTailsCount()).isEqualTo(3); assertThat(model.model().getConstraints(0).getCircuit().getHeadsCount()).isEqualTo(3); assertThat(model.model().getConstraints(0).getCircuit().getLiteralsCount()).isEqualTo(3); } @Test public void testCpModel_addMultipleCircuit() throws Exception { final CpModel model = new CpModel(); assertNotNull(model); final Literal x1 = model.newBoolVar("x1"); final Literal x2 = model.newBoolVar("x2"); final Literal x3 = model.newBoolVar("x3"); MultipleCircuitConstraint circuit = model.addMultipleCircuit(); circuit.addArc(0, 1, x1); circuit.addArc(1, 2, x2.not()); circuit.addArc(2, 0, x3); assertThat(model.model().getConstraintsCount()).isEqualTo(1); assertThat(model.model().getConstraints(0).hasRoutes()).isTrue(); assertThat(model.model().getConstraints(0).getRoutes().getTailsCount()).isEqualTo(3); assertThat(model.model().getConstraints(0).getRoutes().getHeadsCount()).isEqualTo(3); assertThat(model.model().getConstraints(0).getRoutes().getLiteralsCount()).isEqualTo(3); } @Test public void testCpModel_addAutomaton() throws Exception { final CpModel model = new CpModel(); assertNotNull(model); final IntVar x1 = model.newIntVar(0, 5, "x1"); final IntVar x2 = model.newIntVar(0, 5, "x2"); final IntVar x3 = model.newIntVar(0, 5, "x3"); AutomatonConstraint automaton = model.addAutomaton(new IntVar[] {x1, x2, x3}, 0, new long[] {1, 2}); automaton.addTransition(0, 1, 0); automaton.addTransition(1, 1, 1); automaton.addTransition(1, 2, 2); assertThat(model.model().getConstraintsCount()).isEqualTo(1); assertThat(model.model().getConstraints(0).hasAutomaton()).isTrue(); assertThat(model.model().getConstraints(0).hasAutomaton()).isTrue(); assertThat(model.model().getConstraints(0).getAutomaton().getTransitionTailCount()) .isEqualTo(3); assertThat(model.model().getConstraints(0).getAutomaton().getTransitionHeadCount()) .isEqualTo(3); assertThat(model.model().getConstraints(0).getAutomaton().getTransitionLabelCount()) .isEqualTo(3); assertThat(model.model().getConstraints(0).getAutomaton().getStartingState()).isEqualTo(0); assertThat(model.model().getConstraints(0).getAutomaton().getFinalStatesCount()).isEqualTo(2); } @Test public void testCpModel_addNoOverlap() throws Exception { final CpModel model = new CpModel(); assertNotNull(model); final int horizon = 100; final IntVar startVar1 = model.newIntVar(0, horizon, "start1"); final int duration1 = 10; final IntervalVar interval1 = model.newFixedSizeIntervalVar(startVar1, duration1, "interval1"); final IntVar startVar2 = model.newIntVar(0, horizon, "start2"); final int duration2 = 15; final IntervalVar interval2 = model.newFixedSizeIntervalVar(startVar2, duration2, "interval2"); model.addNoOverlap(new IntervalVar[] {interval1, interval2}); assertThat(model.model().getConstraintsCount()).isEqualTo(3); assertThat(model.model().getConstraints(0).hasInterval()).isTrue(); assertThat(model.model().getConstraints(1).hasInterval()).isTrue(); assertThat(model.model().getConstraints(2).hasNoOverlap()).isTrue(); assertThat(model.model().getConstraints(2).getNoOverlap().getIntervalsCount()).isEqualTo(2); } @Test public void testCpModel_addCumulative() throws Exception { final CpModel model = new CpModel(); assertNotNull(model); final int horizon = 100; final IntVar startVar1 = model.newIntVar(0, horizon, "start1"); final int duration1 = 10; final int demand1 = 20; final IntervalVar interval1 = model.newFixedSizeIntervalVar(startVar1, duration1, "interval1"); final IntVar startVar2 = model.newIntVar(0, horizon, "start2"); final IntVar demandVar2 = model.newIntVar(2, 5, "demand2"); final int duration2 = 15; final IntervalVar interval2 = model.newFixedSizeIntervalVar(startVar2, duration2, "interval2"); CumulativeConstraint cumul = model.addCumulative(13); cumul.addDemand(interval1, demand1); cumul.addDemand(interval2, demandVar2); assertThat(model.model().getConstraintsCount()).isEqualTo(3); assertThat(model.model().getConstraints(0).hasInterval()).isTrue(); assertThat(model.model().getConstraints(1).hasInterval()).isTrue(); assertThat(model.model().getConstraints(2).hasCumulative()).isTrue(); assertThat(model.model().getConstraints(2).getCumulative().getIntervalsCount()).isEqualTo(2); cumul.addDemands(new IntervalVar[] {interval1}, new int[] {2}); cumul.addDemands(new IntervalVar[] {interval1}, new long[] {2}); cumul.addDemands( new IntervalVar[] {interval2}, new LinearArgument[] {LinearExpr.affine(demandVar2, 1, 2)}); cumul.addDemands( new IntervalVar[] {interval2}, new LinearExpr[] {LinearExpr.affine(demandVar2, 1, 3)}); assertThat(model.model().getConstraints(2).getCumulative().getIntervalsCount()).isEqualTo(6); } @Test public void testCpModel_addNoOverlap2D() throws Exception { final CpModel model = new CpModel(); assertNotNull(model); final int horizon = 100; final IntVar startVar1 = model.newIntVar(0, horizon, "start1"); final int duration1 = 10; final IntervalVar interval1 = model.newFixedSizeIntervalVar(startVar1, duration1, "interval1"); final IntVar startVar2 = model.newIntVar(0, horizon, "start2"); final int duration2 = 15; final IntervalVar interval2 = model.newFixedSizeIntervalVar(startVar2, duration2, "interval2"); NoOverlap2dConstraint ct = model.addNoOverlap2D(); ct.addRectangle(interval1, interval1); ct.addRectangle(interval2, interval2); assertThat(model.model().getConstraintsCount()).isEqualTo(3); assertThat(model.model().getConstraints(0).hasInterval()).isTrue(); assertThat(model.model().getConstraints(1).hasInterval()).isTrue(); assertThat(model.model().getConstraints(2).hasNoOverlap2D()).isTrue(); assertThat(model.model().getConstraints(2).getNoOverlap2D().getXIntervalsCount()).isEqualTo(2); assertThat(model.model().getConstraints(2).getNoOverlap2D().getYIntervalsCount()).isEqualTo(2); } @Test public void testCpModel_modelStats() throws Exception { final CpModel model = new CpModel(); assertNotNull(model); final BoolVar x = model.newBoolVar("x"); final BoolVar y = model.newBoolVar("y"); model.addImplication(x, y); String stats = model.modelStats(); assertThat(stats).isNotEmpty(); } @Test public void testCpModel_validateOk() throws Exception { final CpModel model = new CpModel(); assertNotNull(model); final BoolVar x = model.newBoolVar("x"); final BoolVar y = model.newBoolVar("y"); model.addImplication(x, y); String stats = model.validate(); assertThat(stats).isEmpty(); } @Test public void testCpModel_validateNotOk() throws Exception { final CpModel model = new CpModel(); assertNotNull(model); final IntVar x = model.newIntVar(0, 9223372036854775807L, "x"); final IntVar y = model.newIntVar(0, 10, "y"); model.addLinearExpressionInDomain(LinearExpr.newBuilder().add(x).add(y), Domain.fromFlatIntervals(new long[] {6, 9223372036854775807L})); String stats = model.validate(); assertThat(stats).isNotEmpty(); } @Test public void testCpModel_exceptionVisibility() throws Exception { CpModel.MismatchedArrayLengths ex1 = new CpModel.MismatchedArrayLengths("test1", "ar1", "ar2"); CpModel.WrongLength ex2 = new CpModel.WrongLength("test2", "ar"); assertThat(ex1).hasMessageThat().isEqualTo("test1: ar1 and ar2 have mismatched lengths"); assertThat(ex2).hasMessageThat().isEqualTo("test2: ar"); } @Test public void testCpModel_clearConstraint() throws Exception { final CpModel model = new CpModel(); assertNotNull(model); final IntVar x = model.newIntVar(0, 92, "x"); final IntVar y = model.newIntVar(0, 10, "y"); List<Constraint> constraints = new ArrayList<>(); for (int i = 0; i < 10; ++i) { Constraint ct = model.addLinearExpressionInDomain(LinearExpr.newBuilder().add(x).add(y), Domain.fromFlatIntervals(new long[] {6 + i, 92 - i})); constraints.add(ct); } for (int i = 0; i < 10; ++i) { Constraint ct = constraints.get(i); assertThat(ct.getBuilder().toString()) .isEqualTo(model.getBuilder().getConstraintsBuilder(i).toString()); assertThat(ct.getBuilder().hasLinear()).isTrue(); assertThat(model.getBuilder().getConstraintsBuilder(i).hasLinear()).isTrue(); assertThat(ct.getBuilder().toString()) .isEqualTo(model.getBuilder().getConstraintsBuilder(i).toString()); } for (int i = 0; i < 10; ++i) { Constraint ct = constraints.get(i); ct.getBuilder().clear(); } for (int i = 0; i < 10; ++i) { Constraint ct = constraints.get(i); assertThat(ct.getBuilder().hasLinear()).isFalse(); assertThat(model.getBuilder().getConstraintsBuilder(i).hasLinear()).isFalse(); } } @Test public void testCpModel_minimize() throws Exception { final CpModel model = new CpModel(); assertNotNull(model); final IntVar x1 = model.newIntVar(0, 5, "x1"); final IntVar x2 = model.newIntVar(0, 5, "x2"); final IntVar x3 = model.newIntVar(0, 5, "x3"); model.minimize(LinearExpr.sum(new IntVar[] {x1, x2})); assertThat(model.getBuilder().getObjectiveBuilder().getVarsCount()).isEqualTo(2); assertThat(model.getBuilder().hasFloatingPointObjective()).isFalse(); model.minimize(x3); assertThat(model.getBuilder().getObjectiveBuilder().getVarsCount()).isEqualTo(1); assertThat(model.getBuilder().hasFloatingPointObjective()).isFalse(); model.minimize(LinearExpr.sum(new IntVar[] {x1, x2})); assertThat(model.getBuilder().getObjectiveBuilder().getVarsCount()).isEqualTo(2); assertThat(model.getBuilder().hasFloatingPointObjective()).isFalse(); model.minimize(DoubleLinearExpr.weightedSum(new IntVar[] {x1, x2}, new double[] {2.5, 3.5})); assertThat(model.getBuilder().getFloatingPointObjectiveBuilder().getVarsCount()).isEqualTo(2); assertThat(model.getBuilder().hasObjective()).isFalse(); model.minimize(DoubleLinearExpr.affine(x3, 1.4, 1.2)); assertThat(model.getBuilder().getFloatingPointObjectiveBuilder().getVarsCount()).isEqualTo(1); assertThat(model.getBuilder().hasObjective()).isFalse(); model.maximize(LinearExpr.sum(new IntVar[] {x1, x2})); assertThat(model.getBuilder().getObjectiveBuilder().getVarsCount()).isEqualTo(2); assertThat(model.getBuilder().hasFloatingPointObjective()).isFalse(); model.maximize(x3); assertThat(model.getBuilder().getObjectiveBuilder().getVarsCount()).isEqualTo(1); assertThat(model.getBuilder().hasFloatingPointObjective()).isFalse(); model.maximize(DoubleLinearExpr.weightedSum(new IntVar[] {x1, x2}, new double[] {2.5, 3.5})); assertThat(model.getBuilder().getFloatingPointObjectiveBuilder().getVarsCount()).isEqualTo(2); assertThat(model.getBuilder().hasObjective()).isFalse(); model.maximize(DoubleLinearExpr.affine(x3, 1.4, 1.2)); assertThat(model.getBuilder().getFloatingPointObjectiveBuilder().getVarsCount()).isEqualTo(1); assertThat(model.getBuilder().hasObjective()).isFalse(); } }
25,630
42.077311
100
java
or-tools
or-tools-master/examples/tests/CpSolverTest.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.sat; import static com.google.common.truth.Truth.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import com.google.ortools.Loader; import com.google.ortools.sat.CpSolverStatus; import com.google.ortools.util.Domain; import java.util.function.Consumer; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** Tests the CpSolver java interface. */ public final class CpSolverTest { @BeforeEach public void setUp() { Loader.loadNativeLibraries(); } static class SolutionCounter extends CpSolverSolutionCallback { public SolutionCounter() {} @Override public void onSolutionCallback() { solutionCount++; } private int solutionCount; public int getSolutionCount() { return solutionCount; } } static class LogToString { public LogToString() { logBuilder = new StringBuilder(); } public void newMessage(String message) { logBuilder.append(message).append("\n"); } private final StringBuilder logBuilder; public String getLog() { return logBuilder.toString(); } } @Test public void testCpSolver_solve() throws Exception { final CpModel model = new CpModel(); assertNotNull(model); // Creates the variables. int numVals = 3; final IntVar x = model.newIntVar(0, numVals - 1, "x"); final IntVar y = model.newIntVar(0, numVals - 1, "y"); // Creates the constraints. model.addDifferent(x, y); // Creates a solver and solves the model. final CpSolver solver = new CpSolver(); assertNotNull(solver); final CpSolverStatus status = solver.solve(model); assertThat(status).isEqualTo(CpSolverStatus.OPTIMAL); assertThat(solver.value(x)).isNotEqualTo(solver.value(y)); final String stats = solver.responseStats(); assertThat(stats).isNotEmpty(); } @Test public void testCpSolver_invalidModel() throws Exception { final CpModel model = new CpModel(); assertNotNull(model); // Creates the variables. int numVals = 3; final IntVar x = model.newIntVar(0, -1, "x"); final IntVar y = model.newIntVar(0, numVals - 1, "y"); // Creates the constraints. model.addDifferent(x, y); // Creates a solver and solves the model. final CpSolver solver = new CpSolver(); assertNotNull(solver); final CpSolverStatus status = solver.solve(model); assertThat(status).isEqualTo(CpSolverStatus.MODEL_INVALID); assertEquals("var #0 has no domain(): name: \"x\"", solver.getSolutionInfo()); } @Test public void testCpSolver_hinting() throws Exception { final CpModel model = new CpModel(); assertNotNull(model); final IntVar x = model.newIntVar(0, 5, "x"); final IntVar y = model.newIntVar(0, 6, "y"); // Creates the constraints. model.addEquality(LinearExpr.newBuilder().add(x).add(y), 6); // Add hints. model.addHint(x, 2); model.addHint(y, 4); // Creates a solver and solves the model. final CpSolver solver = new CpSolver(); assertNotNull(solver); solver.getParameters().setCpModelPresolve(false); final CpSolverStatus status = solver.solve(model); assertThat(status).isEqualTo(CpSolverStatus.OPTIMAL); assertThat(solver.value(x)).isEqualTo(2); assertThat(solver.value(y)).isEqualTo(4); } @Test public void testCpSolver_booleanValue() throws Exception { final CpModel model = new CpModel(); assertNotNull(model); final BoolVar x = model.newBoolVar("x"); final BoolVar y = model.newBoolVar("y"); model.addBoolOr(new Literal[] {x, y.not()}); // Creates a solver and solves the model. final CpSolver solver = new CpSolver(); assertNotNull(solver); final CpSolverStatus status = solver.solve(model); assertEquals(CpSolverStatus.OPTIMAL, status); assertThat(solver.booleanValue(x) || solver.booleanValue(y.not())).isTrue(); } @Test public void testCpSolver_searchAllSolutions() throws Exception { final CpModel model = new CpModel(); assertNotNull(model); // Creates the variables. int numVals = 3; final IntVar x = model.newIntVar(0, numVals - 1, "x"); final IntVar y = model.newIntVar(0, numVals - 1, "y"); model.newIntVar(0, numVals - 1, "z"); // Creates the constraints. model.addDifferent(x, y); // Creates a solver and solves the model. final CpSolver solver = new CpSolver(); assertNotNull(solver); final SolutionCounter cb = new SolutionCounter(); solver.searchAllSolutions(model, cb); assertThat(cb.getSolutionCount()).isEqualTo(18); assertThat(solver.numBranches()).isGreaterThan(0L); } @Test public void testCpSolver_objectiveValue() throws Exception { final CpModel model = new CpModel(); assertNotNull(model); // Creates the variables. final int numVals = 3; final IntVar x = model.newIntVar(0, numVals - 1, "x"); final IntVar y = model.newIntVar(0, numVals - 1, "y"); final IntVar z = model.newIntVar(0, numVals - 1, "z"); // Creates the constraints. model.addDifferent(x, y); // Maximizes a linear combination of variables. model.maximize(LinearExpr.newBuilder().add(x).addTerm(y, 2).addTerm(z, 3)); // Creates a solver and solves the model. final CpSolver solver = new CpSolver(); assertNotNull(solver); CpSolverStatus status = solver.solve(model); assertThat(status).isEqualTo(CpSolverStatus.OPTIMAL); assertThat(solver.objectiveValue()).isEqualTo(11.0); assertThat(solver.value(LinearExpr.newBuilder().addSum(new IntVar[] {x, y, z}).build())) .isEqualTo(solver.value(x) + solver.value(y) + solver.value(z)); } @Test public void testCpModel_crashPresolve() throws Exception { final CpModel model = new CpModel(); assertNotNull(model); // Create decision variables final IntVar x = model.newIntVar(0, 5, "x"); final IntVar y = model.newIntVar(0, 5, "y"); // Create a linear constraint which enforces that only x or y can be greater than 0. model.addLinearConstraint(LinearExpr.newBuilder().add(x).add(y), 0, 1); // Create the objective variable final IntVar obj = model.newIntVar(0, 3, "obj"); // Cut the domain of the objective variable model.addGreaterOrEqual(obj, 2); // Set a constraint that makes the problem infeasible model.addMaxEquality(obj, new IntVar[] {x, y}); // Optimize objective model.minimize(obj); // Create a solver and solve the model. final CpSolver solver = new CpSolver(); assertNotNull(solver); com.google.ortools.sat.CpSolverStatus status = solver.solve(model); assertThat(status).isEqualTo(CpSolverStatus.INFEASIBLE); } @Test public void testCpSolver_customLog() throws Exception { final CpModel model = new CpModel(); assertNotNull(model); // Creates the variables. final int numVals = 3; final IntVar x = model.newIntVar(0, numVals - 1, "x"); final IntVar y = model.newIntVar(0, numVals - 1, "y"); // Creates the constraints. model.addDifferent(x, y); // Creates a solver and solves the model. final CpSolver solver = new CpSolver(); assertNotNull(solver); StringBuilder logBuilder = new StringBuilder(); Consumer<String> appendToLog = (String message) -> logBuilder.append(message).append('\n'); solver.setLogCallback(appendToLog); solver.getParameters().setLogToStdout(false).setLogSearchProgress(true); CpSolverStatus status = solver.solve(model); assertThat(status).isEqualTo(CpSolverStatus.OPTIMAL); String log = logBuilder.toString(); assertThat(log).isNotEmpty(); assertThat(log).contains("Parameters"); assertThat(log).contains("log_to_stdout: false"); assertThat(log).contains("OPTIMAL"); } @Test public void testCpSolver_customLogMultiThread() { final CpModel model = new CpModel(); assertNotNull(model); // Creates the variables. int numVals = 3; IntVar x = model.newIntVar(0, numVals - 1, "x"); IntVar y = model.newIntVar(0, numVals - 1, "y"); // Creates the constraints. model.addDifferent(x, y); // Creates a solver and solves the model. final CpSolver solver = new CpSolver(); assertNotNull(solver); StringBuilder logBuilder = new StringBuilder(); Consumer<String> appendToLog = (String message) -> logBuilder.append(message).append('\n'); solver.setLogCallback(appendToLog); solver.getParameters().setLogToStdout(false).setLogSearchProgress(true).setNumSearchWorkers(12); CpSolverStatus status = solver.solve(model); assertThat(status).isEqualTo(CpSolverStatus.OPTIMAL); String log = logBuilder.toString(); assertThat(log).isNotEmpty(); assertThat(log).contains("Parameters"); assertThat(log).contains("log_to_stdout: false"); assertThat(log).contains("OPTIMAL"); } @Test public void issue3108() { final CpModel model = new CpModel(); final IntVar var1 = model.newIntVar(0, 1, "CONTROLLABLE__C1[0]"); final IntVar var2 = model.newIntVar(0, 1, "CONTROLLABLE__C1[1]"); capacityConstraint(model, new IntVar[] {var1, var2}, new long[] {0L, 1L}, new long[][] {new long[] {1L, 1L}}, new long[][] {new long[] {1L, 1L}}); final CpSolver solver = new CpSolver(); solver.getParameters().setLogSearchProgress(false); solver.getParameters().setCpModelProbingLevel(0); solver.getParameters().setNumSearchWorkers(4); solver.getParameters().setMaxTimeInSeconds(1); final CpSolverStatus status = solver.solve(model); assertEquals(status, CpSolverStatus.OPTIMAL); } private static void capacityConstraint(final CpModel model, final IntVar[] varsToAssign, final long[] domainArr, final long[][] demands, final long[][] capacities) { final int numTasks = varsToAssign.length; final int numResources = demands.length; final IntervalVar[] tasksIntervals = new IntervalVar[numTasks + capacities[0].length]; final Domain domainT = Domain.fromValues(domainArr); final Domain intervalRange = Domain.fromFlatIntervals(new long[] {domainT.min() + 1, domainT.max() + 1}); final int unitIntervalSize = 1; for (int i = 0; i < numTasks; i++) { final BoolVar presence = model.newBoolVar(""); model.addLinearExpressionInDomain(varsToAssign[i], domainT).onlyEnforceIf(presence); model.addLinearExpressionInDomain(varsToAssign[i], domainT.complement()) .onlyEnforceIf(presence.not()); // interval with start as taskToNodeAssignment and size of 1 tasksIntervals[i] = model.newOptionalFixedSizeIntervalVar(varsToAssign[i], unitIntervalSize, presence, ""); } // Create dummy intervals for (int i = numTasks; i < tasksIntervals.length; i++) { final int nodeIndex = i - numTasks; tasksIntervals[i] = model.newFixedInterval(domainArr[nodeIndex], 1, ""); } // Convert to list of arrays final long[][] nodeCapacities = new long[numResources][]; final long[] maxCapacities = new long[numResources]; for (int i = 0; i < capacities.length; i++) { final long[] capacityArr = capacities[i]; long maxCapacityValue = Long.MIN_VALUE; for (int j = 0; j < capacityArr.length; j++) { maxCapacityValue = Math.max(maxCapacityValue, capacityArr[j]); } nodeCapacities[i] = capacityArr; maxCapacities[i] = maxCapacityValue; } // For each resource, create dummy demands to accommodate heterogeneous capacities final long[][] updatedDemands = new long[numResources][]; for (int i = 0; i < numResources; i++) { final long[] demand = new long[numTasks + capacities[0].length]; // copy ver task demands int iter = 0; for (final long taskDemand : demands[i]) { demand[iter] = taskDemand; iter++; } // copy over dummy demands final long maxCapacity = maxCapacities[i]; for (final long nodeHeterogeneityAdjustment : nodeCapacities[i]) { demand[iter] = maxCapacity - nodeHeterogeneityAdjustment; iter++; } updatedDemands[i] = demand; } // 2. Capacity constraints for (int i = 0; i < numResources; i++) { model.addCumulative(maxCapacities[i]).addDemands(tasksIntervals, updatedDemands[i]); } // Cumulative score for (int i = 0; i < numResources; i++) { final IntVar max = model.newIntVar(0, maxCapacities[i], ""); model.addCumulative(max).addDemands(tasksIntervals, updatedDemands[i]).getBuilder(); model.minimize(max); } } }
13,245
34.607527
100
java
or-tools
or-tools-master/examples/tests/FlowTest.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.graph; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import com.google.ortools.Loader; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** Test the Min/Max Flow solver java interface. */ public final class FlowTest { @BeforeEach public void setUp() { Loader.loadNativeLibraries(); } @Test public void testMinCostFlow() { final int numSources = 4; final int numTargets = 4; final int[][] costs = { {90, 75, 75, 80}, {35, 85, 55, 65}, {125, 95, 90, 105}, {45, 110, 95, 115}}; final int expectedCost = 275; final MinCostFlow minCostFlow = new MinCostFlow(); assertNotNull(minCostFlow); for (int source = 0; source < numSources; ++source) { for (int target = 0; target < numTargets; ++target) { minCostFlow.addArcWithCapacityAndUnitCost( source, numSources + target, 1, costs[source][target]); } } for (int source = 0; source < numSources; ++source) { minCostFlow.setNodeSupply(source, 1); } for (int target = 0; target < numTargets; ++target) { minCostFlow.setNodeSupply(numSources + target, -1); } final MinCostFlowBase.Status solveStatus = minCostFlow.solve(); assertEquals(solveStatus, MinCostFlow.Status.OPTIMAL); final long totalFlowCost = minCostFlow.getOptimalCost(); assertEquals(expectedCost, totalFlowCost); } @Test public void testMaxFlow() { final int numNodes = 6; final int numArcs = 9; final int[] tails = {0, 0, 0, 0, 1, 2, 3, 3, 4}; final int[] heads = {1, 2, 3, 4, 3, 4, 4, 5, 5}; final int[] capacities = {5, 8, 2, 0, 4, 5, 6, 0, 4}; final int[] expectedFlows = {4, 4, 2, 0, 4, 4, 0, 6, 4}; final int expectedTotalFlow = 10; final MaxFlow maxFlow = new MaxFlow(); assertNotNull(maxFlow); for (int i = 0; i < numArcs; ++i) { maxFlow.addArcWithCapacity(tails[i], heads[i], capacities[i]); } maxFlow.setArcCapacity(7, 6); final MaxFlow.Status solveStatus = maxFlow.solve(/*source=*/0, /*sink=*/numNodes - 1); assertEquals(solveStatus, MaxFlow.Status.OPTIMAL); final long totalFlow = maxFlow.getOptimalFlow(); assertEquals(expectedTotalFlow, totalFlow); for (int i = 0; i < numArcs; ++i) { assertEquals(maxFlow.getFlow(i), expectedFlows[i]); } } }
3,010
35.719512
90
java
or-tools
or-tools-master/examples/tests/InitTest.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.init; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.ortools.Loader; import com.google.ortools.init.CppBridge; import com.google.ortools.init.CppFlags; import com.google.ortools.init.OrToolsVersion; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** Tests the Init java interface. */ public final class InitTest { @BeforeEach public void setUp() { Loader.loadNativeLibraries(); } @Test public void testLogging() { CppBridge.initLogging("init"); CppBridge.shutdownLogging(); } @Test public void testFlags() { final CppFlags cpp_flags = new CppFlags(); assertNotNull(cpp_flags); cpp_flags.setLogtostderr(true); cpp_flags.setLog_prefix(true); cpp_flags.setCp_model_dump_prefix("init"); cpp_flags.setCp_model_dump_models(true); cpp_flags.setCp_model_dump_lns(true); cpp_flags.setCp_model_dump_response(true); CppBridge.setFlags(cpp_flags); } @Test public void testVersion() { final OrToolsVersion v = new OrToolsVersion(); assertNotNull(v); final int major = v.getMajorNumber(); final int minor = v.getMinorNumber(); final int patch = v.getPatchNumber(); final String version = v.getVersionString(); final String check = major + "." + minor + "." + patch; assertEquals(check, version); } }
2,155
31.666667
75
java
or-tools
or-tools-master/examples/tests/KnapsackSolverTest.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.algorithms; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import com.google.ortools.Loader; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** Test the Knapsack solver java interface. */ public final class KnapsackSolverTest { @BeforeEach public void setUp() { Loader.loadNativeLibraries(); } @Test public void testKnapsackSolver() { final KnapsackSolver solver = new KnapsackSolver( KnapsackSolver.SolverType.KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER, "test"); assertNotNull(solver); 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[] capacities = {850}; solver.init(profits, weights, capacities); final long computedProfit = solver.solve(); assertEquals(7534, computedProfit); } }
1,931
38.428571
100
java
or-tools
or-tools-master/examples/tests/LinearExprTest.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.sat; import static com.google.common.truth.Truth.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import com.google.ortools.Loader; import com.google.ortools.util.Domain; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public final class LinearExprTest { @BeforeEach public void setUp() { Loader.loadNativeLibraries(); } @Test public void testLinearExpr_add() { final CpModel model = new CpModel(); assertNotNull(model); final Domain domain = new Domain(0, 10); final IntVar y = model.newIntVarFromDomain(domain, "y"); final LinearExpr expr = LinearExpr.newBuilder().add(y).build(); assertNotNull(expr); assertEquals(1, expr.numElements()); assertEquals(y.getIndex(), expr.getVariableIndex(0)); assertEquals(1, expr.getCoefficient(0)); assertEquals(0, expr.getOffset()); } @Test public void testLinearExpr_add_literal() { final CpModel model = new CpModel(); assertNotNull(model); final BoolVar y = model.newBoolVar("y"); final LinearExpr expr = LinearExpr.newBuilder().add(y).build(); assertNotNull(expr); assertEquals(1, expr.numElements()); assertEquals(y.getIndex(), expr.getVariableIndex(0)); assertEquals(1, expr.getCoefficient(0)); assertEquals(0, expr.getOffset()); } @Test public void testLinearExpr_add_negated_literal() { final CpModel model = new CpModel(); assertNotNull(model); final BoolVar y = model.newBoolVar("y"); final LinearExpr expr = LinearExpr.newBuilder().add(y.not()).build(); assertNotNull(expr); assertEquals(1, expr.numElements()); assertEquals(y.getIndex(), expr.getVariableIndex(0)); assertEquals(-1, expr.getCoefficient(0)); assertEquals(1, expr.getOffset()); } @Test public void testLinearExpr_term() { final CpModel model = new CpModel(); assertNotNull(model); final Domain domain = new Domain(0, 10); final IntVar y = model.newIntVarFromDomain(domain, "y"); final LinearExpr expr = LinearExpr.newBuilder().addTerm(y, 12).build(); assertNotNull(expr); assertEquals(1, expr.numElements()); assertEquals(y.getIndex(), expr.getVariableIndex(0)); assertEquals(12, expr.getCoefficient(0)); assertEquals(0, expr.getOffset()); } @Test public void testLinearExpr_booleanTerm() { final CpModel model = new CpModel(); assertNotNull(model); final Literal y = model.newBoolVar("y"); final LinearExpr expr = LinearExpr.newBuilder().addTerm(y.not(), 12).build(); assertNotNull(expr); assertThat(expr.numElements()).isEqualTo(1); assertThat(expr.getVariableIndex(0)).isEqualTo(y.getIndex()); assertThat(expr.getCoefficient(0)).isEqualTo(-12); assertThat(expr.getOffset()).isEqualTo(12); } @Test public void testLinearExpr_affine() { final CpModel model = new CpModel(); assertNotNull(model); final Domain domain = new Domain(0, 10); final IntVar y = model.newIntVarFromDomain(domain, "y"); final LinearExpr expr = LinearExpr.newBuilder().addTerm(y, 12).add(5).build(); assertNotNull(expr); assertThat(expr.numElements()).isEqualTo(1); assertThat(expr.getVariableIndex(0)).isEqualTo(y.getIndex()); assertThat(expr.getCoefficient(0)).isEqualTo(12); assertThat(expr.getOffset()).isEqualTo(5); } @Test public void testLinearExpr_booleanAffine() { final CpModel model = new CpModel(); assertNotNull(model); final Literal y = model.newBoolVar("y"); final LinearExpr expr = LinearExpr.newBuilder().addTerm(y.not(), 12).add(5).build(); assertNotNull(expr); assertThat(expr.numElements()).isEqualTo(1); assertThat(expr.getVariableIndex(0)).isEqualTo(y.getIndex()); assertThat(expr.getCoefficient(0)).isEqualTo(-12); assertThat(expr.getOffset()).isEqualTo(17); } @Test public void testLinearExpr_sum() { final CpModel model = new CpModel(); assertNotNull(model); final Domain domain = new Domain(0, 10); final IntVar x = model.newIntVarFromDomain(domain, "x"); final IntVar y = model.newIntVarFromDomain(domain, "y"); final LinearExpr expr = LinearExpr.newBuilder().add(x).add(y).build(); assertNotNull(expr); assertThat(expr.numElements()).isEqualTo(2); assertThat(expr.getVariableIndex(0)).isEqualTo(x.getIndex()); assertThat(expr.getCoefficient(0)).isEqualTo(1); assertThat(expr.getVariableIndex(1)).isEqualTo(y.getIndex()); assertThat(expr.getCoefficient(1)).isEqualTo(1); assertThat(expr.getOffset()).isEqualTo(0); } @Test public void testLinearExpr_weightedSum() { final CpModel model = new CpModel(); assertNotNull(model); final Domain domain = new Domain(0, 10); final IntVar x = model.newIntVarFromDomain(domain, "x"); final IntVar y = model.newIntVarFromDomain(domain, "y"); final LinearExpr expr = LinearExpr.newBuilder().addTerm(x, 3).addTerm(y, 5).build(); assertNotNull(expr); assertThat(expr.numElements()).isEqualTo(2); assertThat(expr.getVariableIndex(0)).isEqualTo(x.getIndex()); assertThat(expr.getCoefficient(0)).isEqualTo(3); assertThat(expr.getVariableIndex(1)).isEqualTo(y.getIndex()); assertThat(expr.getCoefficient(1)).isEqualTo(5); assertThat(expr.getOffset()).isEqualTo(0); } @Test public void testLinearExpr_booleanSum() { final CpModel model = new CpModel(); assertNotNull(model); final Literal x = model.newBoolVar("x"); final Literal y = model.newBoolVar("y"); final LinearExpr expr = LinearExpr.newBuilder().add(x).add(y.not()).build(); assertNotNull(expr); assertThat(expr.numElements()).isEqualTo(2); assertThat(expr.getVariableIndex(0)).isEqualTo(x.getIndex()); assertThat(expr.getCoefficient(0)).isEqualTo(1); assertThat(expr.getVariableIndex(1)).isEqualTo(y.getIndex()); assertThat(expr.getCoefficient(1)).isEqualTo(-1); assertThat(expr.getOffset()).isEqualTo(1); } @Test public void testLinearExpr_booleanWeightedSum() { final CpModel model = new CpModel(); assertNotNull(model); final Literal x = model.newBoolVar("x"); final Literal y = model.newBoolVar("y"); final LinearExpr expr = LinearExpr.newBuilder().addTerm(x, 3).addTerm(y.not(), 5).build(); assertNotNull(expr); assertThat(expr.numElements()).isEqualTo(2); assertThat(expr.getVariableIndex(0)).isEqualTo(x.getIndex()); assertThat(expr.getCoefficient(0)).isEqualTo(3); assertThat(expr.getVariableIndex(1)).isEqualTo(y.getIndex()); assertThat(expr.getCoefficient(1)).isEqualTo(-5); assertThat(expr.getOffset()).isEqualTo(5); } }
7,343
33.478873
94
java
or-tools
or-tools-master/examples/tests/LinearSolverTest.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.linearsolver; import static com.google.common.truth.Truth.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.ortools.Loader; import com.google.ortools.linearsolver.MPModelProto; import com.google.ortools.linearsolver.MPModelRequest; import com.google.ortools.linearsolver.MPSolutionResponse; import com.google.ortools.linearsolver.MPSolverResponseStatus; import com.google.ortools.linearsolver.MPVariableProto; import com.google.ortools.linearsolver.PartialVariableAssignment; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** Test the Linear Solver java interface. */ public final class LinearSolverTest { // Numerical tolerance for checking primal, dual, objective values // and other values. private static final double NUM_TOLERANCE = 1e-5; @BeforeEach public void setUp() { Loader.loadNativeLibraries(); } private void runBasicCtor(MPSolver.OptimizationProblemType solverType) { if (!MPSolver.supportsProblemType(solverType)) { return; } final MPSolver solver = new MPSolver("testBasicCtor", solverType); assertNotNull(solver); solver.solve(); } @Test public void testMPSolver_basicCtor() { runBasicCtor(MPSolver.OptimizationProblemType.GLOP_LINEAR_PROGRAMMING); runBasicCtor(MPSolver.OptimizationProblemType.GLPK_LINEAR_PROGRAMMING); runBasicCtor(MPSolver.OptimizationProblemType.GLPK_MIXED_INTEGER_PROGRAMMING); runBasicCtor(MPSolver.OptimizationProblemType.CLP_LINEAR_PROGRAMMING); runBasicCtor(MPSolver.OptimizationProblemType.CBC_MIXED_INTEGER_PROGRAMMING); } @Test public void testMPSolver_destructor() { final MPSolver solver = new MPSolver("testDestructor", MPSolver.OptimizationProblemType.GLOP_LINEAR_PROGRAMMING); assertNotNull(solver); solver.delete(); } private void runLinearSolver( MPSolver.OptimizationProblemType problemType, boolean integerVariables) { if (!MPSolver.supportsProblemType(problemType)) { return; } final MPSolver solver = new MPSolver("Solver", problemType); assertNotNull(solver); final double infinity = MPSolver.infinity(); final MPVariable x1 = solver.makeNumVar(0.0, infinity, "x1"); final MPVariable x2 = solver.makeNumVar(0.0, infinity, "x2"); final MPVariable x3 = solver.makeNumVar(0.0, infinity, "x3"); if (integerVariables) { x1.setInteger(true); x2.setInteger(true); x3.setInteger(true); } assertEquals(3, solver.numVariables()); final MPObjective objective = solver.objective(); objective.setCoefficient(x1, 10); objective.setCoefficient(x2, 6); objective.setCoefficient(x3, 4); objective.setMaximization(); assertEquals(6.0, objective.getCoefficient(x2), 1e-6); assertTrue(objective.maximization()); assertFalse(objective.minimization()); final MPConstraint c0 = solver.makeConstraint(-1000, 100.0); c0.setCoefficient(x1, 1); c0.setCoefficient(x2, 1); c0.setCoefficient(x3, 1); final MPConstraint c1 = solver.makeConstraint(-1000, 600.0); c1.setCoefficient(x1, 10); c1.setCoefficient(x2, 4); c1.setCoefficient(x3, 5); assertEquals(4.0, c1.getCoefficient(x2), 1e-6); final MPConstraint c2 = solver.makeConstraint(-1000, 300.0); c2.setCoefficient(x1, 2); c2.setCoefficient(x2, 2); c2.setCoefficient(x3, 6); assertEquals(MPSolver.ResultStatus.OPTIMAL, solver.solve()); if (integerVariables) { assertEquals(732.0, objective.value(), NUM_TOLERANCE); assertEquals(33.0, x1.solutionValue(), NUM_TOLERANCE); assertEquals(67.0, x2.solutionValue(), NUM_TOLERANCE); assertEquals(0.0, x3.solutionValue(), NUM_TOLERANCE); } else { assertEquals(733.333333, objective.value(), NUM_TOLERANCE); assertEquals(33.333333, x1.solutionValue(), NUM_TOLERANCE); assertEquals(66.666667, x2.solutionValue(), NUM_TOLERANCE); assertEquals(0, x3.solutionValue(), NUM_TOLERANCE); } } @Test public void testMPSolver_linearSolver() { runLinearSolver(MPSolver.OptimizationProblemType.GLOP_LINEAR_PROGRAMMING, false); runLinearSolver(MPSolver.OptimizationProblemType.CLP_LINEAR_PROGRAMMING, false); runLinearSolver(MPSolver.OptimizationProblemType.GLPK_LINEAR_PROGRAMMING, false); runLinearSolver(MPSolver.OptimizationProblemType.CBC_MIXED_INTEGER_PROGRAMMING, true); runLinearSolver(MPSolver.OptimizationProblemType.GLPK_MIXED_INTEGER_PROGRAMMING, true); runLinearSolver(MPSolver.OptimizationProblemType.SCIP_MIXED_INTEGER_PROGRAMMING, true); } private void runFirstLinearExample(MPSolver.OptimizationProblemType problemType) { if (!MPSolver.supportsProblemType(problemType)) { return; } final MPSolver solver = new MPSolver("Solver", problemType); assertNotNull(solver); final MPVariable x1 = solver.makeNumVar(0.0, Double.POSITIVE_INFINITY, "x1"); final MPVariable x2 = solver.makeNumVar(0.0, Double.POSITIVE_INFINITY, "x2"); final MPVariable x3 = solver.makeNumVar(0.0, Double.POSITIVE_INFINITY, "x3"); assertEquals(3, solver.numVariables()); final double[] obj = {10.0, 6.0, 4.0}; final MPObjective objective = solver.objective(); objective.setCoefficient(x1, obj[0]); objective.setCoefficient(x2, obj[1]); objective.setCoefficient(x3, obj[2]); objective.setMaximization(); final double rhs0 = 100.0; final MPConstraint c0 = solver.makeConstraint(-Double.POSITIVE_INFINITY, rhs0, "c0"); final double[] coef0 = {1.0, 1.0, 1.0}; c0.setCoefficient(x1, coef0[0]); c0.setCoefficient(x2, coef0[1]); c0.setCoefficient(x3, coef0[2]); final double rhs1 = 600.0; final MPConstraint c1 = solver.makeConstraint(-Double.POSITIVE_INFINITY, rhs1, "c1"); final double[] coef1 = {10.0, 4.0, 5.0}; c1.setCoefficient(x1, coef1[0]); c1.setCoefficient(x2, coef1[1]); c1.setCoefficient(x3, coef1[2]); final double rhs2 = 300.0; final MPConstraint c2 = solver.makeConstraint(-Double.POSITIVE_INFINITY, rhs2); final double[] coef2 = {2.0, 2.0, 6.0}; c2.setCoefficient(x1, coef2[0]); c2.setCoefficient(x2, coef2[1]); c2.setCoefficient(x3, coef2[2]); assertEquals(3, solver.numConstraints()); assertEquals("c0", c0.name()); assertEquals("c1", c1.name()); assertEquals("auto_c_000000002", c2.name()); // The problem has an optimal solution.; assertEquals(MPSolver.ResultStatus.OPTIMAL, solver.solve()); assertEquals(733.333333, objective.value(), NUM_TOLERANCE); assertEquals(33.333333, x1.solutionValue(), NUM_TOLERANCE); assertEquals(66.666667, x2.solutionValue(), NUM_TOLERANCE); assertEquals(0, x3.solutionValue(), NUM_TOLERANCE); // c0 and c1 are binding; final double[] activities = solver.computeConstraintActivities(); assertEquals(3, activities.length); assertEquals(3.333333, c0.dualValue(), NUM_TOLERANCE); assertEquals(0.666667, c1.dualValue(), NUM_TOLERANCE); assertEquals(rhs0, activities[c0.index()], NUM_TOLERANCE); assertEquals(rhs1, activities[c1.index()], NUM_TOLERANCE); assertEquals(MPSolver.BasisStatus.AT_UPPER_BOUND, c0.basisStatus()); assertEquals(MPSolver.BasisStatus.AT_UPPER_BOUND, c1.basisStatus()); // c2 is not binding; assertEquals(0.0, c2.dualValue(), NUM_TOLERANCE); assertEquals(200.0, activities[c2.index()], NUM_TOLERANCE); assertEquals(MPSolver.BasisStatus.BASIC, c2.basisStatus()); // The optimum of the dual problem is equal to the optimum of the; // primal problem.; final double dualObjectiveValue = c0.dualValue() * rhs0 + c1.dualValue() * rhs1; assertEquals(objective.value(), dualObjectiveValue, NUM_TOLERANCE); // x1 and x2 are basic; assertEquals(0.0, x1.reducedCost(), NUM_TOLERANCE); assertEquals(0.0, x2.reducedCost(), NUM_TOLERANCE); assertEquals(MPSolver.BasisStatus.BASIC, x1.basisStatus()); assertEquals(MPSolver.BasisStatus.BASIC, x2.basisStatus()); // x3 is non-basic; final double x3ExpectedReducedCost = (obj[2] - coef0[2] * c0.dualValue() - coef1[2] * c1.dualValue()); assertEquals(x3ExpectedReducedCost, x3.reducedCost(), NUM_TOLERANCE); assertEquals(MPSolver.BasisStatus.AT_LOWER_BOUND, x3.basisStatus()); if (solver.problemType() == MPSolver.OptimizationProblemType.GLPK_LINEAR_PROGRAMMING) { assertEquals(56.333333, solver.computeExactConditionNumber(), NUM_TOLERANCE); } } @Test public void testMPSolver_firstLinearExample() { runFirstLinearExample(MPSolver.OptimizationProblemType.GLOP_LINEAR_PROGRAMMING); runFirstLinearExample(MPSolver.OptimizationProblemType.CLP_LINEAR_PROGRAMMING); runFirstLinearExample(MPSolver.OptimizationProblemType.GLPK_LINEAR_PROGRAMMING); runFirstLinearExample(MPSolver.OptimizationProblemType.GUROBI_LINEAR_PROGRAMMING); } private void runFirstMIPExample(MPSolver.OptimizationProblemType problemType) { if (!MPSolver.supportsProblemType(problemType)) { return; } final MPSolver solver = new MPSolver("Solver", problemType); assertNotNull(solver); // Integer variables shouldn't have infinite bounds, nor really large bounds: // it can make your solver behave erratically. If you have integer variables // with a truly large dynamic range you should consider making it non-integer. final double upperBound = 1000; final MPVariable x1 = solver.makeIntVar(0.0, upperBound, "x1"); final MPVariable x2 = solver.makeIntVar(0.0, upperBound, "x2"); solver.objective().setCoefficient(x1, 1); solver.objective().setCoefficient(x2, 2); final MPConstraint ct = solver.makeConstraint(17, Double.POSITIVE_INFINITY); ct.setCoefficient(x1, 3); ct.setCoefficient(x2, 2); // Check the solution. assertEquals(MPSolver.ResultStatus.OPTIMAL, solver.solve()); final double optObjValue = 6.0; assertEquals(optObjValue, solver.objective().value(), 1e-6); assertEquals(optObjValue, solver.objective().bestBound(), 1e-6); final double optRowActivity = 18.0; assertEquals(optRowActivity, solver.computeConstraintActivities()[ct.index()], NUM_TOLERANCE); // BOP does not support nodes(). if (solver.problemType() != MPSolver.OptimizationProblemType.BOP_INTEGER_PROGRAMMING) { assertThat(solver.nodes()).isAtLeast(0); } } @Test public void testMPSolver_firstMIPExample() { runFirstMIPExample(MPSolver.OptimizationProblemType.BOP_INTEGER_PROGRAMMING); runFirstMIPExample(MPSolver.OptimizationProblemType.CBC_MIXED_INTEGER_PROGRAMMING); runFirstMIPExample(MPSolver.OptimizationProblemType.GLPK_MIXED_INTEGER_PROGRAMMING); runFirstMIPExample(MPSolver.OptimizationProblemType.SCIP_MIXED_INTEGER_PROGRAMMING); runFirstMIPExample(MPSolver.OptimizationProblemType.SAT_INTEGER_PROGRAMMING); runFirstMIPExample(MPSolver.OptimizationProblemType.GUROBI_MIXED_INTEGER_PROGRAMMING); } private void runSuccessiveObjectives(MPSolver.OptimizationProblemType problemType) { if (!MPSolver.supportsProblemType(problemType)) { return; } final MPSolver solver = new MPSolver("Solver", problemType); assertNotNull(solver); final MPVariable x1 = solver.makeNumVar(0, 10, "var1"); final MPVariable x2 = solver.makeNumVar(0, 10, "var2"); final MPConstraint ct = solver.makeConstraint(0, 10); ct.setCoefficient(x1, 1); ct.setCoefficient(x2, 2); final MPObjective objective = solver.objective(); objective.setCoefficient(x1, 1); objective.setCoefficient(x2, 0); objective.setOptimizationDirection(true); // Check the solution. assertEquals(MPSolver.ResultStatus.OPTIMAL, solver.solve()); assertEquals(10.0, x1.solutionValue(), NUM_TOLERANCE); assertEquals(0.0, x2.solutionValue(), NUM_TOLERANCE); objective.setCoefficient(x1, 0); objective.setCoefficient(x2, 1); objective.setOptimizationDirection(true); // Check the solution assertEquals(MPSolver.ResultStatus.OPTIMAL, solver.solve()); assertEquals(0.0, x1.solutionValue(), NUM_TOLERANCE); assertEquals(5.0, x2.solutionValue(), NUM_TOLERANCE); objective.setCoefficient(x1, -1); objective.setCoefficient(x2, 0); objective.setOptimizationDirection(false); // Check the solution. assertEquals(MPSolver.ResultStatus.OPTIMAL, solver.solve()); assertEquals(10.0, x1.solutionValue(), NUM_TOLERANCE); assertEquals(0.0, x2.solutionValue(), NUM_TOLERANCE); } @Test public void testMPSolver_successiveObjectives() { runSuccessiveObjectives(MPSolver.OptimizationProblemType.GLOP_LINEAR_PROGRAMMING); runSuccessiveObjectives(MPSolver.OptimizationProblemType.CLP_LINEAR_PROGRAMMING); runSuccessiveObjectives(MPSolver.OptimizationProblemType.GLPK_LINEAR_PROGRAMMING); runSuccessiveObjectives(MPSolver.OptimizationProblemType.GUROBI_LINEAR_PROGRAMMING); runSuccessiveObjectives(MPSolver.OptimizationProblemType.CBC_MIXED_INTEGER_PROGRAMMING); runSuccessiveObjectives(MPSolver.OptimizationProblemType.GLPK_MIXED_INTEGER_PROGRAMMING); runSuccessiveObjectives(MPSolver.OptimizationProblemType.SCIP_MIXED_INTEGER_PROGRAMMING); runSuccessiveObjectives(MPSolver.OptimizationProblemType.SAT_INTEGER_PROGRAMMING); runSuccessiveObjectives(MPSolver.OptimizationProblemType.GUROBI_MIXED_INTEGER_PROGRAMMING); } private void runObjectiveOffset(MPSolver.OptimizationProblemType problemType) { if (!MPSolver.supportsProblemType(problemType)) { return; } final MPSolver solver = new MPSolver("Solver", problemType); assertNotNull(solver); final MPVariable x1 = solver.makeNumVar(1.0, 10.0, "x1"); final MPVariable x2 = solver.makeNumVar(1.0, 10.0, "x2"); final MPConstraint ct = solver.makeConstraint(0, 4.0); ct.setCoefficient(x1, 1); ct.setCoefficient(x2, 2); final double objectiveOffset = 10.0; // Simple minimization. final MPObjective objective = solver.objective(); objective.setCoefficient(x1, 1.0); objective.setCoefficient(x2, 1.0); objective.setOffset(objectiveOffset); objective.setOptimizationDirection(false); assertEquals(MPSolver.ResultStatus.OPTIMAL, solver.solve()); assertEquals(2.0 + objectiveOffset, objective.value(), 1e-6); // Offset is provided in several separate constants. objective.setCoefficient(x1, 1.0); objective.setCoefficient(x2, 1.0); objective.setOffset(-1.0); objective.setOffset(objectiveOffset + objective.offset()); objective.setOffset(1.0 + objective.offset()); assertEquals(MPSolver.ResultStatus.OPTIMAL, solver.solve()); assertEquals(2.0 + objectiveOffset, objective.value(), 1e-6); // Simple maximization. objective.setCoefficient(x1, 1.0); objective.setCoefficient(x2, 1.0); objective.setOffset(objectiveOffset); objective.setOptimizationDirection(true); assertEquals(MPSolver.ResultStatus.OPTIMAL, solver.solve()); assertEquals(3.0 + objectiveOffset, objective.value(), 1e-6); } @Test public void testMPSolver_objectiveOffset() { runObjectiveOffset(MPSolver.OptimizationProblemType.GLOP_LINEAR_PROGRAMMING); runObjectiveOffset(MPSolver.OptimizationProblemType.CLP_LINEAR_PROGRAMMING); runObjectiveOffset(MPSolver.OptimizationProblemType.GLPK_LINEAR_PROGRAMMING); runObjectiveOffset(MPSolver.OptimizationProblemType.GUROBI_LINEAR_PROGRAMMING); runObjectiveOffset(MPSolver.OptimizationProblemType.CBC_MIXED_INTEGER_PROGRAMMING); runObjectiveOffset(MPSolver.OptimizationProblemType.GLPK_MIXED_INTEGER_PROGRAMMING); runObjectiveOffset(MPSolver.OptimizationProblemType.SCIP_MIXED_INTEGER_PROGRAMMING); runObjectiveOffset(MPSolver.OptimizationProblemType.SAT_INTEGER_PROGRAMMING); runObjectiveOffset(MPSolver.OptimizationProblemType.GUROBI_MIXED_INTEGER_PROGRAMMING); } @Test public void testMPSolver_lazyConstraints() { final MPSolver.OptimizationProblemType problemType = MPSolver.OptimizationProblemType.SCIP_MIXED_INTEGER_PROGRAMMING; if (!MPSolver.supportsProblemType(problemType)) { return; } final MPSolver solver = new MPSolver("testLazyConstraints", problemType); assertNotNull(solver); final double infinity = MPSolver.infinity(); final MPVariable x = solver.makeIntVar(0, infinity, "x"); final MPVariable y = solver.makeIntVar(0, infinity, "y"); final MPConstraint ct1 = solver.makeConstraint(0, 10.0); ct1.setCoefficient(x, 2.0); ct1.setCoefficient(y, 1.0); final MPConstraint ct2 = solver.makeConstraint(0, 10.0); ct2.setCoefficient(x, 1.0); ct2.setCoefficient(y, 2.0); ct2.setIsLazy(true); assertFalse(ct1.isLazy()); assertTrue(ct2.isLazy()); final MPObjective objective = solver.objective(); objective.setCoefficient(x, 1.0); objective.setCoefficient(y, 1.0); objective.setOptimizationDirection(true); assertEquals(MPSolver.ResultStatus.OPTIMAL, solver.solve()); assertEquals(solver.objective().value(), 6.0, NUM_TOLERANCE); } @Test public void testMPSolver_sameConstraintName() { MPSolver solver = MPSolver.createSolver("GLOP"); assertNotNull(solver); boolean success = true; solver.makeConstraint("my_const_name"); try { solver.makeConstraint("my_const_name"); } catch (Throwable e) { System.out.println(e); success = false; } assertTrue(success); } @Test public void testMPSolver_exportModelToProto() { final MPSolver.OptimizationProblemType problemType = MPSolver.OptimizationProblemType.GLOP_LINEAR_PROGRAMMING; if (!MPSolver.supportsProblemType(problemType)) { return; } final MPSolver solver = new MPSolver("testExportModelToProto", problemType); assertNotNull(solver); solver.makeNumVar(0.0, 10.0, "x1"); solver.makeConstraint(0.0, 0.0); solver.objective().setOptimizationDirection(true); final MPModelProto model = solver.exportModelToProto(); assertEquals(1, model.getVariableCount()); assertEquals(1, model.getConstraintCount()); assertTrue(model.getMaximize()); } @Test public void testMPsolver_createSolutionResponseProto() { final MPSolver.OptimizationProblemType problemType = MPSolver.OptimizationProblemType.GLOP_LINEAR_PROGRAMMING; if (!MPSolver.supportsProblemType(problemType)) { return; } final MPSolver solver = new MPSolver("testCreateSolutionResponseProto", problemType); assertNotNull(solver); final MPVariable x1 = solver.makeNumVar(0.0, 10.0, "x1"); solver.objective().setCoefficient(x1, 1.0); solver.objective().setOptimizationDirection(true); solver.solve(); final MPSolutionResponse response = solver.createSolutionResponseProto(); assertEquals(MPSolverResponseStatus.MPSOLVER_OPTIMAL, response.getStatus()); assertEquals(10.0, response.getObjectiveValue(), 1e-6); } @Test public void testMPSolver_solveWithProto() { final MPSolver.OptimizationProblemType problemType = MPSolver.OptimizationProblemType.GLOP_LINEAR_PROGRAMMING; if (!MPSolver.supportsProblemType(problemType)) { return; } final MPModelProto.Builder modelBuilder = MPModelProto.newBuilder().setMaximize(true); final MPVariableProto variable = MPVariableProto.newBuilder() .setLowerBound(0.0) .setUpperBound(10.0) .setName("x1") .setIsInteger(false) .setObjectiveCoefficient(1.0) .build(); modelBuilder.addVariable(variable); final MPModelRequest request = MPModelRequest.newBuilder() .setModel(modelBuilder.build()) .setSolverType(MPModelRequest.SolverType.GLOP_LINEAR_PROGRAMMING) .build(); final MPSolutionResponse response = MPSolver.solveWithProto(request); assertEquals(MPSolverResponseStatus.MPSOLVER_OPTIMAL, response.getStatus()); assertEquals(10.0, response.getObjectiveValue(), 1e-6); } @Test public void testModelExport() { final MPSolver.OptimizationProblemType problemType = MPSolver.OptimizationProblemType.GLOP_LINEAR_PROGRAMMING; if (!MPSolver.supportsProblemType(problemType)) { return; } final MPSolver solver = new MPSolver("tesModelExport", problemType); assertNotNull(solver); final double infinity = MPSolver.infinity(); // x1, x2 and x3 are continuous non-negative variables. final MPVariable x1 = solver.makeNumVar(0.0, infinity, "x1"); // Maximize 10 * x1. solver.objective().setCoefficient(x1, 10); solver.objective().setMinimization(); // 5 * x1 <= 30. final MPConstraint c0 = solver.makeConstraint(-infinity, 100.0); c0.setCoefficient(x1, 5); final MPModelExportOptions obfuscate = new MPModelExportOptions(); obfuscate.setObfuscate(true); String out = solver.exportModelAsLpFormat(); assertThat(out).isNotEmpty(); out = solver.exportModelAsLpFormat(obfuscate); assertThat(out).isNotEmpty(); out = solver.exportModelAsMpsFormat(); assertThat(out).isNotEmpty(); out = solver.exportModelAsMpsFormat(obfuscate); assertThat(out).isNotEmpty(); } @Test public void testMPSolver_wrongModelExport() { final MPSolver.OptimizationProblemType problemType = MPSolver.OptimizationProblemType.GLOP_LINEAR_PROGRAMMING; if (!MPSolver.supportsProblemType(problemType)) { return; } final MPSolver solver = new MPSolver("testWrongModelExport", problemType); assertNotNull(solver); // Test that forbidden names are renamed. solver.makeBoolVar("<-%$#!&~-+ ⌂"); // Some illegal name. String out = solver.exportModelAsLpFormat(); assertThat(out).isNotEmpty(); out = solver.exportModelAsMpsFormat(); assertThat(out).isNotEmpty(); } @Test public void testMPSolver_setHint() { final MPSolver.OptimizationProblemType problemType = MPSolver.OptimizationProblemType.GLOP_LINEAR_PROGRAMMING; if (!MPSolver.supportsProblemType(problemType)) { return; } final MPSolver solver = new MPSolver("testSetHint", problemType); assertNotNull(solver); final MPVariable[] variables = { solver.makeNumVar(0.0, 10.0, "x1"), solver.makeNumVar(0.0, 10.0, "x2")}; final double[] values = {5.0, 6.0}; solver.setHint(variables, values); final MPModelProto model = solver.exportModelToProto(); final PartialVariableAssignment hint = model.getSolutionHint(); assertEquals(2, hint.getVarIndexCount()); assertEquals(2, hint.getVarValueCount()); assertEquals(0, hint.getVarIndex(0)); assertEquals(5.0, hint.getVarValue(0), 1e-6); assertEquals(1, hint.getVarIndex(1)); assertEquals(6.0, hint.getVarValue(1), 1e-6); } @Test public void testMPSolver_issue132() { final MPSolver.OptimizationProblemType problemType = MPSolver.OptimizationProblemType.CLP_LINEAR_PROGRAMMING; if (!MPSolver.supportsProblemType(problemType)) { return; } final MPSolver solver = new MPSolver("CoinError", problemType); assertNotNull(solver); final double infinity = MPSolver.infinity(); final MPVariable x0 = solver.makeNumVar(0.0, 1.0, "x0"); final MPVariable x1 = solver.makeNumVar(0.0, 0.3, "x1"); final MPVariable x2 = solver.makeNumVar(0.0, 0.3, "x2"); final MPVariable x3 = solver.makeNumVar(-infinity, infinity, "x3"); final MPObjective obj = solver.objective(); obj.setCoefficient(x1, 2.655523); obj.setCoefficient(x2, -2.70917); obj.setCoefficient(x3, 1); obj.setMaximization(); final MPConstraint c0 = solver.makeConstraint(-infinity, 0.302499); c0.setCoefficient(x3, 1); c0.setCoefficient(x0, -3.484345); final MPConstraint c1 = solver.makeConstraint(-infinity, 0.507194); c1.setCoefficient(x3, 1); c1.setCoefficient(x0, -3.074807); final MPConstraint c2 = solver.makeConstraint(0.594, 0.594); c2.setCoefficient(x0, 1); c2.setCoefficient(x1, 1.01); c2.setCoefficient(x2, -0.99); System.out.println("Number of variables = " + solver.numVariables()); System.out.println("Number of constraints = " + solver.numConstraints()); solver.enableOutput(); System.out.println(solver.exportModelAsLpFormat()); System.out.println(solver.solve()); } @Test public void testMPSolver_setHintAndSolverGetters() { final MPSolver.OptimizationProblemType problemType = MPSolver.OptimizationProblemType.GLOP_LINEAR_PROGRAMMING; if (!MPSolver.supportsProblemType(problemType)) { return; } final MPSolver solver = new MPSolver("glop", problemType); assertNotNull(solver); // x and y are continuous non-negative variables. final MPVariable x = solver.makeIntVar(0.0, Double.POSITIVE_INFINITY, "x"); final MPVariable y = solver.makeIntVar(0.0, Double.POSITIVE_INFINITY, "y"); // Objectif function: Maximize x + 10 * y. final MPObjective objective = solver.objective(); objective.setCoefficient(x, 1); objective.setCoefficient(y, 10); objective.setMaximization(); // x + 7 * y <= 17.5. final MPConstraint c0 = solver.makeConstraint(-Double.POSITIVE_INFINITY, 17.5, "c0"); c0.setCoefficient(x, 1); c0.setCoefficient(y, 7); // x <= 3.5. final MPConstraint c1 = solver.makeConstraint(-Double.POSITIVE_INFINITY, 3.5, "c1"); c1.setCoefficient(x, 1); c1.setCoefficient(y, 0); // Test solver getters. final MPVariable[] variables = solver.variables(); assertThat(variables).hasLength(2); final MPConstraint[] constraints = solver.constraints(); assertThat(constraints).hasLength(2); // Test API compiles. solver.setHint(variables, new double[] {2.0, 3.0}); assertEquals("y", variables[1].name()); assertEquals("c0", constraints[0].name()); // TODO(user): Add API to query the hint. assertFalse(solver.setNumThreads(4)); } }
26,903
40.074809
98
java
or-tools
or-tools-master/examples/tests/ModelBuilderTest.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.modelbuilder; import static com.google.common.truth.Truth.assertThat; import com.google.ortools.Loader; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public final class ModelBuilderTest { @BeforeEach public void setUp() { Loader.loadNativeLibraries(); } @Test public void runMinimalLinearExample_ok() { ModelBuilder model = new ModelBuilder(); model.setName("minimal_linear_example"); double infinity = java.lang.Double.POSITIVE_INFINITY; Variable x1 = model.newNumVar(0.0, infinity, "x1"); Variable x2 = model.newNumVar(0.0, infinity, "x2"); Variable x3 = model.newNumVar(0.0, infinity, "x3"); assertThat(model.numVariables()).isEqualTo(3); assertThat(x1.getIntegrality()).isFalse(); assertThat(x1.getLowerBound()).isEqualTo(0.0); assertThat(x2.getUpperBound()).isEqualTo(infinity); x1.setLowerBound(1.0); assertThat(x1.getLowerBound()).isEqualTo(1.0); LinearConstraint c0 = model.addLessOrEqual(LinearExpr.sum(new Variable[] {x1, x2, x3}), 100.0); assertThat(c0.getUpperBound()).isEqualTo(100.0); LinearConstraint c1 = model .addLessOrEqual( LinearExpr.newBuilder().addTerm(x1, 10.0).addTerm(x2, 4.0).addTerm(x3, 5.0), 600.0) .withName("c1"); assertThat(c1.getName()).isEqualTo("c1"); LinearConstraint c2 = model.addLessOrEqual( LinearExpr.newBuilder().addTerm(x1, 2.0).addTerm(x2, 2.0).addTerm(x3, 6.0), 300.0); assertThat(c2.getUpperBound()).isEqualTo(300.0); model.maximize( LinearExpr.weightedSum(new Variable[] {x1, x2, x3}, new double[] {10.0, 6, 4.0})); assertThat(x3.getObjectiveCoefficient()).isEqualTo(4.0); assertThat(model.getObjectiveOffset()).isEqualTo(0.0); model.setObjectiveOffset(-5.5); assertThat(model.getObjectiveOffset()).isEqualTo(-5.5); ModelSolver solver = new ModelSolver("glop"); assertThat(solver.solverIsSupported()).isTrue(); assertThat(solver.solve(model)).isEqualTo(SolveStatus.OPTIMAL); assertThat(solver.getObjectiveValue()) .isWithin(1e-5) .of(733.333333 + model.getObjectiveOffset()); assertThat(solver.getValue(x1)).isWithin(1e-5).of(33.333333); assertThat(solver.getValue(x2)).isWithin(1e-5).of(66.6666673); assertThat(solver.getValue(x3)).isWithin(1e-5).of(0.0); double dualObjectiveValue = solver.getDualValue(c0) * c0.getUpperBound() + solver.getDualValue(c1) * c1.getUpperBound() + solver.getDualValue(c2) * c2.getUpperBound() + model.getObjectiveOffset(); assertThat(solver.getObjectiveValue()).isWithin(1e-5).of(dualObjectiveValue); assertThat(solver.getReducedCost(x1)).isWithin(1e-5).of(0.0); assertThat(solver.getReducedCost(x2)).isWithin(1e-5).of(0.0); assertThat(solver.getReducedCost(x3)) .isWithin(1e-5) .of(4.0 - 1.0 * solver.getDualValue(c0) - 5.0 * solver.getDualValue(c1)); assertThat(model.exportToLpString(false)).contains("minimal_linear_example"); assertThat(model.exportToMpsString(false)).contains("minimal_linear_example"); } }
3,727
40.88764
99
java
or-tools
or-tools-master/examples/tests/RoutingSolverTest.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.constraintsolver; import static com.google.common.truth.Truth.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.auto.value.AutoValue; import com.google.ortools.Loader; import com.google.ortools.constraintsolver.RoutingModelParameters; import com.google.ortools.constraintsolver.RoutingSearchParameters; import com.google.protobuf.Duration; import java.util.ArrayList; import java.util.function.LongBinaryOperator; import java.util.function.LongUnaryOperator; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** Tests the Routing java interface. */ public final class RoutingSolverTest { @AutoValue abstract static class Location { static Location create(Integer latitude, Integer longitude) { return new AutoValue_RoutingSolverTest_Location(latitude, longitude); } abstract Integer latitude(); abstract Integer longitude(); } private ArrayList<Location> coordinates; @BeforeEach public void setUp() { Loader.loadNativeLibraries(); coordinates = new ArrayList<>(); coordinates.add(Location.create(0, 0)); coordinates.add(Location.create(-1, 0)); coordinates.add(Location.create(-1, 2)); coordinates.add(Location.create(2, 1)); coordinates.add(Location.create(1, 0)); } public LongBinaryOperator createManhattanCostCallback(RoutingIndexManager manager) { return (long i, long j) -> { final int firstIndex = manager.indexToNode(i); final int secondIndex = manager.indexToNode(j); final Location firstCoordinate = coordinates.get(firstIndex); final Location secondCoordinate = coordinates.get(secondIndex); return (long) Math.abs(firstCoordinate.latitude() - secondCoordinate.latitude()) + Math.abs(firstCoordinate.longitude() - secondCoordinate.longitude()); }; } public LongUnaryOperator createUnaryCostCallback(RoutingIndexManager manager) { return (long fromIndex) -> { final int fromNode = manager.indexToNode(fromIndex); final Location firstCoordinate = coordinates.get(fromNode); return (long) Math.abs(firstCoordinate.latitude()) + Math.abs(firstCoordinate.longitude()); }; } public LongBinaryOperator createReturnOneCallback() { return (long i, long j) -> 1; } @Test public void testRoutingModel_checkGlobalRefGuard() { for (int i = 0; i < 500; ++i) { final RoutingIndexManager manager = new RoutingIndexManager(coordinates.size(), 1, 0); assertNotNull(manager); final RoutingModel model = new RoutingModel(manager); assertNotNull(model); LongBinaryOperator transit = (long fromIndex, long toIndex) -> { final int fromNode = manager.indexToNode(fromIndex); final int toNode = manager.indexToNode(toIndex); return (long) Math.abs(toNode - fromNode); }; model.registerTransitCallback(transit); System.gc(); // model should keep alive the callback } } @Test public void testRoutingIndexManager() { final RoutingIndexManager manager = new RoutingIndexManager(42, 3, 7); assertNotNull(manager); assertEquals(42, manager.getNumberOfNodes()); assertEquals(3, manager.getNumberOfVehicles()); assertEquals(42 + 3 * 2 - 1, manager.getNumberOfIndices()); for (int i = 0; i < manager.getNumberOfVehicles(); ++i) { assertEquals(7, manager.indexToNode(manager.getStartIndex(i))); assertEquals(7, manager.indexToNode(manager.getEndIndex(i))); } } @Test public void testRoutingIndexManager_multiDepotSame() { final RoutingIndexManager manager = new RoutingIndexManager(42, 3, new int[] {7, 7, 7}, new int[] {7, 7, 7}); assertNotNull(manager); assertEquals(42, manager.getNumberOfNodes()); assertEquals(3, manager.getNumberOfVehicles()); assertEquals(42 + 3 * 2 - 1, manager.getNumberOfIndices()); for (int i = 0; i < manager.getNumberOfVehicles(); ++i) { assertEquals(7, manager.indexToNode(manager.getStartIndex(i))); assertEquals(7, manager.indexToNode(manager.getEndIndex(i))); } } @Test public void testRoutingIndexManager_multiDepotAllDifferent() { final RoutingIndexManager manager = new RoutingIndexManager(42, 3, new int[] {1, 2, 3}, new int[] {4, 5, 6}); assertNotNull(manager); assertEquals(42, manager.getNumberOfNodes()); assertEquals(3, manager.getNumberOfVehicles()); assertEquals(42, manager.getNumberOfIndices()); for (int i = 0; i < manager.getNumberOfVehicles(); ++i) { assertEquals(i + 1, manager.indexToNode(manager.getStartIndex(i))); assertEquals(i + 4, manager.indexToNode(manager.getEndIndex(i))); } } @Test public void testRoutingModel() { final RoutingIndexManager manager = new RoutingIndexManager(42, 3, new int[] {1, 2, 3}, new int[] {4, 5, 6}); assertNotNull(manager); final RoutingModel model = new RoutingModel(manager); assertNotNull(model); for (int i = 0; i < manager.getNumberOfVehicles(); ++i) { assertEquals(i + 1, manager.indexToNode(model.start(i))); assertEquals(i + 4, manager.indexToNode(model.end(i))); } } @Test public void testRoutingModelParameters() { final RoutingModelParameters parameters = main.defaultRoutingModelParameters(); final RoutingIndexManager manager = new RoutingIndexManager(coordinates.size(), 1, 0); final RoutingModel model = new RoutingModel(manager, parameters); assertEquals(1, model.vehicles()); } @Test public void testRoutingModel_solveWithParameters() { final RoutingIndexManager manager = new RoutingIndexManager(coordinates.size(), 1, 0); final RoutingModel model = new RoutingModel(manager); final RoutingSearchParameters parameters = main.defaultRoutingSearchParameters(); final LongBinaryOperator callback = createManhattanCostCallback(manager); final int cost = model.registerTransitCallback(callback); System.gc(); model.setArcCostEvaluatorOfAllVehicles(cost); assertEquals(RoutingModel.ROUTING_NOT_SOLVED, model.status()); Assignment solution = model.solveWithParameters(parameters); assertEquals(10, solution.objectiveValue()); solution = model.solveFromAssignmentWithParameters(solution, parameters); assertEquals(10, solution.objectiveValue()); } @Test public void testRoutingModel_costsAndSolve() { final RoutingIndexManager manager = new RoutingIndexManager(coordinates.size(), 1, 0); final RoutingModel model = new RoutingModel(manager); assertEquals(5, model.nodes()); final LongBinaryOperator callback = createManhattanCostCallback(manager); final int cost = model.registerTransitCallback(callback); System.gc(); model.setArcCostEvaluatorOfAllVehicles(cost); assertEquals(RoutingModel.ROUTING_NOT_SOLVED, model.status()); final Assignment solution = model.solve(null); assertEquals(RoutingModel.ROUTING_SUCCESS, model.status()); assertNotNull(solution); assertEquals(10, solution.objectiveValue()); } @Test public void testRoutingModel_matrixTransitOwnership() { final RoutingIndexManager manager = new RoutingIndexManager(coordinates.size(), 1, 0); final RoutingModel model = new RoutingModel(manager); assertEquals(5, model.nodes()); final long[][] matrix = { {0, 1, 3, 3, 1}, {1, 0, 2, 4, 2}, {3, 2, 0, 4, 4}, {3, 4, 4, 0, 2}, {1, 2, 4, 2, 0}, }; final int cost = model.registerTransitMatrix(matrix); System.gc(); // model should keep alive the callback model.setArcCostEvaluatorOfAllVehicles(cost); assertEquals(RoutingModel.ROUTING_NOT_SOLVED, model.status()); final Assignment solution = model.solve(null); assertEquals(RoutingModel.ROUTING_SUCCESS, model.status()); assertNotNull(solution); assertEquals(10, solution.objectiveValue()); } @Test public void testRoutingModel_transitCallbackOwnership() { final RoutingIndexManager manager = new RoutingIndexManager(coordinates.size(), 1, 0); final RoutingModel model = new RoutingModel(manager); assertEquals(5, model.nodes()); final int cost = model.registerTransitCallback(createManhattanCostCallback(manager)); System.gc(); // model should keep alive the callback model.setArcCostEvaluatorOfAllVehicles(cost); assertEquals(RoutingModel.ROUTING_NOT_SOLVED, model.status()); final Assignment solution = model.solve(null); assertEquals(RoutingModel.ROUTING_SUCCESS, model.status()); assertNotNull(solution); assertEquals(10, solution.objectiveValue()); } @Test public void testRoutingModel_lambdaTransitCallbackOwnership() { final RoutingIndexManager manager = new RoutingIndexManager(coordinates.size(), 1, 0); final RoutingModel model = new RoutingModel(manager); assertEquals(5, model.nodes()); final int cost = model.registerTransitCallback((long fromIndex, long toIndex) -> { final int fromNode = manager.indexToNode(fromIndex); final int toNode = manager.indexToNode(toIndex); return (long) Math.abs(toNode - fromNode); }); System.gc(); // model should keep alive the callback model.setArcCostEvaluatorOfAllVehicles(cost); assertEquals(RoutingModel.ROUTING_NOT_SOLVED, model.status()); final Assignment solution = model.solve(null); assertEquals(RoutingModel.ROUTING_SUCCESS, model.status()); assertNotNull(solution); assertEquals(8, solution.objectiveValue()); } @Test public void testRoutingModel_unaryTransitVectorOwnership() { final RoutingIndexManager manager = new RoutingIndexManager(10, 1, 0); final RoutingModel model = new RoutingModel(manager); assertEquals(10, model.nodes()); final long[] vector = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; final int cost = model.registerUnaryTransitVector(vector); System.gc(); // model should keep alive the callback model.setArcCostEvaluatorOfAllVehicles(cost); assertEquals(RoutingModel.ROUTING_NOT_SOLVED, model.status()); final Assignment solution = model.solve(null); assertEquals(RoutingModel.ROUTING_SUCCESS, model.status()); assertNotNull(solution); assertEquals(45, solution.objectiveValue()); } @Test public void testRoutingModel_unaryTransitCallbackOwnership() { final RoutingIndexManager manager = new RoutingIndexManager(coordinates.size(), 1, 0); final RoutingModel model = new RoutingModel(manager); assertEquals(5, model.nodes()); final int cost = model.registerUnaryTransitCallback(createUnaryCostCallback(manager)); System.gc(); // model should keep alive the callback model.setArcCostEvaluatorOfAllVehicles(cost); assertEquals(RoutingModel.ROUTING_NOT_SOLVED, model.status()); Assignment solution = model.solve(null); assertEquals(RoutingModel.ROUTING_SUCCESS, model.status()); assertNotNull(solution); assertEquals(8, solution.objectiveValue()); } @Test public void testRoutingModel_lambdaUnaryTransitCallbackOwnership() { final RoutingIndexManager manager = new RoutingIndexManager(coordinates.size(), 1, 0); final RoutingModel model = new RoutingModel(manager); assertEquals(5, model.nodes()); final int cost = model.registerUnaryTransitCallback((long fromIndex) -> { final int fromNode = manager.indexToNode(fromIndex); return (long) Math.abs(fromNode); }); System.gc(); // model should keep alive the callback model.setArcCostEvaluatorOfAllVehicles(cost); assertEquals(RoutingModel.ROUTING_NOT_SOLVED, model.status()); Assignment solution = model.solve(null); assertEquals(RoutingModel.ROUTING_SUCCESS, model.status()); assertNotNull(solution); assertEquals(10, solution.objectiveValue()); } @Test public void testRoutingModel_routesToAssignment() { final int vehicles = coordinates.size() - 1; final RoutingIndexManager manager = new RoutingIndexManager(coordinates.size(), vehicles, 0); final RoutingModel model = new RoutingModel(manager); model.closeModel(); long[][] routes = new long[vehicles][]; for (int i = 0; i < vehicles; ++i) { // Each route has a single node routes[i] = new long[1]; routes[i][0] = manager.nodeToIndex(i + 1); } Assignment assignment = new Assignment(model.solver()); model.routesToAssignment(routes, false, true, assignment); for (int i = 0; i < vehicles; ++i) { assertEquals(assignment.value(model.nextVar(model.start(i))), i + 1); assertEquals(assignment.value(model.nextVar(i + 1)), model.end(i)); } } @Test public void testRoutingModel_addDisjunction() { final RoutingIndexManager manager = new RoutingIndexManager(coordinates.size(), 1, 0); final RoutingModel model = new RoutingModel(manager); final LongBinaryOperator callback = createManhattanCostCallback(manager); final int cost = model.registerTransitCallback(callback); model.setArcCostEvaluatorOfAllVehicles(cost); int[] a = new int[2]; a[0] = 2; a[1] = 3; int[] b = new int[1]; b[0] = 1; int[] c = new int[1]; c[0] = 4; model.addDisjunction(manager.nodesToIndices(a)); model.addDisjunction(manager.nodesToIndices(b)); model.addDisjunction(manager.nodesToIndices(c)); Assignment solution = model.solve(null); assertEquals(8, solution.objectiveValue()); } @Test public void testRoutingModel_addConstantDimension() { final RoutingIndexManager manager = new RoutingIndexManager(10, 1, 0); final RoutingModel model = new RoutingModel(manager); assertEquals(10, model.nodes()); final IntBoolPair pair = model.addConstantDimension(1, /*capacity=*/100, /*fix_start_cumul_to_zero=*/true, "Dimension"); assertEquals(1, pair.getFirst()); assertTrue(pair.getSecond()); RoutingDimension dimension = model.getMutableDimension("Dimension"); dimension.setSpanCostCoefficientForAllVehicles(2); RoutingSearchParameters searchParameters = main.defaultRoutingSearchParameters() .toBuilder() .setTimeLimit(Duration.newBuilder().setSeconds(10)) .build(); assertEquals(RoutingModel.ROUTING_NOT_SOLVED, model.status()); final Assignment solution = model.solveWithParameters(searchParameters); assertEquals(RoutingModel.ROUTING_SUCCESS, model.status()); assertNotNull(solution); assertEquals(20, solution.objectiveValue()); } @Test public void testRoutingModel_addVectorDimension() { final RoutingIndexManager manager = new RoutingIndexManager(10, 1, 0); final RoutingModel model = new RoutingModel(manager); assertEquals(10, model.nodes()); final long[] vector = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; final IntBoolPair pair = model.addVectorDimension(vector, /*capacity=*/100, /*fix_start_cumul_to_zero=*/true, "Dimension"); assertEquals(1, pair.getFirst()); assertTrue(pair.getSecond()); System.gc(); // model should keep alive the callback model.setArcCostEvaluatorOfAllVehicles(pair.getFirst()); RoutingSearchParameters searchParameters = main.defaultRoutingSearchParameters() .toBuilder() .setTimeLimit(Duration.newBuilder().setSeconds(10)) .build(); assertEquals(RoutingModel.ROUTING_NOT_SOLVED, model.status()); final Assignment solution = model.solveWithParameters(searchParameters); assertEquals(RoutingModel.ROUTING_SUCCESS, model.status()); assertNotNull(solution); assertEquals(45, solution.objectiveValue()); } @Test public void testRoutingModel_addMatrixDimension() { final RoutingIndexManager manager = new RoutingIndexManager(5, 1, 0); final RoutingModel model = new RoutingModel(manager); assertEquals(5, model.nodes()); final long[][] matrix = { {0, 1, 3, 3, 1}, {1, 0, 2, 4, 2}, {3, 2, 0, 4, 4}, {3, 4, 4, 0, 2}, {1, 2, 4, 2, 0}, }; final IntBoolPair pair = model.addMatrixDimension(matrix, /*capacity=*/100, /*fix_start_cumul_to_zero=*/true, "Dimension"); assertEquals(1, pair.getFirst()); assertTrue(pair.getSecond()); System.gc(); // model should keep alive the callback model.setArcCostEvaluatorOfAllVehicles(pair.getFirst()); final RoutingSearchParameters searchParameters = main.defaultRoutingSearchParameters() .toBuilder() .setTimeLimit(Duration.newBuilder().setSeconds(10)) .build(); assertEquals(RoutingModel.ROUTING_NOT_SOLVED, model.status()); final Assignment solution = model.solveWithParameters(searchParameters); assertEquals(RoutingModel.ROUTING_SUCCESS, model.status()); assertNotNull(solution); assertEquals(10, solution.objectiveValue()); } @Test public void testRoutingModel_addDimension() { final RoutingIndexManager manager = new RoutingIndexManager(coordinates.size(), 1, 0); final RoutingModel model = new RoutingModel(manager); final LongBinaryOperator manhattanCostCallback = createManhattanCostCallback(manager); final int cost = model.registerTransitCallback(manhattanCostCallback); model.setArcCostEvaluatorOfAllVehicles(cost); final LongBinaryOperator transit = (long firstIndex, long secondIndex) -> { int firstNode = manager.indexToNode(firstIndex); int secondNode = manager.indexToNode(secondIndex); if (firstNode >= coordinates.size()) { firstNode = 0; } if (secondNode >= coordinates.size()) { secondNode = 0; } long distanceTime = manhattanCostCallback.applyAsLong(firstIndex, secondIndex) * 10; long visitingTime = 1; return distanceTime + visitingTime; }; assertTrue( model.addDimension(model.registerTransitCallback(transit), 1000, 1000, true, "time")); RoutingDimension dimension = model.getMutableDimension("time"); for (int i = 1; i < coordinates.size(); i++) { int[] a = new int[1]; a[0] = i; model.addDisjunction(manager.nodesToIndices(a), 10); dimension.cumulVar(i).setMin(0); dimension.cumulVar(i).setMax(40); } RoutingSearchParameters searchParameters = main.defaultRoutingSearchParameters() .toBuilder() .setTimeLimit(Duration.newBuilder().setSeconds(10)) .build(); assertEquals(RoutingModel.ROUTING_NOT_SOLVED, model.status()); Assignment solution = model.solveWithParameters(searchParameters); assertEquals(RoutingModel.ROUTING_SUCCESS, model.status()); assertNotNull(solution); solution = model.solve(solution); assertNotNull(solution); assertTrue(solution.objectiveValue() >= 24 && solution.objectiveValue() <= 30); for (long i = 1; i < coordinates.size(); i++) { assertTrue( solution.min(dimension.cumulVar(i)) >= 0 && solution.max(dimension.cumulVar(i)) <= 40); } } @Test public void testRoutingModel_dimensionVehicleSpanCost() { final RoutingIndexManager manager = new RoutingIndexManager(2, 1, 0); final RoutingModel model = new RoutingModel(manager); final LongBinaryOperator callback = createReturnOneCallback(); assertTrue( model.addDimension(model.registerTransitCallback(callback), 1000, 1000, true, "time")); RoutingDimension dimension = model.getMutableDimension("time"); dimension.cumulVar(1).setMin(10); dimension.setSpanCostCoefficientForAllVehicles(2); assertEquals(2, dimension.getSpanCostCoefficientForVehicle(0)); assertEquals(RoutingModel.ROUTING_NOT_SOLVED, model.status()); final Assignment solution = model.solve(null); assertEquals(RoutingModel.ROUTING_SUCCESS, model.status()); assertNotNull(solution); assertEquals(2 * (10 + 1), solution.objectiveValue()); } @Test public void testRoutingModel_dimensionGlobalSpanCost() { final RoutingIndexManager manager = new RoutingIndexManager(3, 2, 0); final RoutingModel model = new RoutingModel(manager); final LongBinaryOperator callback = createReturnOneCallback(); assertTrue( model.addDimension(model.registerTransitCallback(callback), 1000, 1000, false, "time")); RoutingDimension timeDimension = model.getMutableDimension("time"); timeDimension.cumulVar(1).setMin(10); model.vehicleVar(1).setValue(0); timeDimension.cumulVar(2).setMax(2); model.vehicleVar(2).setValue(1); timeDimension.setGlobalSpanCostCoefficient(2); assertEquals(2, timeDimension.getGlobalSpanCostCoefficient()); assertEquals(RoutingModel.ROUTING_NOT_SOLVED, model.status()); final Assignment solution = model.solve(null); assertEquals(RoutingModel.ROUTING_SUCCESS, model.status()); assertNotNull(solution); assertEquals(2 * (11 - 1), solution.objectiveValue()); } @Test public void testRoutingModel_cumulVarSoftUpperBound() { final RoutingIndexManager manager = new RoutingIndexManager(2, 1, 0); final RoutingModel model = new RoutingModel(manager); final LongBinaryOperator callback = createReturnOneCallback(); assertTrue( model.addDimension(model.registerTransitCallback(callback), 1000, 1000, false, "time")); RoutingDimension dimension = model.getMutableDimension("time"); assertEquals(1000, dimension.getCumulVarSoftUpperBound(1)); assertEquals(0, dimension.getCumulVarSoftUpperBoundCoefficient(1)); dimension.setCumulVarSoftUpperBound(1, 5, 1); assertEquals(5, dimension.getCumulVarSoftUpperBound(1)); assertEquals(1, dimension.getCumulVarSoftUpperBoundCoefficient(1)); } @Test public void testRoutingModel_addDimensionWithVehicleCapacity() { final RoutingIndexManager manager = new RoutingIndexManager(1, 3, 0); final RoutingModel model = new RoutingModel(manager); final LongBinaryOperator callback = createReturnOneCallback(); final long[] capacity = {5, 6, 7}; model.addDimensionWithVehicleCapacity( model.registerTransitCallback(callback), 1000, capacity, false, "dim"); RoutingDimension dimension = model.getMutableDimension("dim"); assertEquals(RoutingModel.ROUTING_NOT_SOLVED, model.status()); final Assignment solution = model.solve(null); assertEquals(RoutingModel.ROUTING_SUCCESS, model.status()); assertNotNull(solution); for (int vehicle = 0; vehicle < 3; ++vehicle) { assertEquals(vehicle + 4, solution.max(dimension.cumulVar(model.start(vehicle)))); assertEquals(vehicle + 5, solution.max(dimension.cumulVar(model.end(vehicle)))); } } @Test public void testRoutingModel_addDimensionWithVehicleTransits() { final RoutingIndexManager manager = new RoutingIndexManager(1, 3, 0); final RoutingModel model = new RoutingModel(manager); final LongBinaryOperator[] callbacks = new LongBinaryOperator[3]; int[] transits = new int[3]; for (int i = 0; i < 3; ++i) { final int value = i + 1; callbacks[i] = (long firstIndex, long secondIndex) -> value; transits[i] = model.registerTransitCallback(callbacks[i]); } long capacity = 5; model.addDimensionWithVehicleTransits(transits, 1000, capacity, false, "dim"); RoutingDimension dimension = model.getMutableDimension("dim"); assertEquals(RoutingModel.ROUTING_NOT_SOLVED, model.status()); final Assignment solution = model.solve(null); assertEquals(RoutingModel.ROUTING_SUCCESS, model.status()); assertNotNull(solution); for (int vehicle = 0; vehicle < 3; ++vehicle) { assertEquals( capacity - (vehicle + 1), solution.max(dimension.cumulVar(model.start(vehicle)))); assertEquals(capacity, solution.max(dimension.cumulVar(model.end(vehicle)))); } } @Test public void testRoutingModel_addDimensionWithVehicleTransitAndCapacity() { final RoutingIndexManager manager = new RoutingIndexManager(1, 3, 0); final RoutingModel model = new RoutingModel(manager); final LongBinaryOperator[] callbacks = new LongBinaryOperator[3]; final int[] transits = new int[3]; for (int i = 0; i < 3; ++i) { final int value = i + 1; callbacks[i] = (long firstIndex, long secondIndex) -> value; transits[i] = model.registerTransitCallback(callbacks[i]); } long[] capacity = new long[3]; for (int i = 0; i < 3; ++i) { capacity[i] = i + 5L; } model.addDimensionWithVehicleTransitAndCapacity(transits, 1000, capacity, false, "dim"); final RoutingDimension dimension = model.getMutableDimension("dim"); assertEquals(RoutingModel.ROUTING_NOT_SOLVED, model.status()); final Assignment solution = model.solve(null); assertEquals(RoutingModel.ROUTING_SUCCESS, model.status()); assertNotNull(solution); for (int vehicle = 0; vehicle < 3; ++vehicle) { assertEquals(4, solution.max(dimension.cumulVar(model.start(vehicle)))); assertEquals(vehicle + 5, solution.max(dimension.cumulVar(model.end(vehicle)))); } } @Test public void testRoutingModel_intVarVectorGetter() { final RoutingIndexManager manager = new RoutingIndexManager(coordinates.size(), 1, 0); final RoutingModel model = new RoutingModel(manager); final LongBinaryOperator manhattanCostCallback = createManhattanCostCallback(manager); final int cost = model.registerTransitCallback(manhattanCostCallback); model.setArcCostEvaluatorOfAllVehicles(cost); final LongBinaryOperator transit = (long firstIndex, long secondIndex) -> { int firstNode = manager.indexToNode(firstIndex); int secondNode = manager.indexToNode(secondIndex); if (firstNode >= coordinates.size()) { firstNode = 0; } if (secondNode >= coordinates.size()) { secondNode = 0; } long distanceTime = manhattanCostCallback.applyAsLong(firstIndex, secondIndex) * 10; long visitingTime = 1; return distanceTime + visitingTime; }; assertTrue( model.addDimension(model.registerTransitCallback(transit), 1000, 1000, true, "time")); RoutingDimension timeDimension = model.getMutableDimension("time"); IntVar[] cumuls = timeDimension.cumuls(); assertThat(cumuls).isNotEmpty(); IntVar[] transits = timeDimension.transits(); assertThat(transits).isNotEmpty(); IntVar[] slacks = timeDimension.slacks(); assertThat(slacks).isNotEmpty(); IntVar[] nexts = model.nexts(); assertThat(nexts).isNotEmpty(); IntVar[] vehicleVars = model.vehicleVars(); assertThat(vehicleVars).isNotEmpty(); } }
27,212
40.866154
97
java
or-tools
or-tools-master/examples/tests/SatSolverTest.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools; import com.google.ortools.Loader; import com.google.ortools.sat.CpModel; import com.google.ortools.sat.CpSolver; import com.google.ortools.sat.CpSolverStatus; import com.google.ortools.sat.IntVar; import com.google.ortools.sat.LinearExpr; import com.google.ortools.sat.TableConstraint; import com.google.ortools.util.Domain; import java.util.Random; import java.util.function.Consumer; import java.util.logging.Logger; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** Tests the CP-SAT java interface. */ public class SatSolverTest { private static final Logger logger = Logger.getLogger(SatSolverTest.class.getName()); @BeforeEach public void setUp() { Loader.loadNativeLibraries(); } @Test public void testDomainGetter() { logger.info("testDomainGetter"); CpModel model = new CpModel(); // Create decision variables IntVar x = model.newIntVar(0, 5, "x"); Domain d = x.getDomain(); long[] flat = d.flattenedIntervals(); if (flat.length != 2 || flat[0] != 0 || flat[1] != 5) { throw new RuntimeException("Wrong domain"); } } @Test public void testCrashInPresolve() { logger.info("testCrashInPresolve"); CpModel model = new CpModel(); // Create decision variables IntVar x = model.newIntVar(0, 5, "x"); IntVar y = model.newIntVar(0, 5, "y"); // Create a linear constraint which enforces that only x or y can be greater // than 0. model.addLinearConstraint(LinearExpr.sum(new IntVar[] {x, y}), 0, 1); // Create the objective variable IntVar obj = model.newIntVar(0, 3, "obj"); // Cut the domain of the objective variable model.addGreaterOrEqual(obj, 2); // Set a constraint that makes the problem infeasible model.addMaxEquality(obj, new IntVar[] {x, y}); // Optimize objective model.minimize(obj); // Create a solver and solve the model. CpSolver solver = new CpSolver(); com.google.ortools.sat.CpSolverStatus status = solver.solve(model); if (status != CpSolverStatus.INFEASIBLE) { throw new IllegalStateException("Wrong status in testCrashInPresolve"); } } @Test public void testCrashInSolveWithAllowedAssignment() { logger.info("testCrashInSolveWithAllowedAssignment"); final CpModel model = new CpModel(); final int numEntityOne = 50000; final int numEntityTwo = 100; final IntVar[] entitiesOne = new IntVar[numEntityOne]; for (int i = 0; i < entitiesOne.length; i++) { entitiesOne[i] = model.newIntVar(1, numEntityTwo, "E" + i); } final int[][] allAllowedValues = new int[numEntityTwo][entitiesOne.length]; for (int i = 0; i < numEntityTwo; i++) { for (int j = 0; j < entitiesOne.length; j++) { allAllowedValues[i][j] = i; } } try { TableConstraint table = model.addAllowedAssignments(entitiesOne); final int[] oneTuple = new int[entitiesOne.length]; for (int i = 0; i < numEntityTwo; i++) { for (int j = 0; j < entitiesOne.length; j++) { oneTuple[j] = i; } table.addTuple(oneTuple); } } catch (final Exception e) { e.printStackTrace(); } final Random r = new Random(); for (int i = 0; i < entitiesOne.length; i++) { model.addEquality(entitiesOne[i], r.nextInt((numEntityTwo))); } final CpSolver solver = new CpSolver(); solver.solve(model); } @Test public void testCrashEquality() { logger.info("testCrashInSolveWithAllowedAssignment"); final CpModel model = new CpModel(); final IntVar[] entities = new IntVar[20]; for (int i = 0; i < entities.length; i++) { entities[i] = model.newIntVar(1, 5, "E" + i); } final int[] equalities = new int[] {18, 4, 19, 3, 12}; addEqualities(model, entities, equalities); final int[] allowedAssignments = new int[] {12, 8, 15}; final int[] allowedAssignmentValues = new int[] {1, 3}; addAllowedAssignMents(model, entities, allowedAssignments, allowedAssignmentValues); final int[] forbiddenAssignments1 = new int[] {6, 15, 19}; final int[] forbiddenAssignments1Values = new int[] {3}; final int[] forbiddenAssignments2 = new int[] {10, 19}; final int[] forbiddenAssignments2Values = new int[] {4}; final int[] forbiddenAssignments3 = new int[] {18, 0, 9, 7}; final int[] forbiddenAssignments3Values = new int[] {4}; final int[] forbiddenAssignments4 = new int[] {14, 11}; final int[] forbiddenAssignments4Values = new int[] {1, 2, 3, 4, 5}; final int[] forbiddenAssignments5 = new int[] {5, 16, 1, 3}; final int[] forbiddenAssignments5Values = new int[] {1, 2, 3, 4, 5}; final int[] forbiddenAssignments6 = new int[] {2, 6, 11, 4}; final int[] forbiddenAssignments6Values = new int[] {1, 2, 3, 4, 5}; final int[] forbiddenAssignments7 = new int[] {6, 18, 12, 2, 9, 14}; final int[] forbiddenAssignments7Values = new int[] {1, 2, 3, 4, 5}; addForbiddenAssignments(forbiddenAssignments1Values, forbiddenAssignments1, entities, model); addForbiddenAssignments(forbiddenAssignments2Values, forbiddenAssignments2, entities, model); addForbiddenAssignments(forbiddenAssignments3Values, forbiddenAssignments3, entities, model); addForbiddenAssignments(forbiddenAssignments4Values, forbiddenAssignments4, entities, model); addForbiddenAssignments(forbiddenAssignments5Values, forbiddenAssignments5, entities, model); addForbiddenAssignments(forbiddenAssignments6Values, forbiddenAssignments6, entities, model); addForbiddenAssignments(forbiddenAssignments7Values, forbiddenAssignments7, entities, model); final int[] configuration = new int[] {5, 4, 2, 3, 3, 3, 4, 3, 3, 1, 4, 4, 3, 1, 4, 1, 4, 4, 3, 3}; for (int i = 0; i < configuration.length; i++) { model.addEquality(entities[i], configuration[i]); } final CpSolver solver = new CpSolver(); solver.solve(model); } @Test public void testLogCapture() { logger.info("testLogCapture"); // Creates the model. CpModel model = new CpModel(); // Creates the variables. int numVals = 3; IntVar x = model.newIntVar(0, numVals - 1, "x"); IntVar y = model.newIntVar(0, numVals - 1, "y"); // Creates the constraints. model.addDifferent(x, y); // Creates a solver and solves the model. final CpSolver solver = new CpSolver(); StringBuilder logBuilder = new StringBuilder(); Consumer<String> appendToLog = (String message) -> { logger.info("Current Thread Name:" + Thread.currentThread().getName() + " Id:" + Thread.currentThread().getId() + " msg:" + message); logBuilder.append(message).append('\n'); }; solver.setLogCallback(appendToLog); solver.getParameters().setLogToStdout(false).setLogSearchProgress(true); CpSolverStatus status = solver.solve(model); if (status != CpSolverStatus.OPTIMAL) { throw new IllegalStateException("Wrong status in testCrashInPresolve"); } String log = logBuilder.toString(); if (log.isEmpty()) { throw new IllegalStateException("Log should not be empty"); } } private void addEqualities(final CpModel model, final IntVar[] entities, final int[] equalities) { for (int i = 0; i < (equalities.length - 1); i++) { model.addEquality(entities[equalities[i]], entities[equalities[i + 1]]); } } private void addAllowedAssignMents(final CpModel model, final IntVar[] entities, final int[] allowedAssignments, final int[] allowedAssignmentValues) { final int[][] allAllowedValues = new int[allowedAssignmentValues.length][allowedAssignments.length]; for (int i = 0; i < allowedAssignmentValues.length; i++) { final Integer value = allowedAssignmentValues[i]; for (int j = 0; j < allowedAssignments.length; j++) { allAllowedValues[i][j] = value; } } final IntVar[] specificEntities = new IntVar[allowedAssignments.length]; for (int i = 0; i < allowedAssignments.length; i++) { specificEntities[i] = entities[allowedAssignments[i]]; } try { TableConstraint table = model.addAllowedAssignments(specificEntities); for (int[] tuple : allAllowedValues) { table.addTuple(tuple); } } catch (final Exception e) { e.printStackTrace(); } } private void addForbiddenAssignments(final int[] forbiddenAssignmentsValues, final int[] forbiddenAssignments, final IntVar[] entities, final CpModel model) { final IntVar[] specificEntities = new IntVar[forbiddenAssignments.length]; for (int i = 0; i < forbiddenAssignments.length; i++) { specificEntities[i] = entities[forbiddenAssignments[i]]; } final int[][] notAllowedValues = new int[forbiddenAssignmentsValues.length][forbiddenAssignments.length]; for (int i = 0; i < forbiddenAssignmentsValues.length; i++) { final Integer value = forbiddenAssignmentsValues[i]; for (int j = 0; j < forbiddenAssignments.length; j++) { notAllowedValues[i][j] = value; } } try { TableConstraint table = model.addForbiddenAssignments(specificEntities); for (int[] tuple : notAllowedValues) { table.addTuple(tuple); } } catch (final Exception e) { e.printStackTrace(); } } }
9,947
36.825095
100
java
or-tools
or-tools-master/ortools/algorithms/samples/Knapsack.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START program] package com.google.ortools.algorithms.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.algorithms.KnapsackSolver; import java.util.ArrayList; // [END import] /** * Sample showing how to model using the knapsack solver. */ public class Knapsack { private Knapsack() {} private static void solve() { // [START solver] KnapsackSolver solver = new KnapsackSolver( KnapsackSolver.SolverType.KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER, "test"); // [END solver] // [START data] final long[] values = {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[] capacities = {850}; // [END data] // [START solve] solver.init(values, weights, capacities); final long computedValue = solver.solve(); // [END solve] // [START print_solution] ArrayList<Integer> packedItems = new ArrayList<>(); ArrayList<Long> packedWeights = new ArrayList<>(); int totalWeight = 0; System.out.println("Total value = " + computedValue); for (int i = 0; i < values.length; i++) { if (solver.bestSolutionContains(i)) { packedItems.add(i); packedWeights.add(weights[0][i]); totalWeight = (int) (totalWeight + weights[0][i]); } } System.out.println("Total weight: " + totalWeight); System.out.println("Packed items: " + packedItems); System.out.println("Packed weights: " + packedWeights); // [END print_solution] } public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); Knapsack.solve(); } } // [END program]
2,651
34.36
100
java
or-tools
or-tools-master/ortools/constraint_solver/samples/CpIsFunCp.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START program] // Cryptarithmetic puzzle // // First attempt to solve equation CP + IS + FUN = TRUE // where each letter represents a unique digit. // // This problem has 72 different solutions in base 10. package com.google.ortools.constraintsolver.samples; // [START import] // [END import] import com.google.ortools.Loader; import com.google.ortools.constraintsolver.DecisionBuilder; import com.google.ortools.constraintsolver.IntVar; import com.google.ortools.constraintsolver.Solver; // [END import] /** Cryptarithmetic puzzle. */ public final class CpIsFunCp { public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); // Instantiate the solver. // [START solver] Solver solver = new Solver("CP is fun!"); // [END solver] // [START variables] final int base = 10; // Decision variables. final IntVar c = solver.makeIntVar(1, base - 1, "C"); final IntVar p = solver.makeIntVar(0, base - 1, "P"); final IntVar i = solver.makeIntVar(1, base - 1, "I"); final IntVar s = solver.makeIntVar(0, base - 1, "S"); final IntVar f = solver.makeIntVar(1, base - 1, "F"); final IntVar u = solver.makeIntVar(0, base - 1, "U"); final IntVar n = solver.makeIntVar(0, base - 1, "N"); final IntVar t = solver.makeIntVar(1, base - 1, "T"); final IntVar r = solver.makeIntVar(0, base - 1, "R"); final IntVar e = solver.makeIntVar(0, base - 1, "E"); // Group variables in a vector so that we can use AllDifferent. final IntVar[] letters = new IntVar[] {c, p, i, s, f, u, n, t, r, e}; // Verify that we have enough digits. if (base < letters.length) { throw new Exception("base < letters.Length"); } // [END variables] // Define constraints. // [START constraints] solver.addConstraint(solver.makeAllDifferent(letters)); // CP + IS + FUN = TRUE final IntVar sum1 = solver .makeSum(new IntVar[] {p, s, n, solver.makeProd(solver.makeSum(new IntVar[] {c, i, u}).var(), base).var(), solver.makeProd(f, base * base).var()}) .var(); final IntVar sum2 = solver .makeSum(new IntVar[] {e, solver.makeProd(u, base).var(), solver.makeProd(r, base * base).var(), solver.makeProd(t, base * base * base).var()}) .var(); solver.addConstraint(solver.makeEquality(sum1, sum2)); // [END constraints] // [START solve] int countSolution = 0; // Create the decision builder to search for solutions. final DecisionBuilder db = solver.makePhase(letters, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); solver.newSearch(db); while (solver.nextSolution()) { System.out.println("C=" + c.value() + " P=" + p.value()); System.out.println(" I=" + i.value() + " S=" + s.value()); System.out.println(" F=" + f.value() + " U=" + u.value()); System.out.println(" N=" + n.value() + " T=" + t.value()); System.out.println(" R=" + r.value() + " E=" + e.value()); // Is CP + IS + FUN = TRUE? if (p.value() + s.value() + n.value() + base * (c.value() + i.value() + u.value()) + base * base * f.value() != e.value() + base * u.value() + base * base * r.value() + base * base * base * t.value()) { throw new Exception("CP + IS + FUN != TRUE"); } countSolution++; } solver.endSearch(); System.out.println("Number of solutions found: " + countSolution); // [END solve] } private CpIsFunCp() {} } // [END program]
4,266
37.098214
90
java
or-tools
or-tools-master/ortools/constraint_solver/samples/NQueensCp.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START program] // OR-Tools solution to the N-queens problem. package com.google.ortools.constraintsolver.samples; // [START import] // [END import] import com.google.ortools.Loader; import com.google.ortools.constraintsolver.DecisionBuilder; import com.google.ortools.constraintsolver.IntVar; import com.google.ortools.constraintsolver.Solver; // [END import] /** N-Queens Problem. */ public final class NQueensCp { public static void main(String[] args) { Loader.loadNativeLibraries(); // Instantiate the solver. // [START solver] Solver solver = new Solver("N-Queens"); // [END solver] // [START variables] int boardSize = 8; IntVar[] queens = new IntVar[boardSize]; for (int i = 0; i < boardSize; ++i) { queens[i] = solver.makeIntVar(0, boardSize - 1, "x" + i); } // [END variables] // Define constraints. // [START constraints] // All rows must be different. solver.addConstraint(solver.makeAllDifferent(queens)); // All columns must be different because the indices of queens are all different. // No two queens can be on the same diagonal. IntVar[] diag1 = new IntVar[boardSize]; IntVar[] diag2 = new IntVar[boardSize]; for (int i = 0; i < boardSize; ++i) { diag1[i] = solver.makeSum(queens[i], i).var(); diag2[i] = solver.makeSum(queens[i], -i).var(); } solver.addConstraint(solver.makeAllDifferent(diag1)); solver.addConstraint(solver.makeAllDifferent(diag2)); // [END constraints] // [START db] // Create the decision builder to search for solutions. final DecisionBuilder db = solver.makePhase(queens, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); // [END db] // [START solve] int solutionCount = 0; solver.newSearch(db); while (solver.nextSolution()) { System.out.println("Solution " + solutionCount); for (int i = 0; i < boardSize; ++i) { for (int j = 0; j < boardSize; ++j) { if (queens[j].value() == i) { System.out.print("Q"); } else { System.out.print("_"); } if (j != boardSize - 1) { System.out.print(" "); } } System.out.println(); } solutionCount++; } solver.endSearch(); // [END solve] // Statistics. // [START statistics] System.out.println("Statistics"); System.out.println(" failures: " + solver.failures()); System.out.println(" branches: " + solver.branches()); System.out.println(" wall time: " + solver.wallTime() + "ms"); System.out.println(" Solutions found: " + solutionCount); // [END statistics] } private NQueensCp() {} } // [END program]
3,326
31.940594
87
java
or-tools
or-tools-master/ortools/constraint_solver/samples/SimpleCpProgram.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START program] package com.google.ortools.constraintsolver.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.constraintsolver.DecisionBuilder; import com.google.ortools.constraintsolver.IntVar; import com.google.ortools.constraintsolver.Solver; import java.util.logging.Logger; // [END import] /** Simple CP Program.*/ public class SimpleCpProgram { private SimpleCpProgram() {} private static final Logger logger = Logger.getLogger(SimpleCpProgram.class.getName()); public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); // Instantiate the solver. // [START solver] Solver solver = new Solver("CpSimple"); // [END solver] // Create the variables. // [START variables] final long numVals = 3; final IntVar x = solver.makeIntVar(0, numVals - 1, "x"); final IntVar y = solver.makeIntVar(0, numVals - 1, "y"); final IntVar z = solver.makeIntVar(0, numVals - 1, "z"); // [END variables] // Constraint 0: x != y.. // [START constraints] solver.addConstraint(solver.makeAllDifferent(new IntVar[] {x, y})); logger.info("Number of constraints: " + solver.constraints()); // [END constraints] // Solve the problem. // [START solve] final DecisionBuilder db = solver.makePhase( new IntVar[] {x, y, z}, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); // [END solve] // Print solution on console. // [START print_solution] int count = 0; solver.newSearch(db); while (solver.nextSolution()) { ++count; logger.info( String.format("Solution: %d\n x=%d y=%d z=%d", count, x.value(), y.value(), z.value())); } solver.endSearch(); logger.info("Number of solutions found: " + solver.solutions()); // [END print_solution] // [START advanced] logger.info(String.format("Advanced usage:\nProblem solved in %d ms\nMemory usage: %d bytes", solver.wallTime(), Solver.memoryUsage())); // [END advanced] } } // [END program]
2,655
33.493506
98
java
or-tools
or-tools-master/ortools/constraint_solver/samples/SimpleRoutingProgram.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START program] package com.google.ortools.constraintsolver.samples; // [START import] import static java.lang.Math.abs; import com.google.ortools.Loader; import com.google.ortools.constraintsolver.Assignment; import com.google.ortools.constraintsolver.FirstSolutionStrategy; import com.google.ortools.constraintsolver.RoutingIndexManager; import com.google.ortools.constraintsolver.RoutingModel; import com.google.ortools.constraintsolver.RoutingSearchParameters; import com.google.ortools.constraintsolver.main; import java.util.logging.Logger; // [END import] /** Minimal Routing example to showcase calling the solver.*/ public class SimpleRoutingProgram { private static final Logger logger = Logger.getLogger(SimpleRoutingProgram.class.getName()); public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); // Instantiate the data problem. // [START data] final int numLocation = 5; final int numVehicles = 1; final int depot = 0; // [END data] // Create Routing Index Manager // [START index_manager] RoutingIndexManager manager = new RoutingIndexManager(numLocation, numVehicles, depot); // [END index_manager] // Create Routing Model. // [START routing_model] RoutingModel routing = new RoutingModel(manager); // [END routing_model] // Create and register a transit callback. // [START transit_callback] final int transitCallbackIndex = routing.registerTransitCallback((long fromIndex, long toIndex) -> { // Convert from routing variable Index to user NodeIndex. int fromNode = manager.indexToNode(fromIndex); int toNode = manager.indexToNode(toIndex); return abs(toNode - fromNode); }); // [END transit_callback] // Define cost of each arc. // [START arc_cost] routing.setArcCostEvaluatorOfAllVehicles(transitCallbackIndex); // [END arc_cost] // Setting first solution heuristic. // [START parameters] RoutingSearchParameters searchParameters = main.defaultRoutingSearchParameters() .toBuilder() .setFirstSolutionStrategy(FirstSolutionStrategy.Value.PATH_CHEAPEST_ARC) .build(); // [END parameters] // Solve the problem. // [START solve] Assignment solution = routing.solveWithParameters(searchParameters); // [END solve] // Print solution on console. // [START print_solution] logger.info("Objective: " + solution.objectiveValue()); // Inspect solution. long index = routing.start(0); logger.info("Route for Vehicle 0:"); long routeDistance = 0; String route = ""; while (!routing.isEnd(index)) { route += manager.indexToNode(index) + " -> "; long previousIndex = index; index = solution.value(routing.nextVar(index)); routeDistance += routing.getArcCostForVehicle(previousIndex, index, 0); } route += manager.indexToNode(index); logger.info(route); logger.info("Distance of the route: " + routeDistance + "m"); // [END print_solution] } } // [END program]
3,710
35.029126
94
java
or-tools
or-tools-master/ortools/constraint_solver/samples/Tsp.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START program] package com.google.ortools.constraintsolver.samples; // [START import] import static java.lang.Math.abs; import com.google.ortools.Loader; import com.google.ortools.constraintsolver.Assignment; import com.google.ortools.constraintsolver.FirstSolutionStrategy; import com.google.ortools.constraintsolver.RoutingIndexManager; import com.google.ortools.constraintsolver.RoutingModel; import com.google.ortools.constraintsolver.RoutingSearchParameters; import com.google.ortools.constraintsolver.main; import java.util.function.LongBinaryOperator; import java.util.logging.Logger; // [END import] /** Minimal TSP.*/ public class Tsp { private static final Logger logger = Logger.getLogger(Tsp.class.getName()); // [START data_model] static class DataModel { public final int[][] locations = { {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}, }; public final int vehicleNumber = 1; public final int depot = 0; public DataModel() { // Convert locations in meters using a city block dimension of 114m x 80m. for (int[] element : locations) { element[0] *= 114; element[1] *= 80; } } } // [END data_model] // [START manhattan_distance] /// @brief Manhattan distance implemented as a callback. /// @details It uses an array of positions and computes /// the Manhattan distance between the two positions of /// two different indices. static class ManhattanDistance implements LongBinaryOperator { public ManhattanDistance(DataModel data, RoutingIndexManager manager) { // precompute distance between location to have distance callback in O(1) distanceMatrix = new long[data.locations.length][data.locations.length]; indexManager = manager; for (int fromNode = 0; fromNode < data.locations.length; ++fromNode) { for (int toNode = 0; toNode < data.locations.length; ++toNode) { if (fromNode == toNode) { distanceMatrix[fromNode][toNode] = 0; } else { distanceMatrix[fromNode][toNode] = (long) abs(data.locations[toNode][0] - data.locations[fromNode][0]) + (long) abs(data.locations[toNode][1] - data.locations[fromNode][1]); } } } } @Override public long applyAsLong(long fromIndex, long toIndex) { // Convert from routing variable Index to distance matrix NodeIndex. int fromNode = indexManager.indexToNode(fromIndex); int toNode = indexManager.indexToNode(toIndex); return distanceMatrix[fromNode][toNode]; } private final long[][] distanceMatrix; private final RoutingIndexManager indexManager; } // [END manhattan_distance] // [START solution_printer] /// @brief Print the solution. static void printSolution( DataModel data, RoutingModel routing, RoutingIndexManager manager, Assignment solution) { // Solution cost. logger.info("Objective : " + solution.objectiveValue()); // Inspect solution. logger.info("Route for Vehicle 0:"); long routeDistance = 0; String route = ""; long index = routing.start(0); while (!routing.isEnd(index)) { route += manager.indexToNode(index) + " -> "; long previousIndex = index; index = solution.value(routing.nextVar(index)); routeDistance += routing.getArcCostForVehicle(previousIndex, index, 0); } route += manager.indexToNode(routing.end(0)); logger.info(route); logger.info("Distance of the route: " + routeDistance + "m"); } // [END solution_printer] public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); // Instantiate the data problem. // [START data] final DataModel data = new DataModel(); // [END data] // Create Routing Index Manager // [START index_manager] RoutingIndexManager manager = new RoutingIndexManager(data.locations.length, data.vehicleNumber, data.depot); // [END index_manager] // Create Routing Model. // [START routing_model] RoutingModel routing = new RoutingModel(manager); // [END routing_model] // Create and register a transit callback. // [START transit_callback] final int transitCallbackIndex = routing.registerTransitCallback(new ManhattanDistance(data, manager)); // [END transit_callback] // Define cost of each arc. // [START arc_cost] routing.setArcCostEvaluatorOfAllVehicles(transitCallbackIndex); // [END arc_cost] // Setting first solution heuristic. // [START parameters] RoutingSearchParameters searchParameters = main.defaultRoutingSearchParameters() .toBuilder() .setFirstSolutionStrategy(FirstSolutionStrategy.Value.PATH_CHEAPEST_ARC) .build(); // [END parameters] // Solve the problem. // [START solve] Assignment solution = routing.solveWithParameters(searchParameters); // [END solve] // Print solution on console. // [START print_solution] printSolution(data, routing, manager, solution); // [END print_solution] } } // [END program]
5,944
33.166667
95
java
or-tools
or-tools-master/ortools/constraint_solver/samples/TspCircuitBoard.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START program] package com.google.ortools.constraintsolver.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.constraintsolver.Assignment; import com.google.ortools.constraintsolver.FirstSolutionStrategy; import com.google.ortools.constraintsolver.RoutingIndexManager; import com.google.ortools.constraintsolver.RoutingModel; import com.google.ortools.constraintsolver.RoutingSearchParameters; import com.google.ortools.constraintsolver.main; import java.util.logging.Logger; // [END import] /** Minimal TSP. */ public class TspCircuitBoard { private static final Logger logger = Logger.getLogger(TspCircuitBoard.class.getName()); // [START data_model] static class DataModel { public final int[][] locations = {{288, 149}, {288, 129}, {270, 133}, {256, 141}, {256, 157}, {246, 157}, {236, 169}, {228, 169}, {228, 161}, {220, 169}, {212, 169}, {204, 169}, {196, 169}, {188, 169}, {196, 161}, {188, 145}, {172, 145}, {164, 145}, {156, 145}, {148, 145}, {140, 145}, {148, 169}, {164, 169}, {172, 169}, {156, 169}, {140, 169}, {132, 169}, {124, 169}, {116, 161}, {104, 153}, {104, 161}, {104, 169}, {90, 165}, {80, 157}, {64, 157}, {64, 165}, {56, 169}, {56, 161}, {56, 153}, {56, 145}, {56, 137}, {56, 129}, {56, 121}, {40, 121}, {40, 129}, {40, 137}, {40, 145}, {40, 153}, {40, 161}, {40, 169}, {32, 169}, {32, 161}, {32, 153}, {32, 145}, {32, 137}, {32, 129}, {32, 121}, {32, 113}, {40, 113}, {56, 113}, {56, 105}, {48, 99}, {40, 99}, {32, 97}, {32, 89}, {24, 89}, {16, 97}, {16, 109}, {8, 109}, {8, 97}, {8, 89}, {8, 81}, {8, 73}, {8, 65}, {8, 57}, {16, 57}, {8, 49}, {8, 41}, {24, 45}, {32, 41}, {32, 49}, {32, 57}, {32, 65}, {32, 73}, {32, 81}, {40, 83}, {40, 73}, {40, 63}, {40, 51}, {44, 43}, {44, 35}, {44, 27}, {32, 25}, {24, 25}, {16, 25}, {16, 17}, {24, 17}, {32, 17}, {44, 11}, {56, 9}, {56, 17}, {56, 25}, {56, 33}, {56, 41}, {64, 41}, {72, 41}, {72, 49}, {56, 49}, {48, 51}, {56, 57}, {56, 65}, {48, 63}, {48, 73}, {56, 73}, {56, 81}, {48, 83}, {56, 89}, {56, 97}, {104, 97}, {104, 105}, {104, 113}, {104, 121}, {104, 129}, {104, 137}, {104, 145}, {116, 145}, {124, 145}, {132, 145}, {132, 137}, {140, 137}, {148, 137}, {156, 137}, {164, 137}, {172, 125}, {172, 117}, {172, 109}, {172, 101}, {172, 93}, {172, 85}, {180, 85}, {180, 77}, {180, 69}, {180, 61}, {180, 53}, {172, 53}, {172, 61}, {172, 69}, {172, 77}, {164, 81}, {148, 85}, {124, 85}, {124, 93}, {124, 109}, {124, 125}, {124, 117}, {124, 101}, {104, 89}, {104, 81}, {104, 73}, {104, 65}, {104, 49}, {104, 41}, {104, 33}, {104, 25}, {104, 17}, {92, 9}, {80, 9}, {72, 9}, {64, 21}, {72, 25}, {80, 25}, {80, 25}, {80, 41}, {88, 49}, {104, 57}, {124, 69}, {124, 77}, {132, 81}, {140, 65}, {132, 61}, {124, 61}, {124, 53}, {124, 45}, {124, 37}, {124, 29}, {132, 21}, {124, 21}, {120, 9}, {128, 9}, {136, 9}, {148, 9}, {162, 9}, {156, 25}, {172, 21}, {180, 21}, {180, 29}, {172, 29}, {172, 37}, {172, 45}, {180, 45}, {180, 37}, {188, 41}, {196, 49}, {204, 57}, {212, 65}, {220, 73}, {228, 69}, {228, 77}, {236, 77}, {236, 69}, {236, 61}, {228, 61}, {228, 53}, {236, 53}, {236, 45}, {228, 45}, {228, 37}, {236, 37}, {236, 29}, {228, 29}, {228, 21}, {236, 21}, {252, 21}, {260, 29}, {260, 37}, {260, 45}, {260, 53}, {260, 61}, {260, 69}, {260, 77}, {276, 77}, {276, 69}, {276, 61}, {276, 53}, {284, 53}, {284, 61}, {284, 69}, {284, 77}, {284, 85}, {284, 93}, {284, 101}, {288, 109}, {280, 109}, {276, 101}, {276, 93}, {276, 85}, {268, 97}, {260, 109}, {252, 101}, {260, 93}, {260, 85}, {236, 85}, {228, 85}, {228, 93}, {236, 93}, {236, 101}, {228, 101}, {228, 109}, {228, 117}, {228, 125}, {220, 125}, {212, 117}, {204, 109}, {196, 101}, {188, 93}, {180, 93}, {180, 101}, {180, 109}, {180, 117}, {180, 125}, {196, 145}, {204, 145}, {212, 145}, {220, 145}, {228, 145}, {236, 145}, {246, 141}, {252, 125}, {260, 129}, {280, 133}}; public final int vehicleNumber = 1; public final int depot = 0; } // [END data_model] // [START euclidean_distance] /// @brief Compute Euclidean distance matrix from locations array. /// @details It uses an array of locations and computes /// the Euclidean distance between any two locations. private static long[][] computeEuclideanDistanceMatrix(int[][] locations) { // Calculate distance matrix using Euclidean distance. long[][] distanceMatrix = new long[locations.length][locations.length]; for (int fromNode = 0; fromNode < locations.length; ++fromNode) { for (int toNode = 0; toNode < locations.length; ++toNode) { if (fromNode == toNode) { distanceMatrix[fromNode][toNode] = 0; } else { distanceMatrix[fromNode][toNode] = (long) Math.hypot(locations[toNode][0] - locations[fromNode][0], locations[toNode][1] - locations[fromNode][1]); } } } return distanceMatrix; } // [END euclidean_distance] // [START solution_printer] /// @brief Print the solution. static void printSolution( RoutingModel routing, RoutingIndexManager manager, Assignment solution) { // Solution cost. logger.info("Objective: " + solution.objectiveValue()); // Inspect solution. logger.info("Route:"); long routeDistance = 0; String route = ""; long index = routing.start(0); while (!routing.isEnd(index)) { route += manager.indexToNode(index) + " -> "; long previousIndex = index; index = solution.value(routing.nextVar(index)); routing.getArcCostForVehicle(previousIndex, index, 0); } route += manager.indexToNode(routing.end(0)); logger.info(route); logger.info("Route distance: " + routeDistance); } // [END solution_printer] public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); // Instantiate the data problem. // [START data] final DataModel data = new DataModel(); // [END data] // Create Routing Index Manager // [START index_manager] RoutingIndexManager manager = new RoutingIndexManager(data.locations.length, data.vehicleNumber, data.depot); // [END index_manager] // Create Routing Model. // [START routing_model] RoutingModel routing = new RoutingModel(manager); // [END routing_model] // Create and register a transit callback. // [START transit_callback] final long[][] distanceMatrix = computeEuclideanDistanceMatrix(data.locations); final int transitCallbackIndex = routing.registerTransitCallback((long fromIndex, long toIndex) -> { // Convert from routing variable Index to user NodeIndex. int fromNode = manager.indexToNode(fromIndex); int toNode = manager.indexToNode(toIndex); return distanceMatrix[fromNode][toNode]; }); // [END transit_callback] // Define cost of each arc. // [START arc_cost] routing.setArcCostEvaluatorOfAllVehicles(transitCallbackIndex); // [END arc_cost] // Setting first solution heuristic. // [START parameters] RoutingSearchParameters searchParameters = main.defaultRoutingSearchParameters() .toBuilder() .setFirstSolutionStrategy(FirstSolutionStrategy.Value.PATH_CHEAPEST_ARC) .build(); // [END parameters] // Solve the problem. // [START solve] Assignment solution = routing.solveWithParameters(searchParameters); // [END solve] // Print solution on console. // [START print_solution] printSolution(routing, manager, solution); // [END print_solution] } } // [END program]
8,433
46.920455
99
java
or-tools
or-tools-master/ortools/constraint_solver/samples/TspCities.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START program] package com.google.ortools.constraintsolver.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.constraintsolver.Assignment; import com.google.ortools.constraintsolver.FirstSolutionStrategy; import com.google.ortools.constraintsolver.RoutingIndexManager; import com.google.ortools.constraintsolver.RoutingModel; import com.google.ortools.constraintsolver.RoutingSearchParameters; import com.google.ortools.constraintsolver.main; import java.util.logging.Logger; // [END import] /** Minimal TSP using distance matrix. */ public class TspCities { private static final Logger logger = Logger.getLogger(TspCities.class.getName()); // [START data_model] static class DataModel { public final long[][] distanceMatrix = { {0, 2451, 713, 1018, 1631, 1374, 2408, 213, 2571, 875, 1420, 2145, 1972}, {2451, 0, 1745, 1524, 831, 1240, 959, 2596, 403, 1589, 1374, 357, 579}, {713, 1745, 0, 355, 920, 803, 1737, 851, 1858, 262, 940, 1453, 1260}, {1018, 1524, 355, 0, 700, 862, 1395, 1123, 1584, 466, 1056, 1280, 987}, {1631, 831, 920, 700, 0, 663, 1021, 1769, 949, 796, 879, 586, 371}, {1374, 1240, 803, 862, 663, 0, 1681, 1551, 1765, 547, 225, 887, 999}, {2408, 959, 1737, 1395, 1021, 1681, 0, 2493, 678, 1724, 1891, 1114, 701}, {213, 2596, 851, 1123, 1769, 1551, 2493, 0, 2699, 1038, 1605, 2300, 2099}, {2571, 403, 1858, 1584, 949, 1765, 678, 2699, 0, 1744, 1645, 653, 600}, {875, 1589, 262, 466, 796, 547, 1724, 1038, 1744, 0, 679, 1272, 1162}, {1420, 1374, 940, 1056, 879, 225, 1891, 1605, 1645, 679, 0, 1017, 1200}, {2145, 357, 1453, 1280, 586, 887, 1114, 2300, 653, 1272, 1017, 0, 504}, {1972, 579, 1260, 987, 371, 999, 701, 2099, 600, 1162, 1200, 504, 0}, }; public final int vehicleNumber = 1; public final int depot = 0; } // [END data_model] // [START solution_printer] /// @brief Print the solution. static void printSolution( RoutingModel routing, RoutingIndexManager manager, Assignment solution) { // Solution cost. logger.info("Objective: " + solution.objectiveValue() + "miles"); // Inspect solution. logger.info("Route:"); long routeDistance = 0; String route = ""; long index = routing.start(0); while (!routing.isEnd(index)) { route += manager.indexToNode(index) + " -> "; long previousIndex = index; index = solution.value(routing.nextVar(index)); routeDistance += routing.getArcCostForVehicle(previousIndex, index, 0); } route += manager.indexToNode(routing.end(0)); logger.info(route); logger.info("Route distance: " + routeDistance + "miles"); } // [END solution_printer] public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); // Instantiate the data problem. // [START data] final DataModel data = new DataModel(); // [END data] // Create Routing Index Manager // [START index_manager] RoutingIndexManager manager = new RoutingIndexManager(data.distanceMatrix.length, data.vehicleNumber, data.depot); // [END index_manager] // Create Routing Model. // [START routing_model] RoutingModel routing = new RoutingModel(manager); // [END routing_model] // Create and register a transit callback. // [START transit_callback] final int transitCallbackIndex = routing.registerTransitCallback((long fromIndex, long toIndex) -> { // Convert from routing variable Index to user NodeIndex. int fromNode = manager.indexToNode(fromIndex); int toNode = manager.indexToNode(toIndex); return data.distanceMatrix[fromNode][toNode]; }); // [END transit_callback] // Define cost of each arc. // [START arc_cost] routing.setArcCostEvaluatorOfAllVehicles(transitCallbackIndex); // [END arc_cost] // Setting first solution heuristic. // [START parameters] RoutingSearchParameters searchParameters = main.defaultRoutingSearchParameters() .toBuilder() .setFirstSolutionStrategy(FirstSolutionStrategy.Value.PATH_CHEAPEST_ARC) .build(); // [END parameters] // Solve the problem. // [START solve] Assignment solution = routing.solveWithParameters(searchParameters); // [END solve] // Print solution on console. // [START print_solution] printSolution(routing, manager, solution); // [END print_solution] } } // [END program]
5,156
38.068182
92
java
or-tools
or-tools-master/ortools/constraint_solver/samples/TspDistanceMatrix.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START program] package com.google.ortools.constraintsolver.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.constraintsolver.Assignment; import com.google.ortools.constraintsolver.FirstSolutionStrategy; import com.google.ortools.constraintsolver.RoutingIndexManager; import com.google.ortools.constraintsolver.RoutingModel; import com.google.ortools.constraintsolver.RoutingSearchParameters; import com.google.ortools.constraintsolver.main; import java.util.logging.Logger; // [END import] /** Minimal TSP using distance matrix.*/ public class TspDistanceMatrix { private static final Logger logger = Logger.getLogger(TspDistanceMatrix.class.getName()); // [START data_model] static class DataModel { public final long[][] distanceMatrix = { {0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354, 468, 776, 662}, {548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674, 1016, 868, 1210}, {776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164, 1130, 788, 1552, 754}, {696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822, 1164, 560, 1358}, {582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708, 1050, 674, 1244}, {274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628, 514, 1050, 708}, {502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856, 514, 1278, 480}, {194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320, 662, 742, 856}, {308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662, 320, 1084, 514}, {194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388, 274, 810, 468}, {536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764, 730, 388, 1152, 354}, {502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114, 308, 650, 274, 844}, {388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194, 536, 388, 730}, {354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0, 342, 422, 536}, {468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536, 342, 0, 764, 194}, {776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274, 388, 422, 764, 0, 798}, {662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730, 536, 194, 798, 0}, }; public final int vehicleNumber = 1; public final int depot = 0; } // [END data_model] // [START solution_printer] /// @brief Print the solution. static void printSolution( DataModel data, RoutingModel routing, RoutingIndexManager manager, Assignment solution) { // Solution cost. logger.info("Objective : " + solution.objectiveValue()); // Inspect solution. logger.info("Route for Vehicle 0:"); long routeDistance = 0; String route = ""; long index = routing.start(0); while (!routing.isEnd(index)) { route += manager.indexToNode(index) + " -> "; long previousIndex = index; index = solution.value(routing.nextVar(index)); routeDistance += routing.getArcCostForVehicle(previousIndex, index, 0); } route += manager.indexToNode(routing.end(0)); logger.info(route); logger.info("Distance of the route: " + routeDistance + "m"); } // [END solution_printer] public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); // Instantiate the data problem. // [START data] final DataModel data = new DataModel(); // [END data] // Create Routing Index Manager // [START index_manager] RoutingIndexManager manager = new RoutingIndexManager(data.distanceMatrix.length, data.vehicleNumber, data.depot); // [END index_manager] // Create Routing Model. // [START routing_model] RoutingModel routing = new RoutingModel(manager); // [END routing_model] // Create and register a transit callback. // [START transit_callback] final int transitCallbackIndex = routing.registerTransitCallback((long fromIndex, long toIndex) -> { // Convert from routing variable Index to user NodeIndex. int fromNode = manager.indexToNode(fromIndex); int toNode = manager.indexToNode(toIndex); return data.distanceMatrix[fromNode][toNode]; }); // [END transit_callback] // Define cost of each arc. // [START arc_cost] routing.setArcCostEvaluatorOfAllVehicles(transitCallbackIndex); // [END arc_cost] // Setting first solution heuristic. // [START parameters] RoutingSearchParameters searchParameters = main.defaultRoutingSearchParameters() .toBuilder() .setFirstSolutionStrategy(FirstSolutionStrategy.Value.PATH_CHEAPEST_ARC) .build(); // [END parameters] // Solve the problem. // [START solve] Assignment solution = routing.solveWithParameters(searchParameters); // [END solve] // Print solution on console. // [START print_solution] printSolution(data, routing, manager, solution); // [END print_solution] } } // [END program]
5,780
41.822222
97
java
or-tools
or-tools-master/ortools/constraint_solver/samples/Vrp.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START program] package com.google.ortools.constraintsolver.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.constraintsolver.Assignment; import com.google.ortools.constraintsolver.FirstSolutionStrategy; import com.google.ortools.constraintsolver.RoutingIndexManager; import com.google.ortools.constraintsolver.RoutingModel; import com.google.ortools.constraintsolver.RoutingSearchParameters; import com.google.ortools.constraintsolver.main; import java.util.logging.Logger; // [END import] /** Minimal VRP.*/ public class Vrp { private static final Logger logger = Logger.getLogger(Vrp.class.getName()); // [START data_model] static class DataModel { public final long[][] distanceMatrix = { {0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354, 468, 776, 662}, {548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674, 1016, 868, 1210}, {776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164, 1130, 788, 1552, 754}, {696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822, 1164, 560, 1358}, {582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708, 1050, 674, 1244}, {274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628, 514, 1050, 708}, {502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856, 514, 1278, 480}, {194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320, 662, 742, 856}, {308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662, 320, 1084, 514}, {194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388, 274, 810, 468}, {536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764, 730, 388, 1152, 354}, {502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114, 308, 650, 274, 844}, {388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194, 536, 388, 730}, {354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0, 342, 422, 536}, {468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536, 342, 0, 764, 194}, {776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274, 388, 422, 764, 0, 798}, {662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730, 536, 194, 798, 0}, }; public final int vehicleNumber = 4; public final int depot = 0; } // [END data_model] // [START solution_printer] /// @brief Print the solution. static void printSolution( DataModel data, RoutingModel routing, RoutingIndexManager manager, Assignment solution) { // Solution cost. logger.info("Objective : " + solution.objectiveValue()); // Inspect solution. long totalDistance = 0; for (int i = 0; i < data.vehicleNumber; ++i) { logger.info("Route for Vehicle " + i + ":"); long routeDistance = 0; String route = ""; long index = routing.start(i); while (!routing.isEnd(index)) { route += manager.indexToNode(index) + " -> "; long previousIndex = index; index = solution.value(routing.nextVar(index)); routeDistance += routing.getArcCostForVehicle(previousIndex, index, i); } route += manager.indexToNode(routing.end(i)); logger.info(route); logger.info("Distance of the route: " + routeDistance + "m"); totalDistance += routeDistance; } logger.info("Total Distance of all routes: " + totalDistance + "m"); } // [END solution_printer] public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); // Instantiate the data problem. // [START data] final DataModel data = new DataModel(); // [END data] // Create Routing Index Manager // [START index_manager] RoutingIndexManager manager = new RoutingIndexManager(data.distanceMatrix.length, data.vehicleNumber, data.depot); // [END index_manager] // Create Routing Model. // [START routing_model] RoutingModel routing = new RoutingModel(manager); // [END routing_model] // Create and register a transit callback. // [START transit_callback] final int transitCallbackIndex = routing.registerTransitCallback((long fromIndex, long toIndex) -> { // Convert from routing variable Index to user NodeIndex. int fromNode = manager.indexToNode(fromIndex); int toNode = manager.indexToNode(toIndex); return data.distanceMatrix[fromNode][toNode]; }); // [END transit_callback] // Define cost of each arc. // [START arc_cost] routing.setArcCostEvaluatorOfAllVehicles(transitCallbackIndex); // [END arc_cost] // Setting first solution heuristic. // [START parameters] RoutingSearchParameters searchParameters = main.defaultRoutingSearchParameters() .toBuilder() .setFirstSolutionStrategy(FirstSolutionStrategy.Value.PATH_CHEAPEST_ARC) .build(); // [END parameters] // Solve the problem. // [START solve] Assignment solution = routing.solveWithParameters(searchParameters); // [END solve] // Print solution on console. // [START print_solution] printSolution(data, routing, manager, solution); // [END print_solution] } } // [END program]
5,960
41.578571
97
java
or-tools
or-tools-master/ortools/constraint_solver/samples/VrpBreaks.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START program] package com.google.ortools.constraintsolver.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.constraintsolver.Assignment; import com.google.ortools.constraintsolver.AssignmentIntervalContainer; import com.google.ortools.constraintsolver.FirstSolutionStrategy; import com.google.ortools.constraintsolver.IntVar; import com.google.ortools.constraintsolver.IntervalVar; import com.google.ortools.constraintsolver.IntervalVarElement; import com.google.ortools.constraintsolver.RoutingDimension; import com.google.ortools.constraintsolver.RoutingIndexManager; import com.google.ortools.constraintsolver.RoutingModel; import com.google.ortools.constraintsolver.RoutingSearchParameters; import com.google.ortools.constraintsolver.Solver; import com.google.ortools.constraintsolver.main; import java.util.logging.Logger; // [END import] /** Minimal VRP with breaks. */ public final class VrpBreaks { private static final Logger logger = Logger.getLogger(VrpBreaks.class.getName()); // [START data_model] static class DataModel { public final long[][] timeMatrix = { {0, 27, 38, 34, 29, 13, 25, 9, 15, 9, 26, 25, 19, 17, 23, 38, 33}, {27, 0, 34, 15, 9, 25, 36, 17, 34, 37, 54, 29, 24, 33, 50, 43, 60}, {38, 34, 0, 49, 43, 25, 13, 40, 23, 37, 20, 63, 58, 56, 39, 77, 37}, {34, 15, 49, 0, 5, 32, 43, 25, 42, 44, 61, 25, 31, 41, 58, 28, 67}, {29, 9, 43, 5, 0, 26, 38, 19, 36, 38, 55, 20, 25, 35, 52, 33, 62}, {13, 25, 25, 32, 26, 0, 11, 15, 9, 12, 29, 38, 33, 31, 25, 52, 35}, {25, 36, 13, 43, 38, 11, 0, 26, 9, 23, 17, 50, 44, 42, 25, 63, 24}, {9, 17, 40, 25, 19, 15, 26, 0, 17, 19, 36, 23, 17, 16, 33, 37, 42}, {15, 34, 23, 42, 36, 9, 9, 17, 0, 13, 19, 40, 34, 33, 16, 54, 25}, {9, 37, 37, 44, 38, 12, 23, 19, 13, 0, 17, 26, 21, 19, 13, 40, 23}, {26, 54, 20, 61, 55, 29, 17, 36, 19, 17, 0, 43, 38, 36, 19, 57, 17}, {25, 29, 63, 25, 20, 38, 50, 23, 40, 26, 43, 0, 5, 15, 32, 13, 42}, {19, 24, 58, 31, 25, 33, 44, 17, 34, 21, 38, 5, 0, 9, 26, 19, 36}, {17, 33, 56, 41, 35, 31, 42, 16, 33, 19, 36, 15, 9, 0, 17, 21, 26}, {23, 50, 39, 58, 52, 25, 25, 33, 16, 13, 19, 32, 26, 17, 0, 38, 9}, {38, 43, 77, 28, 33, 52, 63, 37, 54, 40, 57, 13, 19, 21, 38, 0, 39}, {33, 60, 37, 67, 62, 35, 24, 42, 25, 23, 17, 42, 36, 26, 9, 39, 0}, }; public final long[] serviceTime = { 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, }; public final int vehicleNumber = 4; public final int depot = 0; } // [END data_model] // [START solution_printer] /// @brief Print the solution. static void printSolution( RoutingModel routing, RoutingIndexManager manager, Assignment solution) { logger.info("Objective: " + solution.objectiveValue()); logger.info("Breaks:"); AssignmentIntervalContainer intervals = solution.intervalVarContainer(); for (int i = 0; i < intervals.size(); ++i) { IntervalVarElement breakInterval = intervals.element(i); if (breakInterval.performedValue() == 1) { logger.info(breakInterval.var().name() + " " + breakInterval); } else { logger.info(breakInterval.var().name() + ": Unperformed"); } } long totalTime = 0; RoutingDimension timeDimension = routing.getMutableDimension("Time"); for (int i = 0; i < manager.getNumberOfVehicles(); ++i) { logger.info("Route for Vehicle " + i + ":"); long index = routing.start(i); String route = ""; while (!routing.isEnd(index)) { IntVar timeVar = timeDimension.cumulVar(index); route += manager.indexToNode(index) + " Time(" + solution.value(timeVar) + ") -> "; index = solution.value(routing.nextVar(index)); } IntVar timeVar = timeDimension.cumulVar(index); route += manager.indexToNode(index) + " Time(" + solution.value(timeVar) + ")"; logger.info(route); logger.info("Time of the route: " + solution.value(timeVar) + "min"); totalTime += solution.value(timeVar); } logger.info("Total time of all roues: " + totalTime + "min"); } // [END solution_printer] public static void main(String[] args) { Loader.loadNativeLibraries(); // Instantiate the data problem. // [START data] final DataModel data = new DataModel(); // [END data] // Create Routing Index Manager // [START index_manager] RoutingIndexManager manager = new RoutingIndexManager(data.timeMatrix.length, data.vehicleNumber, data.depot); // [END index_manager] // Create Routing Model. // [START routing_model] RoutingModel routing = new RoutingModel(manager); // [END routing_model] // Create and register a transit callback. // [START transit_callback] final int transitCallbackIndex = routing.registerTransitCallback((long fromIndex, long toIndex) -> { // Convert from routing variable Index to user NodeIndex. int fromNode = manager.indexToNode(fromIndex); int toNode = manager.indexToNode(toIndex); return data.timeMatrix[fromNode][toNode] + data.serviceTime[fromNode]; }); // [END transit_callback] // Define cost of each arc. // [START arc_cost] routing.setArcCostEvaluatorOfAllVehicles(transitCallbackIndex); // [END arc_cost] // Add Time constraint. // [START time_constraint] routing.addDimension(transitCallbackIndex, 10, 180, true, // start cumul to zero "Time"); RoutingDimension timeDimension = routing.getMutableDimension("Time"); timeDimension.setGlobalSpanCostCoefficient(10); // [END time_constraint] // Add Breaks long[] serviceTimes = new long[(int) routing.size()]; for (int index = 0; index < routing.size(); index++) { int node = manager.indexToNode(index); serviceTimes[index] = data.serviceTime[node]; } Solver solver = routing.solver(); for (int vehicle = 0; vehicle < manager.getNumberOfVehicles(); ++vehicle) { IntervalVar[] breakIntervals = new IntervalVar[1]; IntervalVar breakInterval = solver.makeFixedDurationIntervalVar(50, // start min 60, // start max 10, // duration: 10min false, // optional: no "Break for vehicle " + vehicle); breakIntervals[0] = breakInterval; timeDimension.setBreakIntervalsOfVehicle(breakIntervals, vehicle, serviceTimes); } // Setting first solution heuristic. // [START parameters] RoutingSearchParameters searchParameters = main.defaultRoutingSearchParameters() .toBuilder() .setFirstSolutionStrategy(FirstSolutionStrategy.Value.PATH_CHEAPEST_ARC) .build(); // [END parameters] // Solve the problem. // [START solve] Assignment solution = routing.solveWithParameters(searchParameters); // [END solve] // Print solution on console. // [START print_solution] if (solution != null) { printSolution(routing, manager, solution); } else { logger.info("Solution not found."); } // [END print_solution] } private VrpBreaks() {} } // [END program]
7,973
36.971429
91
java
or-tools
or-tools-master/ortools/constraint_solver/samples/VrpCapacity.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START program] package com.google.ortools.constraintsolver.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.constraintsolver.Assignment; import com.google.ortools.constraintsolver.FirstSolutionStrategy; import com.google.ortools.constraintsolver.LocalSearchMetaheuristic; import com.google.ortools.constraintsolver.RoutingIndexManager; import com.google.ortools.constraintsolver.RoutingModel; import com.google.ortools.constraintsolver.RoutingSearchParameters; import com.google.ortools.constraintsolver.main; import com.google.protobuf.Duration; import java.util.logging.Logger; // [END import] /** Minimal VRP. */ public final class VrpCapacity { private static final Logger logger = Logger.getLogger(VrpCapacity.class.getName()); // [START data_model] static class DataModel { public final long[][] distanceMatrix = { {0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354, 468, 776, 662}, {548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674, 1016, 868, 1210}, {776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164, 1130, 788, 1552, 754}, {696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822, 1164, 560, 1358}, {582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708, 1050, 674, 1244}, {274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628, 514, 1050, 708}, {502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856, 514, 1278, 480}, {194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320, 662, 742, 856}, {308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662, 320, 1084, 514}, {194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388, 274, 810, 468}, {536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764, 730, 388, 1152, 354}, {502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114, 308, 650, 274, 844}, {388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194, 536, 388, 730}, {354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0, 342, 422, 536}, {468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536, 342, 0, 764, 194}, {776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274, 388, 422, 764, 0, 798}, {662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730, 536, 194, 798, 0}, }; // [START demands_capacities] public final long[] demands = {0, 1, 1, 2, 4, 2, 4, 8, 8, 1, 2, 1, 2, 4, 4, 8, 8}; public final long[] vehicleCapacities = {15, 15, 15, 15}; // [END demands_capacities] public final int vehicleNumber = 4; public final int depot = 0; } // [END data_model] // [START solution_printer] /// @brief Print the solution. static void printSolution( DataModel data, RoutingModel routing, RoutingIndexManager manager, Assignment solution) { // Solution cost. logger.info("Objective: " + solution.objectiveValue()); // Inspect solution. long totalDistance = 0; long totalLoad = 0; for (int i = 0; i < data.vehicleNumber; ++i) { long index = routing.start(i); logger.info("Route for Vehicle " + i + ":"); long routeDistance = 0; long routeLoad = 0; String route = ""; while (!routing.isEnd(index)) { long nodeIndex = manager.indexToNode(index); routeLoad += data.demands[(int) nodeIndex]; route += nodeIndex + " Load(" + routeLoad + ") -> "; long previousIndex = index; index = solution.value(routing.nextVar(index)); routeDistance += routing.getArcCostForVehicle(previousIndex, index, i); } route += manager.indexToNode(routing.end(i)); logger.info(route); logger.info("Distance of the route: " + routeDistance + "m"); totalDistance += routeDistance; totalLoad += routeLoad; } logger.info("Total distance of all routes: " + totalDistance + "m"); logger.info("Total load of all routes: " + totalLoad); } // [END solution_printer] public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); // Instantiate the data problem. // [START data] final DataModel data = new DataModel(); // [END data] // Create Routing Index Manager // [START index_manager] RoutingIndexManager manager = new RoutingIndexManager(data.distanceMatrix.length, data.vehicleNumber, data.depot); // [END index_manager] // Create Routing Model. // [START routing_model] RoutingModel routing = new RoutingModel(manager); // [END routing_model] // Create and register a transit callback. // [START transit_callback] final int transitCallbackIndex = routing.registerTransitCallback((long fromIndex, long toIndex) -> { // Convert from routing variable Index to user NodeIndex. int fromNode = manager.indexToNode(fromIndex); int toNode = manager.indexToNode(toIndex); return data.distanceMatrix[fromNode][toNode]; }); // [END transit_callback] // Define cost of each arc. // [START arc_cost] routing.setArcCostEvaluatorOfAllVehicles(transitCallbackIndex); // [END arc_cost] // Add Capacity constraint. // [START capacity_constraint] final int demandCallbackIndex = routing.registerUnaryTransitCallback((long fromIndex) -> { // Convert from routing variable Index to user NodeIndex. int fromNode = manager.indexToNode(fromIndex); return data.demands[fromNode]; }); routing.addDimensionWithVehicleCapacity(demandCallbackIndex, 0, // null capacity slack data.vehicleCapacities, // vehicle maximum capacities true, // start cumul to zero "Capacity"); // [END capacity_constraint] // Setting first solution heuristic. // [START parameters] RoutingSearchParameters searchParameters = main.defaultRoutingSearchParameters() .toBuilder() .setFirstSolutionStrategy(FirstSolutionStrategy.Value.PATH_CHEAPEST_ARC) .setLocalSearchMetaheuristic(LocalSearchMetaheuristic.Value.GUIDED_LOCAL_SEARCH) .setTimeLimit(Duration.newBuilder().setSeconds(1).build()) .build(); // [END parameters] // Solve the problem. // [START solve] Assignment solution = routing.solveWithParameters(searchParameters); // [END solve] // Print solution on console. // [START print_solution] printSolution(data, routing, manager, solution); // [END print_solution] } private VrpCapacity() {} } // [END program]
7,315
42.289941
97
java
or-tools
or-tools-master/ortools/constraint_solver/samples/VrpDropNodes.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START program] package com.google.ortools.constraintsolver.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.constraintsolver.Assignment; import com.google.ortools.constraintsolver.FirstSolutionStrategy; import com.google.ortools.constraintsolver.LocalSearchMetaheuristic; import com.google.ortools.constraintsolver.RoutingIndexManager; import com.google.ortools.constraintsolver.RoutingModel; import com.google.ortools.constraintsolver.RoutingSearchParameters; import com.google.ortools.constraintsolver.main; import com.google.protobuf.Duration; import java.util.logging.Logger; // [END import] /** Minimal VRP.*/ public class VrpDropNodes { private static final Logger logger = Logger.getLogger(VrpDropNodes.class.getName()); // [START data_model] static class DataModel { public final long[][] distanceMatrix = { {0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354, 468, 776, 662}, {548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674, 1016, 868, 1210}, {776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164, 1130, 788, 1552, 754}, {696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822, 1164, 560, 1358}, {582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708, 1050, 674, 1244}, {274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628, 514, 1050, 708}, {502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856, 514, 1278, 480}, {194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320, 662, 742, 856}, {308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662, 320, 1084, 514}, {194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388, 274, 810, 468}, {536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764, 730, 388, 1152, 354}, {502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114, 308, 650, 274, 844}, {388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194, 536, 388, 730}, {354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0, 342, 422, 536}, {468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536, 342, 0, 764, 194}, {776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274, 388, 422, 764, 0, 798}, {662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730, 536, 194, 798, 0}, }; // [START demands_capacities] public final long[] demands = {0, 1, 1, 3, 6, 3, 6, 8, 8, 1, 2, 1, 2, 6, 6, 8, 8}; public final long[] vehicleCapacities = {15, 15, 15, 15}; // [END demands_capacities] public final int vehicleNumber = 4; public final int depot = 0; } // [END data_model] // [START solution_printer] /// @brief Print the solution. static void printSolution( DataModel data, RoutingModel routing, RoutingIndexManager manager, Assignment solution) { // Solution cost. logger.info("Objective: " + solution.objectiveValue()); // Inspect solution. // Display dropped nodes. String droppedNodes = "Dropped nodes:"; for (int node = 0; node < routing.size(); ++node) { if (routing.isStart(node) || routing.isEnd(node)) { continue; } if (solution.value(routing.nextVar(node)) == node) { droppedNodes += " " + manager.indexToNode(node); } } logger.info(droppedNodes); // Display routes long totalDistance = 0; long totalLoad = 0; for (int i = 0; i < data.vehicleNumber; ++i) { long index = routing.start(i); logger.info("Route for Vehicle " + i + ":"); long routeDistance = 0; long routeLoad = 0; String route = ""; while (!routing.isEnd(index)) { long nodeIndex = manager.indexToNode(index); routeLoad += data.demands[(int) nodeIndex]; route += nodeIndex + " Load(" + routeLoad + ") -> "; long previousIndex = index; index = solution.value(routing.nextVar(index)); routeDistance += routing.getArcCostForVehicle(previousIndex, index, i); } route += manager.indexToNode(routing.end(i)); logger.info(route); logger.info("Distance of the route: " + routeDistance + "m"); totalDistance += routeDistance; totalLoad += routeLoad; } logger.info("Total Distance of all routes: " + totalDistance + "m"); logger.info("Total Load of all routes: " + totalLoad); } // [END solution_printer] public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); // Instantiate the data problem. // [START data] final DataModel data = new DataModel(); // [END data] // Create Routing Index Manager // [START index_manager] RoutingIndexManager manager = new RoutingIndexManager(data.distanceMatrix.length, data.vehicleNumber, data.depot); // [END index_manager] // Create Routing Model. // [START routing_model] RoutingModel routing = new RoutingModel(manager); // [END routing_model] // Create and register a transit callback. // [START transit_callback] final int transitCallbackIndex = routing.registerTransitCallback((long fromIndex, long toIndex) -> { // Convert from routing variable Index to user NodeIndex. int fromNode = manager.indexToNode(fromIndex); int toNode = manager.indexToNode(toIndex); return data.distanceMatrix[fromNode][toNode]; }); // [END transit_callback] // Define cost of each arc. // [START arc_cost] routing.setArcCostEvaluatorOfAllVehicles(transitCallbackIndex); // [END arc_cost] // Add Capacity constraint. // [START capacity_constraint] final int demandCallbackIndex = routing.registerUnaryTransitCallback((long fromIndex) -> { // Convert from routing variable Index to user NodeIndex. int fromNode = manager.indexToNode(fromIndex); return data.demands[fromNode]; }); routing.addDimensionWithVehicleCapacity(demandCallbackIndex, 0, // null capacity slack data.vehicleCapacities, // vehicle maximum capacities true, // start cumul to zero "Capacity"); // Allow to drop nodes. long penalty = 1000; for (int i = 1; i < data.distanceMatrix.length; ++i) { routing.addDisjunction(new long[] {manager.nodeToIndex(i)}, penalty); } // [END capacity_constraint] // Setting first solution heuristic. // [START parameters] RoutingSearchParameters searchParameters = main.defaultRoutingSearchParameters() .toBuilder() .setFirstSolutionStrategy(FirstSolutionStrategy.Value.PATH_CHEAPEST_ARC) .setLocalSearchMetaheuristic(LocalSearchMetaheuristic.Value.GUIDED_LOCAL_SEARCH) .setTimeLimit(Duration.newBuilder().setSeconds(1).build()) .build(); // [END parameters] // Solve the problem. // [START solve] Assignment solution = routing.solveWithParameters(searchParameters); // [END solve] // Print solution on console. // [START print_solution] printSolution(data, routing, manager, solution); // [END print_solution] } } // [END program]
7,873
41.793478
97
java
or-tools
or-tools-master/ortools/constraint_solver/samples/VrpGlobalSpan.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START program] package com.google.ortools.constraintsolver.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.constraintsolver.Assignment; import com.google.ortools.constraintsolver.FirstSolutionStrategy; import com.google.ortools.constraintsolver.RoutingDimension; import com.google.ortools.constraintsolver.RoutingIndexManager; import com.google.ortools.constraintsolver.RoutingModel; import com.google.ortools.constraintsolver.RoutingSearchParameters; import com.google.ortools.constraintsolver.main; import java.util.logging.Logger; // [END import] /** Minimal VRP.*/ public class VrpGlobalSpan { private static final Logger logger = Logger.getLogger(VrpGlobalSpan.class.getName()); // [START data_model] static class DataModel { public final long[][] distanceMatrix = { {0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354, 468, 776, 662}, {548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674, 1016, 868, 1210}, {776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164, 1130, 788, 1552, 754}, {696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822, 1164, 560, 1358}, {582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708, 1050, 674, 1244}, {274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628, 514, 1050, 708}, {502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856, 514, 1278, 480}, {194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320, 662, 742, 856}, {308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662, 320, 1084, 514}, {194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388, 274, 810, 468}, {536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764, 730, 388, 1152, 354}, {502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114, 308, 650, 274, 844}, {388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194, 536, 388, 730}, {354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0, 342, 422, 536}, {468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536, 342, 0, 764, 194}, {776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274, 388, 422, 764, 0, 798}, {662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730, 536, 194, 798, 0}, }; public final int vehicleNumber = 4; public final int depot = 0; } // [END data_model] // [START solution_printer] /// @brief Print the solution. static void printSolution( DataModel data, RoutingModel routing, RoutingIndexManager manager, Assignment solution) { // Solution cost. logger.info("Objective : " + solution.objectiveValue()); // Inspect solution. long maxRouteDistance = 0; for (int i = 0; i < data.vehicleNumber; ++i) { long index = routing.start(i); logger.info("Route for Vehicle " + i + ":"); long routeDistance = 0; String route = ""; while (!routing.isEnd(index)) { route += manager.indexToNode(index) + " -> "; long previousIndex = index; index = solution.value(routing.nextVar(index)); routeDistance += routing.getArcCostForVehicle(previousIndex, index, i); } logger.info(route + manager.indexToNode(index)); logger.info("Distance of the route: " + routeDistance + "m"); maxRouteDistance = Math.max(routeDistance, maxRouteDistance); } logger.info("Maximum of the route distances: " + maxRouteDistance + "m"); } // [END solution_printer] public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); // Instantiate the data problem. // [START data] final DataModel data = new DataModel(); // [END data] // Create Routing Index Manager // [START index_manager] RoutingIndexManager manager = new RoutingIndexManager(data.distanceMatrix.length, data.vehicleNumber, data.depot); // [END index_manager] // Create Routing Model. // [START routing_model] RoutingModel routing = new RoutingModel(manager); // [END routing_model] // Create and register a transit callback. // [START transit_callback] final int transitCallbackIndex = routing.registerTransitCallback((long fromIndex, long toIndex) -> { // Convert from routing variable Index to user NodeIndex. int fromNode = manager.indexToNode(fromIndex); int toNode = manager.indexToNode(toIndex); return data.distanceMatrix[fromNode][toNode]; }); // [END transit_callback] // Define cost of each arc. // [START arc_cost] routing.setArcCostEvaluatorOfAllVehicles(transitCallbackIndex); // [END arc_cost] // Add Distance constraint. // [START distance_constraint] routing.addDimension(transitCallbackIndex, 0, 3000, true, // start cumul to zero "Distance"); RoutingDimension distanceDimension = routing.getMutableDimension("Distance"); distanceDimension.setGlobalSpanCostCoefficient(100); // [END distance_constraint] // Setting first solution heuristic. // [START parameters] RoutingSearchParameters searchParameters = main.defaultRoutingSearchParameters() .toBuilder() .setFirstSolutionStrategy(FirstSolutionStrategy.Value.PATH_CHEAPEST_ARC) .build(); // [END parameters] // Solve the problem. // [START solve] Assignment solution = routing.solveWithParameters(searchParameters); // [END solve] // Print solution on console. // [START print_solution] printSolution(data, routing, manager, solution); // [END print_solution] } } // [END program]
6,410
42.026846
97
java
or-tools
or-tools-master/ortools/constraint_solver/samples/VrpInitialRoutes.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START program] package com.google.ortools.constraintsolver.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.constraintsolver.Assignment; import com.google.ortools.constraintsolver.RoutingDimension; import com.google.ortools.constraintsolver.RoutingIndexManager; import com.google.ortools.constraintsolver.RoutingModel; import com.google.ortools.constraintsolver.RoutingSearchParameters; import com.google.ortools.constraintsolver.main; import java.util.logging.Logger; // [END import] /** Minimal VRP. */ public class VrpInitialRoutes { private static final Logger logger = Logger.getLogger(VrpInitialRoutes.class.getName()); // [START data_model] static class DataModel { public final long[][] distanceMatrix = { {0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354, 468, 776, 662}, {548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674, 1016, 868, 1210}, {776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164, 1130, 788, 1552, 754}, {696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822, 1164, 560, 1358}, {582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708, 1050, 674, 1244}, {274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628, 514, 1050, 708}, {502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856, 514, 1278, 480}, {194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320, 662, 742, 856}, {308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662, 320, 1084, 514}, {194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388, 274, 810, 468}, {536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764, 730, 388, 1152, 354}, {502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114, 308, 650, 274, 844}, {388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194, 536, 388, 730}, {354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0, 342, 422, 536}, {468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536, 342, 0, 764, 194}, {776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274, 388, 422, 764, 0, 798}, {662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730, 536, 194, 798, 0}, }; // [START initial_routes] public final long[][] initialRoutes = { {8, 16, 14, 13, 12, 11}, {3, 4, 9, 10}, {15, 1}, {7, 5, 2, 6}, }; // [END initial_routes] public final int vehicleNumber = 4; public final int depot = 0; } // [END data_model] // [START solution_printer] /// @brief Print the solution. static void printSolution( DataModel data, RoutingModel routing, RoutingIndexManager manager, Assignment solution) { // Solution cost. logger.info("Objective : " + solution.objectiveValue()); // Inspect solution. long maxRouteDistance = 0; for (int i = 0; i < data.vehicleNumber; ++i) { long index = routing.start(i); logger.info("Route for Vehicle " + i + ":"); long routeDistance = 0; String route = ""; while (!routing.isEnd(index)) { route += manager.indexToNode(index) + " -> "; long previousIndex = index; index = solution.value(routing.nextVar(index)); routeDistance += routing.getArcCostForVehicle(previousIndex, index, i); } logger.info(route + manager.indexToNode(index)); logger.info("Distance of the route: " + routeDistance + "m"); maxRouteDistance = Math.max(routeDistance, maxRouteDistance); } logger.info("Maximum of the route distances: " + maxRouteDistance + "m"); } // [END solution_printer] public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); // Instantiate the data problem. // [START data] final DataModel data = new DataModel(); // [END data] // Create Routing Index Manager // [START index_manager] RoutingIndexManager manager = new RoutingIndexManager(data.distanceMatrix.length, data.vehicleNumber, data.depot); // [END index_manager] // Create Routing Model. // [START routing_model] RoutingModel routing = new RoutingModel(manager); // [END routing_model] // Create and register a transit callback. // [START transit_callback] final int transitCallbackIndex = routing.registerTransitCallback((long fromIndex, long toIndex) -> { // Convert from routing variable Index to user NodeIndex. int fromNode = manager.indexToNode(fromIndex); int toNode = manager.indexToNode(toIndex); return data.distanceMatrix[fromNode][toNode]; }); // [END transit_callback] // Define cost of each arc. // [START arc_cost] routing.setArcCostEvaluatorOfAllVehicles(transitCallbackIndex); // [END arc_cost] // Add Distance constraint. // [START distance_constraint] routing.addDimension(transitCallbackIndex, 0, 3000, true, // start cumul to zero "Distance"); RoutingDimension distanceDimension = routing.getMutableDimension("Distance"); distanceDimension.setGlobalSpanCostCoefficient(100); // [END distance_constraint] // [START print_initial_solution] Assignment initialSolution = routing.readAssignmentFromRoutes(data.initialRoutes, true); logger.info("Initial solution:"); printSolution(data, routing, manager, initialSolution); // [END print_initial_solution] // Setting first solution heuristic. // [START parameters] RoutingSearchParameters searchParameters = main.defaultRoutingSearchParameters(); // [END parameters] // Solve the problem. // [START solve] Assignment solution = routing.solveWithParameters(searchParameters); // [END solve] // Print solution on console. // [START print_solution] logger.info("Solution after search:"); printSolution(data, routing, manager, solution); // [END print_solution] } } // [END program]
6,725
41.301887
97
java
or-tools
or-tools-master/ortools/constraint_solver/samples/VrpPickupDelivery.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START program] package com.google.ortools.constraintsolver.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.constraintsolver.Assignment; import com.google.ortools.constraintsolver.FirstSolutionStrategy; import com.google.ortools.constraintsolver.RoutingDimension; import com.google.ortools.constraintsolver.RoutingIndexManager; import com.google.ortools.constraintsolver.RoutingModel; import com.google.ortools.constraintsolver.RoutingSearchParameters; import com.google.ortools.constraintsolver.Solver; import com.google.ortools.constraintsolver.main; import java.util.logging.Logger; // [END import] /** Minimal Pickup & Delivery Problem (PDP).*/ public class VrpPickupDelivery { private static final Logger logger = Logger.getLogger(VrpPickupDelivery.class.getName()); // [START data_model] static class DataModel { public final long[][] distanceMatrix = { {0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354, 468, 776, 662}, {548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674, 1016, 868, 1210}, {776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164, 1130, 788, 1552, 754}, {696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822, 1164, 560, 1358}, {582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708, 1050, 674, 1244}, {274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628, 514, 1050, 708}, {502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856, 514, 1278, 480}, {194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320, 662, 742, 856}, {308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662, 320, 1084, 514}, {194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388, 274, 810, 468}, {536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764, 730, 388, 1152, 354}, {502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114, 308, 650, 274, 844}, {388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194, 536, 388, 730}, {354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0, 342, 422, 536}, {468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536, 342, 0, 764, 194}, {776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274, 388, 422, 764, 0, 798}, {662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730, 536, 194, 798, 0}, }; // [START pickups_deliveries] public final int[][] pickupsDeliveries = { {1, 6}, {2, 10}, {4, 3}, {5, 9}, {7, 8}, {15, 11}, {13, 12}, {16, 14}, }; // [END pickups_deliveries] public final int vehicleNumber = 4; public final int depot = 0; } // [END data_model] // [START solution_printer] /// @brief Print the solution. static void printSolution( DataModel data, RoutingModel routing, RoutingIndexManager manager, Assignment solution) { // Solution cost. logger.info("Objective : " + solution.objectiveValue()); // Inspect solution. long totalDistance = 0; for (int i = 0; i < data.vehicleNumber; ++i) { long index = routing.start(i); logger.info("Route for Vehicle " + i + ":"); long routeDistance = 0; String route = ""; while (!routing.isEnd(index)) { route += manager.indexToNode(index) + " -> "; long previousIndex = index; index = solution.value(routing.nextVar(index)); routeDistance += routing.getArcCostForVehicle(previousIndex, index, i); } logger.info(route + manager.indexToNode(index)); logger.info("Distance of the route: " + routeDistance + "m"); totalDistance += routeDistance; } logger.info("Total Distance of all routes: " + totalDistance + "m"); } // [END solution_printer] public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); // Instantiate the data problem. // [START data] final DataModel data = new DataModel(); // [END data] // Create Routing Index Manager // [START index_manager] RoutingIndexManager manager = new RoutingIndexManager(data.distanceMatrix.length, data.vehicleNumber, data.depot); // [END index_manager] // Create Routing Model. // [START routing_model] RoutingModel routing = new RoutingModel(manager); // [END routing_model] // Create and register a transit callback. // [START transit_callback] final int transitCallbackIndex = routing.registerTransitCallback((long fromIndex, long toIndex) -> { // Convert from routing variable Index to user NodeIndex. int fromNode = manager.indexToNode(fromIndex); int toNode = manager.indexToNode(toIndex); return data.distanceMatrix[fromNode][toNode]; }); // [END transit_callback] // Define cost of each arc. // [START arc_cost] routing.setArcCostEvaluatorOfAllVehicles(transitCallbackIndex); // [END arc_cost] // Add Distance constraint. // [START distance_constraint] routing.addDimension(transitCallbackIndex, // transit callback index 0, // no slack 3000, // vehicle maximum travel distance true, // start cumul to zero "Distance"); RoutingDimension distanceDimension = routing.getMutableDimension("Distance"); distanceDimension.setGlobalSpanCostCoefficient(100); // [END distance_constraint] // Define Transportation Requests. // [START pickup_delivery_constraint] Solver solver = routing.solver(); for (int[] request : data.pickupsDeliveries) { long pickupIndex = manager.nodeToIndex(request[0]); long deliveryIndex = manager.nodeToIndex(request[1]); routing.addPickupAndDelivery(pickupIndex, deliveryIndex); solver.addConstraint( solver.makeEquality(routing.vehicleVar(pickupIndex), routing.vehicleVar(deliveryIndex))); solver.addConstraint(solver.makeLessOrEqual( distanceDimension.cumulVar(pickupIndex), distanceDimension.cumulVar(deliveryIndex))); } // [END pickup_delivery_constraint] // Setting first solution heuristic. // [START parameters] RoutingSearchParameters searchParameters = main.defaultRoutingSearchParameters() .toBuilder() .setFirstSolutionStrategy(FirstSolutionStrategy.Value.PARALLEL_CHEAPEST_INSERTION) .build(); // [END parameters] // Solve the problem. // [START solve] Assignment solution = routing.solveWithParameters(searchParameters); // [END solve] // Print solution on console. // [START print_solution] printSolution(data, routing, manager, solution); // [END print_solution] } } // [END program]
7,487
41.067416
99
java
or-tools
or-tools-master/ortools/constraint_solver/samples/VrpPickupDeliveryFifo.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START program] package com.google.ortools.constraintsolver.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.constraintsolver.Assignment; import com.google.ortools.constraintsolver.FirstSolutionStrategy; import com.google.ortools.constraintsolver.RoutingDimension; import com.google.ortools.constraintsolver.RoutingIndexManager; import com.google.ortools.constraintsolver.RoutingModel; import com.google.ortools.constraintsolver.RoutingSearchParameters; import com.google.ortools.constraintsolver.Solver; import com.google.ortools.constraintsolver.main; import java.util.logging.Logger; // [END import] /** Minimal Pickup & Delivery Problem (PDP).*/ public class VrpPickupDeliveryFifo { private static final Logger logger = Logger.getLogger(VrpPickupDeliveryFifo.class.getName()); // [START data_model] static class DataModel { public final long[][] distanceMatrix = { {0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354, 468, 776, 662}, {548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674, 1016, 868, 1210}, {776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164, 1130, 788, 1552, 754}, {696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822, 1164, 560, 1358}, {582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708, 1050, 674, 1244}, {274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628, 514, 1050, 708}, {502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856, 514, 1278, 480}, {194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320, 662, 742, 856}, {308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662, 320, 1084, 514}, {194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388, 274, 810, 468}, {536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764, 730, 388, 1152, 354}, {502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114, 308, 650, 274, 844}, {388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194, 536, 388, 730}, {354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0, 342, 422, 536}, {468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536, 342, 0, 764, 194}, {776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274, 388, 422, 764, 0, 798}, {662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730, 536, 194, 798, 0}, }; // [START pickups_deliveries] public final int[][] pickupsDeliveries = { {1, 6}, {2, 10}, {4, 3}, {5, 9}, {7, 8}, {15, 11}, {13, 12}, {16, 14}, }; // [END pickups_deliveries] public final int vehicleNumber = 4; public final int depot = 0; } // [END data_model] // [START solution_printer] /// @brief Print the solution. static void printSolution( DataModel data, RoutingModel routing, RoutingIndexManager manager, Assignment solution) { // Solution cost. logger.info("Objective : " + solution.objectiveValue()); // Inspect solution. long totalDistance = 0; for (int i = 0; i < data.vehicleNumber; ++i) { long index = routing.start(i); logger.info("Route for Vehicle " + i + ":"); long routeDistance = 0; String route = ""; while (!routing.isEnd(index)) { route += manager.indexToNode(index) + " -> "; long previousIndex = index; index = solution.value(routing.nextVar(index)); routeDistance += routing.getArcCostForVehicle(previousIndex, index, i); } logger.info(route + manager.indexToNode(index)); logger.info("Distance of the route: " + routeDistance + "m"); totalDistance += routeDistance; } logger.info("Total Distance of all routes: " + totalDistance + "m"); } // [END solution_printer] public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); // Instantiate the data problem. // [START data] final DataModel data = new DataModel(); // [END data] // Create Routing Index Manager // [START index_manager] RoutingIndexManager manager = new RoutingIndexManager(data.distanceMatrix.length, data.vehicleNumber, data.depot); // [END index_manager] // Create Routing Model. // [START routing_model] RoutingModel routing = new RoutingModel(manager); // [END routing_model] // Create and register a transit callback. // [START transit_callback] final int transitCallbackIndex = routing.registerTransitCallback((long fromIndex, long toIndex) -> { // Convert from routing variable Index to user NodeIndex. int fromNode = manager.indexToNode(fromIndex); int toNode = manager.indexToNode(toIndex); return data.distanceMatrix[fromNode][toNode]; }); // [END transit_callback] // Define cost of each arc. // [START arc_cost] routing.setArcCostEvaluatorOfAllVehicles(transitCallbackIndex); // [END arc_cost] // Add Distance constraint. // [START distance_constraint] routing.addDimension(transitCallbackIndex, // transit callback index 0, // no slack 3000, // vehicle maximum travel distance true, // start cumul to zero "Distance"); RoutingDimension distanceDimension = routing.getMutableDimension("Distance"); distanceDimension.setGlobalSpanCostCoefficient(100); // [END distance_constraint] // Define Transportation Requests. // [START pickup_delivery_constraint] Solver solver = routing.solver(); for (int[] request : data.pickupsDeliveries) { long pickupIndex = manager.nodeToIndex(request[0]); long deliveryIndex = manager.nodeToIndex(request[1]); routing.addPickupAndDelivery(pickupIndex, deliveryIndex); solver.addConstraint( solver.makeEquality(routing.vehicleVar(pickupIndex), routing.vehicleVar(deliveryIndex))); solver.addConstraint(solver.makeLessOrEqual( distanceDimension.cumulVar(pickupIndex), distanceDimension.cumulVar(deliveryIndex))); } routing.setPickupAndDeliveryPolicyOfAllVehicles(RoutingModel.PICKUP_AND_DELIVERY_FIFO); // [END pickup_delivery_constraint] // Setting first solution heuristic. // [START parameters] RoutingSearchParameters searchParameters = main.defaultRoutingSearchParameters() .toBuilder() .setFirstSolutionStrategy(FirstSolutionStrategy.Value.PARALLEL_CHEAPEST_INSERTION) .build(); // [END parameters] // Solve the problem. // [START solve] Assignment solution = routing.solveWithParameters(searchParameters); // [END solve] // Print solution on console. // [START print_solution] printSolution(data, routing, manager, solution); // [END print_solution] } } // [END program]
7,587
41.391061
99
java
or-tools
or-tools-master/ortools/constraint_solver/samples/VrpPickupDeliveryLifo.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START program] package com.google.ortools.constraintsolver.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.constraintsolver.Assignment; import com.google.ortools.constraintsolver.FirstSolutionStrategy; import com.google.ortools.constraintsolver.RoutingDimension; import com.google.ortools.constraintsolver.RoutingIndexManager; import com.google.ortools.constraintsolver.RoutingModel; import com.google.ortools.constraintsolver.RoutingSearchParameters; import com.google.ortools.constraintsolver.Solver; import com.google.ortools.constraintsolver.main; import java.util.logging.Logger; // [END import] /** Minimal Pickup & Delivery Problem (PDP).*/ public class VrpPickupDeliveryLifo { private static final Logger logger = Logger.getLogger(VrpPickupDeliveryLifo.class.getName()); // [START data_model] static class DataModel { public final long[][] distanceMatrix = { {0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354, 468, 776, 662}, {548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674, 1016, 868, 1210}, {776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164, 1130, 788, 1552, 754}, {696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822, 1164, 560, 1358}, {582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708, 1050, 674, 1244}, {274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628, 514, 1050, 708}, {502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856, 514, 1278, 480}, {194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320, 662, 742, 856}, {308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662, 320, 1084, 514}, {194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388, 274, 810, 468}, {536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764, 730, 388, 1152, 354}, {502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114, 308, 650, 274, 844}, {388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194, 536, 388, 730}, {354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0, 342, 422, 536}, {468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536, 342, 0, 764, 194}, {776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274, 388, 422, 764, 0, 798}, {662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730, 536, 194, 798, 0}, }; // [START pickups_deliveries] public final int[][] pickupsDeliveries = { {1, 6}, {2, 10}, {4, 3}, {5, 9}, {7, 8}, {15, 11}, {13, 12}, {16, 14}, }; // [END pickups_deliveries] public final int vehicleNumber = 4; public final int depot = 0; } // [END data_model] // [START solution_printer] /// @brief Print the solution. static void printSolution( DataModel data, RoutingModel routing, RoutingIndexManager manager, Assignment solution) { // Solution cost. logger.info("Objective : " + solution.objectiveValue()); // Inspect solution. long totalDistance = 0; for (int i = 0; i < data.vehicleNumber; ++i) { long index = routing.start(i); logger.info("Route for Vehicle " + i + ":"); long routeDistance = 0; String route = ""; while (!routing.isEnd(index)) { route += manager.indexToNode(index) + " -> "; long previousIndex = index; index = solution.value(routing.nextVar(index)); routeDistance += routing.getArcCostForVehicle(previousIndex, index, i); } logger.info(route + manager.indexToNode(index)); logger.info("Distance of the route: " + routeDistance + "m"); totalDistance += routeDistance; } logger.info("Total Distance of all routes: " + totalDistance + "m"); } // [END solution_printer] public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); // Instantiate the data problem. // [START data] final DataModel data = new DataModel(); // [END data] // Create Routing Index Manager // [START index_manager] RoutingIndexManager manager = new RoutingIndexManager(data.distanceMatrix.length, data.vehicleNumber, data.depot); // [END index_manager] // Create Routing Model. // [START routing_model] RoutingModel routing = new RoutingModel(manager); // [END routing_model] // Create and register a transit callback. // [START transit_callback] final int transitCallbackIndex = routing.registerTransitCallback((long fromIndex, long toIndex) -> { // Convert from routing variable Index to user NodeIndex. int fromNode = manager.indexToNode(fromIndex); int toNode = manager.indexToNode(toIndex); return data.distanceMatrix[fromNode][toNode]; }); // [END transit_callback] // Define cost of each arc. // [START arc_cost] routing.setArcCostEvaluatorOfAllVehicles(transitCallbackIndex); // [END arc_cost] // Add Distance constraint. // [START distance_constraint] routing.addDimension(transitCallbackIndex, // transit callback index 0, // no slack 3000, // vehicle maximum travel distance true, // start cumul to zero "Distance"); RoutingDimension distanceDimension = routing.getMutableDimension("Distance"); distanceDimension.setGlobalSpanCostCoefficient(100); // [END distance_constraint] // Define Transportation Requests. // [START pickup_delivery_constraint] Solver solver = routing.solver(); for (int[] request : data.pickupsDeliveries) { long pickupIndex = manager.nodeToIndex(request[0]); long deliveryIndex = manager.nodeToIndex(request[1]); routing.addPickupAndDelivery(pickupIndex, deliveryIndex); solver.addConstraint( solver.makeEquality(routing.vehicleVar(pickupIndex), routing.vehicleVar(deliveryIndex))); solver.addConstraint(solver.makeLessOrEqual( distanceDimension.cumulVar(pickupIndex), distanceDimension.cumulVar(deliveryIndex))); } routing.setPickupAndDeliveryPolicyOfAllVehicles(RoutingModel.PICKUP_AND_DELIVERY_LIFO); // [END pickup_delivery_constraint] // Setting first solution heuristic. // [START parameters] RoutingSearchParameters searchParameters = main.defaultRoutingSearchParameters() .toBuilder() .setFirstSolutionStrategy(FirstSolutionStrategy.Value.PARALLEL_CHEAPEST_INSERTION) .build(); // [END parameters] // Solve the problem. // [START solve] Assignment solution = routing.solveWithParameters(searchParameters); // [END solve] // Print solution on console. // [START print_solution] printSolution(data, routing, manager, solution); // [END print_solution] } } // [END program]
7,587
41.391061
99
java
or-tools
or-tools-master/ortools/constraint_solver/samples/VrpResources.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START program] package com.google.ortools.constraintsolver.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.constraintsolver.Assignment; import com.google.ortools.constraintsolver.FirstSolutionStrategy; import com.google.ortools.constraintsolver.IntVar; import com.google.ortools.constraintsolver.IntervalVar; import com.google.ortools.constraintsolver.RoutingDimension; import com.google.ortools.constraintsolver.RoutingIndexManager; import com.google.ortools.constraintsolver.RoutingModel; import com.google.ortools.constraintsolver.RoutingSearchParameters; import com.google.ortools.constraintsolver.Solver; import com.google.ortools.constraintsolver.main; import java.util.Arrays; import java.util.logging.Logger; // [END import] /** Minimal VRP with Resource Constraints.*/ public class VrpResources { private static final Logger logger = Logger.getLogger(VrpResources.class.getName()); // [START data_model] static class DataModel { public final long[][] timeMatrix = { {0, 6, 9, 8, 7, 3, 6, 2, 3, 2, 6, 6, 4, 4, 5, 9, 7}, {6, 0, 8, 3, 2, 6, 8, 4, 8, 8, 13, 7, 5, 8, 12, 10, 14}, {9, 8, 0, 11, 10, 6, 3, 9, 5, 8, 4, 15, 14, 13, 9, 18, 9}, {8, 3, 11, 0, 1, 7, 10, 6, 10, 10, 14, 6, 7, 9, 14, 6, 16}, {7, 2, 10, 1, 0, 6, 9, 4, 8, 9, 13, 4, 6, 8, 12, 8, 14}, {3, 6, 6, 7, 6, 0, 2, 3, 2, 2, 7, 9, 7, 7, 6, 12, 8}, {6, 8, 3, 10, 9, 2, 0, 6, 2, 5, 4, 12, 10, 10, 6, 15, 5}, {2, 4, 9, 6, 4, 3, 6, 0, 4, 4, 8, 5, 4, 3, 7, 8, 10}, {3, 8, 5, 10, 8, 2, 2, 4, 0, 3, 4, 9, 8, 7, 3, 13, 6}, {2, 8, 8, 10, 9, 2, 5, 4, 3, 0, 4, 6, 5, 4, 3, 9, 5}, {6, 13, 4, 14, 13, 7, 4, 8, 4, 4, 0, 10, 9, 8, 4, 13, 4}, {6, 7, 15, 6, 4, 9, 12, 5, 9, 6, 10, 0, 1, 3, 7, 3, 10}, {4, 5, 14, 7, 6, 7, 10, 4, 8, 5, 9, 1, 0, 2, 6, 4, 8}, {4, 8, 13, 9, 8, 7, 10, 3, 7, 4, 8, 3, 2, 0, 4, 5, 6}, {5, 12, 9, 14, 12, 6, 6, 7, 3, 3, 4, 7, 6, 4, 0, 9, 2}, {9, 10, 18, 6, 8, 12, 15, 8, 13, 9, 13, 3, 4, 5, 9, 0, 9}, {7, 14, 9, 16, 14, 8, 5, 10, 6, 5, 4, 10, 8, 6, 2, 9, 0}, }; public final long[][] timeWindows = { {0, 5}, // depot {7, 12}, // 1 {10, 15}, // 2 {5, 14}, // 3 {5, 13}, // 4 {0, 5}, // 5 {5, 10}, // 6 {0, 10}, // 7 {5, 10}, // 8 {0, 5}, // 9 {10, 16}, // 10 {10, 15}, // 11 {0, 5}, // 12 {5, 10}, // 13 {7, 12}, // 14 {10, 15}, // 15 {5, 15}, // 16 }; public final int vehicleNumber = 4; // [START resources_data] public final int vehicleLoadTime = 5; public final int vehicleUnloadTime = 5; public final int depotCapacity = 2; // [END resources_data] public final int depot = 0; } // [END data_model] // [START solution_printer] /// @brief Print the solution. static void printSolution( DataModel data, RoutingModel routing, RoutingIndexManager manager, Assignment solution) { // Solution cost. logger.info("Objective : " + solution.objectiveValue()); // Inspect solution. RoutingDimension timeDimension = routing.getMutableDimension("Time"); long totalTime = 0; for (int i = 0; i < data.vehicleNumber; ++i) { long index = routing.start(i); logger.info("Route for Vehicle " + i + ":"); String route = ""; while (!routing.isEnd(index)) { IntVar timeVar = timeDimension.cumulVar(index); route += manager.indexToNode(index) + " Time(" + solution.min(timeVar) + "," + solution.max(timeVar) + ") -> "; index = solution.value(routing.nextVar(index)); } IntVar timeVar = timeDimension.cumulVar(index); route += manager.indexToNode(index) + " Time(" + solution.min(timeVar) + "," + solution.max(timeVar) + ")"; logger.info(route); logger.info("Time of the route: " + solution.min(timeVar) + "min"); totalTime += solution.min(timeVar); } logger.info("Total time of all routes: " + totalTime + "min"); } // [END solution_printer] public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); // Instantiate the data problem. // [START data] final DataModel data = new DataModel(); // [END data] // Create Routing Index Manager // [START index_manager] RoutingIndexManager manager = new RoutingIndexManager(data.timeMatrix.length, data.vehicleNumber, data.depot); // [END index_manager] // Create Routing Model. // [START routing_model] RoutingModel routing = new RoutingModel(manager); // [END routing_model] // Create and register a transit callback. // [START transit_callback] final int transitCallbackIndex = routing.registerTransitCallback((long fromIndex, long toIndex) -> { // Convert from routing variable Index to user NodeIndex. int fromNode = manager.indexToNode(fromIndex); int toNode = manager.indexToNode(toIndex); return data.timeMatrix[fromNode][toNode]; }); // [END transit_callback] // Define cost of each arc. // [START arc_cost] routing.setArcCostEvaluatorOfAllVehicles(transitCallbackIndex); // [END arc_cost] // Add Time constraint. // [START time_constraint] routing.addDimension(transitCallbackIndex, // transit callback 30, // allow waiting time 30, // vehicle maximum capacities false, // start cumul to zero "Time"); RoutingDimension timeDimension = routing.getMutableDimension("Time"); // Add time window constraints for each location except depot. for (int i = 1; i < data.timeWindows.length; ++i) { long index = manager.nodeToIndex(i); timeDimension.cumulVar(index).setRange(data.timeWindows[i][0], data.timeWindows[i][1]); } // Add time window constraints for each vehicle start node. for (int i = 0; i < data.vehicleNumber; ++i) { long index = routing.start(i); timeDimension.cumulVar(index).setRange(data.timeWindows[0][0], data.timeWindows[0][1]); } // [END time_constraint] // Add resource constraints at the depot. // [START depot_load_time] Solver solver = routing.solver(); IntervalVar[] intervals = new IntervalVar[data.vehicleNumber * 2]; for (int i = 0; i < data.vehicleNumber; ++i) { // Add load duration at start of routes intervals[2 * i] = solver.makeFixedDurationIntervalVar( timeDimension.cumulVar(routing.start(i)), data.vehicleLoadTime, "depot_interval"); // Add unload duration at end of routes. intervals[2 * i + 1] = solver.makeFixedDurationIntervalVar( timeDimension.cumulVar(routing.end(i)), data.vehicleUnloadTime, "depot_interval"); } // [END depot_load_time] // [START depot_capacity] long[] depotUsage = new long[intervals.length]; Arrays.fill(depotUsage, 1); solver.addConstraint(solver.makeCumulative(intervals, depotUsage, data.depotCapacity, "depot")); // [END depot_capacity] // Instantiate route start and end times to produce feasible times. // [START depot_start_end_times] for (int i = 0; i < data.vehicleNumber; ++i) { routing.addVariableMinimizedByFinalizer(timeDimension.cumulVar(routing.start(i))); routing.addVariableMinimizedByFinalizer(timeDimension.cumulVar(routing.end(i))); } // [END depot_start_end_times] // Setting first solution heuristic. // [START parameters] RoutingSearchParameters searchParameters = main.defaultRoutingSearchParameters() .toBuilder() .setFirstSolutionStrategy(FirstSolutionStrategy.Value.PATH_CHEAPEST_ARC) .build(); // [END parameters] // Solve the problem. // [START solve] Assignment solution = routing.solveWithParameters(searchParameters); // [END solve] // Print solution on console. // [START print_solution] printSolution(data, routing, manager, solution); // [END print_solution] } } // [END program]
8,701
38.73516
100
java
or-tools
or-tools-master/ortools/constraint_solver/samples/VrpStartsEnds.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START program] package com.google.ortools.constraintsolver.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.constraintsolver.Assignment; import com.google.ortools.constraintsolver.FirstSolutionStrategy; import com.google.ortools.constraintsolver.RoutingDimension; import com.google.ortools.constraintsolver.RoutingIndexManager; import com.google.ortools.constraintsolver.RoutingModel; import com.google.ortools.constraintsolver.RoutingSearchParameters; import com.google.ortools.constraintsolver.main; import java.util.logging.Logger; // [END import] /** Minimal VRP.*/ public class VrpStartsEnds { private static final Logger logger = Logger.getLogger(VrpStartsEnds.class.getName()); // [START data_model] static class DataModel { public final long[][] distanceMatrix = { {0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354, 468, 776, 662}, {548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674, 1016, 868, 1210}, {776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164, 1130, 788, 1552, 754}, {696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822, 1164, 560, 1358}, {582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708, 1050, 674, 1244}, {274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628, 514, 1050, 708}, {502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856, 514, 1278, 480}, {194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320, 662, 742, 856}, {308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662, 320, 1084, 514}, {194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388, 274, 810, 468}, {536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764, 730, 388, 1152, 354}, {502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114, 308, 650, 274, 844}, {388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194, 536, 388, 730}, {354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0, 342, 422, 536}, {468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536, 342, 0, 764, 194}, {776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274, 388, 422, 764, 0, 798}, {662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730, 536, 194, 798, 0}, }; public final int vehicleNumber = 4; // [START starts_ends] public final int[] starts = {1, 2, 15, 16}; public final int[] ends = {0, 0, 0, 0}; // [END starts_ends] } // [END data_model] // [START solution_printer] /// @brief Print the solution. static void printSolution( DataModel data, RoutingModel routing, RoutingIndexManager manager, Assignment solution) { // Solution cost. logger.info("Objective : " + solution.objectiveValue()); // Inspect solution. long maxRouteDistance = 0; for (int i = 0; i < data.vehicleNumber; ++i) { long index = routing.start(i); logger.info("Route for Vehicle " + i + ":"); long routeDistance = 0; String route = ""; while (!routing.isEnd(index)) { route += manager.indexToNode(index) + " -> "; long previousIndex = index; index = solution.value(routing.nextVar(index)); routeDistance += routing.getArcCostForVehicle(previousIndex, index, i); } logger.info(route + manager.indexToNode(index)); logger.info("Distance of the route: " + routeDistance + "m"); maxRouteDistance = Math.max(routeDistance, maxRouteDistance); } logger.info("Maximum of the route distances: " + maxRouteDistance + "m"); } // [END solution_printer] public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); // Instantiate the data problem. // [START data] final DataModel data = new DataModel(); // [END data] // Create Routing Index Manager // [START index_manager] RoutingIndexManager manager = new RoutingIndexManager( data.distanceMatrix.length, data.vehicleNumber, data.starts, data.ends); // [END index_manager] // Create Routing Model. // [START routing_model] RoutingModel routing = new RoutingModel(manager); // [END routing_model] // Create and register a transit callback. // [START transit_callback] final int transitCallbackIndex = routing.registerTransitCallback((long fromIndex, long toIndex) -> { // Convert from routing variable Index to user NodeIndex. int fromNode = manager.indexToNode(fromIndex); int toNode = manager.indexToNode(toIndex); return data.distanceMatrix[fromNode][toNode]; }); // [END transit_callback] // Define cost of each arc. // [START arc_cost] routing.setArcCostEvaluatorOfAllVehicles(transitCallbackIndex); // [END arc_cost] // Add Distance constraint. // [START distance_constraint] routing.addDimension(transitCallbackIndex, 0, 2000, true, // start cumul to zero "Distance"); RoutingDimension distanceDimension = routing.getMutableDimension("Distance"); distanceDimension.setGlobalSpanCostCoefficient(100); // [END distance_constraint] // Setting first solution heuristic. // [START parameters] RoutingSearchParameters searchParameters = main.defaultRoutingSearchParameters() .toBuilder() .setFirstSolutionStrategy(FirstSolutionStrategy.Value.PATH_CHEAPEST_ARC) .build(); // [END parameters] // Solve the problem. // [START solve] Assignment solution = routing.solveWithParameters(searchParameters); // [END solve] // Print solution on console. // [START print_solution] printSolution(data, routing, manager, solution); // [END print_solution] } } // [END program]
6,535
42
97
java
or-tools
or-tools-master/ortools/constraint_solver/samples/VrpTimeWindows.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START program] package com.google.ortools.constraintsolver.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.constraintsolver.Assignment; import com.google.ortools.constraintsolver.FirstSolutionStrategy; import com.google.ortools.constraintsolver.IntVar; import com.google.ortools.constraintsolver.RoutingDimension; import com.google.ortools.constraintsolver.RoutingIndexManager; import com.google.ortools.constraintsolver.RoutingModel; import com.google.ortools.constraintsolver.RoutingSearchParameters; import com.google.ortools.constraintsolver.main; import java.util.logging.Logger; // [END import] /** VRPTW. */ public class VrpTimeWindows { private static final Logger logger = Logger.getLogger(VrpTimeWindows.class.getName()); // [START program_part1] // [START data_model] static class DataModel { public final long[][] timeMatrix = { {0, 6, 9, 8, 7, 3, 6, 2, 3, 2, 6, 6, 4, 4, 5, 9, 7}, {6, 0, 8, 3, 2, 6, 8, 4, 8, 8, 13, 7, 5, 8, 12, 10, 14}, {9, 8, 0, 11, 10, 6, 3, 9, 5, 8, 4, 15, 14, 13, 9, 18, 9}, {8, 3, 11, 0, 1, 7, 10, 6, 10, 10, 14, 6, 7, 9, 14, 6, 16}, {7, 2, 10, 1, 0, 6, 9, 4, 8, 9, 13, 4, 6, 8, 12, 8, 14}, {3, 6, 6, 7, 6, 0, 2, 3, 2, 2, 7, 9, 7, 7, 6, 12, 8}, {6, 8, 3, 10, 9, 2, 0, 6, 2, 5, 4, 12, 10, 10, 6, 15, 5}, {2, 4, 9, 6, 4, 3, 6, 0, 4, 4, 8, 5, 4, 3, 7, 8, 10}, {3, 8, 5, 10, 8, 2, 2, 4, 0, 3, 4, 9, 8, 7, 3, 13, 6}, {2, 8, 8, 10, 9, 2, 5, 4, 3, 0, 4, 6, 5, 4, 3, 9, 5}, {6, 13, 4, 14, 13, 7, 4, 8, 4, 4, 0, 10, 9, 8, 4, 13, 4}, {6, 7, 15, 6, 4, 9, 12, 5, 9, 6, 10, 0, 1, 3, 7, 3, 10}, {4, 5, 14, 7, 6, 7, 10, 4, 8, 5, 9, 1, 0, 2, 6, 4, 8}, {4, 8, 13, 9, 8, 7, 10, 3, 7, 4, 8, 3, 2, 0, 4, 5, 6}, {5, 12, 9, 14, 12, 6, 6, 7, 3, 3, 4, 7, 6, 4, 0, 9, 2}, {9, 10, 18, 6, 8, 12, 15, 8, 13, 9, 13, 3, 4, 5, 9, 0, 9}, {7, 14, 9, 16, 14, 8, 5, 10, 6, 5, 4, 10, 8, 6, 2, 9, 0}, }; public final long[][] timeWindows = { {0, 5}, // depot {7, 12}, // 1 {10, 15}, // 2 {16, 18}, // 3 {10, 13}, // 4 {0, 5}, // 5 {5, 10}, // 6 {0, 4}, // 7 {5, 10}, // 8 {0, 3}, // 9 {10, 16}, // 10 {10, 15}, // 11 {0, 5}, // 12 {5, 10}, // 13 {7, 8}, // 14 {10, 15}, // 15 {11, 15}, // 16 }; public final int vehicleNumber = 4; public final int depot = 0; } // [END data_model] // [START solution_printer] /// @brief Print the solution. static void printSolution( DataModel data, RoutingModel routing, RoutingIndexManager manager, Assignment solution) { // Solution cost. logger.info("Objective : " + solution.objectiveValue()); // Inspect solution. RoutingDimension timeDimension = routing.getMutableDimension("Time"); long totalTime = 0; for (int i = 0; i < data.vehicleNumber; ++i) { long index = routing.start(i); logger.info("Route for Vehicle " + i + ":"); String route = ""; while (!routing.isEnd(index)) { IntVar timeVar = timeDimension.cumulVar(index); route += manager.indexToNode(index) + " Time(" + solution.min(timeVar) + "," + solution.max(timeVar) + ") -> "; index = solution.value(routing.nextVar(index)); } IntVar timeVar = timeDimension.cumulVar(index); route += manager.indexToNode(index) + " Time(" + solution.min(timeVar) + "," + solution.max(timeVar) + ")"; logger.info(route); logger.info("Time of the route: " + solution.min(timeVar) + "min"); totalTime += solution.min(timeVar); } logger.info("Total time of all routes: " + totalTime + "min"); } // [END solution_printer] public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); // Instantiate the data problem. // [START data] final DataModel data = new DataModel(); // [END data] // Create Routing Index Manager // [START index_manager] RoutingIndexManager manager = new RoutingIndexManager(data.timeMatrix.length, data.vehicleNumber, data.depot); // [END index_manager] // Create Routing Model. // [START routing_model] RoutingModel routing = new RoutingModel(manager); // [END routing_model] // Create and register a transit callback. // [START transit_callback] final int transitCallbackIndex = routing.registerTransitCallback((long fromIndex, long toIndex) -> { // Convert from routing variable Index to user NodeIndex. int fromNode = manager.indexToNode(fromIndex); int toNode = manager.indexToNode(toIndex); return data.timeMatrix[fromNode][toNode]; }); // [END transit_callback] // Define cost of each arc. // [START arc_cost] routing.setArcCostEvaluatorOfAllVehicles(transitCallbackIndex); // [END arc_cost] // Add Time constraint. // [START time_constraint] routing.addDimension(transitCallbackIndex, // transit callback 30, // allow waiting time 30, // vehicle maximum capacities false, // start cumul to zero "Time"); RoutingDimension timeDimension = routing.getMutableDimension("Time"); // Add time window constraints for each location except depot. for (int i = 1; i < data.timeWindows.length; ++i) { long index = manager.nodeToIndex(i); timeDimension.cumulVar(index).setRange(data.timeWindows[i][0], data.timeWindows[i][1]); } // Add time window constraints for each vehicle start node. for (int i = 0; i < data.vehicleNumber; ++i) { long index = routing.start(i); timeDimension.cumulVar(index).setRange(data.timeWindows[0][0], data.timeWindows[0][1]); } // [END time_constraint] // Instantiate route start and end times to produce feasible times. // [START depot_start_end_times] for (int i = 0; i < data.vehicleNumber; ++i) { routing.addVariableMinimizedByFinalizer(timeDimension.cumulVar(routing.start(i))); routing.addVariableMinimizedByFinalizer(timeDimension.cumulVar(routing.end(i))); } // [END depot_start_end_times] // Setting first solution heuristic. // [START parameters] RoutingSearchParameters searchParameters = main.defaultRoutingSearchParameters() .toBuilder() .setFirstSolutionStrategy(FirstSolutionStrategy.Value.PATH_CHEAPEST_ARC) .build(); // [END parameters] // Solve the problem. // [START solve] Assignment solution = routing.solveWithParameters(searchParameters); // [END solve] // Print solution on console. // [START print_solution] printSolution(data, routing, manager, solution); // [END print_solution] } } // [END_program_part1] // [END program]
7,484
37.984375
95
java
or-tools
or-tools-master/ortools/constraint_solver/samples/VrpWithTimeLimit.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START program] package com.google.ortools.constraintsolver.samples; // [START import] import static java.lang.Math.max; import com.google.ortools.Loader; import com.google.ortools.constraintsolver.Assignment; import com.google.ortools.constraintsolver.FirstSolutionStrategy; import com.google.ortools.constraintsolver.LocalSearchMetaheuristic; import com.google.ortools.constraintsolver.RoutingDimension; import com.google.ortools.constraintsolver.RoutingIndexManager; import com.google.ortools.constraintsolver.RoutingModel; import com.google.ortools.constraintsolver.RoutingSearchParameters; import com.google.ortools.constraintsolver.main; import com.google.protobuf.Duration; import java.util.logging.Logger; // [END import] /** Minimal VRP. */ public final class VrpWithTimeLimit { private static final Logger logger = Logger.getLogger(VrpWithTimeLimit.class.getName()); // [START solution_printer] /// @brief Print the solution. static void printSolution( RoutingIndexManager manager, RoutingModel routing, Assignment solution) { // Solution cost. logger.info("Objective : " + solution.objectiveValue()); // Inspect solution. long maxRouteDistance = 0; for (int i = 0; i < manager.getNumberOfVehicles(); ++i) { long index = routing.start(i); logger.info("Route for Vehicle " + i + ":"); long routeDistance = 0; String route = ""; while (!routing.isEnd(index)) { route += manager.indexToNode(index) + " -> "; long previousIndex = index; index = solution.value(routing.nextVar(index)); routeDistance += routing.getArcCostForVehicle(previousIndex, index, i); } logger.info(route + manager.indexToNode(index)); logger.info("Distance of the route: " + routeDistance + "m"); maxRouteDistance = max(routeDistance, maxRouteDistance); } logger.info("Maximum of the route distances: " + maxRouteDistance + "m"); } // [END solution_printer] public static void main(String[] args) { Loader.loadNativeLibraries(); // Instantiate the data problem. // [START data] final int locationNumber = 20; final int vehicleNumber = 5; final int depot = 0; // [END data] // Create Routing Index Manager // [START index_manager] RoutingIndexManager manager = new RoutingIndexManager(locationNumber, vehicleNumber, depot); // [END index_manager] // Create Routing Model. // [START routing_model] RoutingModel routing = new RoutingModel(manager); // [END routing_model] // Create and register a transit callback. // [START transit_callback] final int transitCallbackIndex = routing.registerTransitCallback((long fromIndex, long toIndex) -> 1); // [END transit_callback] // Define cost of each arc. // [START arc_cost] routing.setArcCostEvaluatorOfAllVehicles(transitCallbackIndex); // [END arc_cost] // Add Distance constraint. // [START distance_constraint] routing.addDimension(transitCallbackIndex, /*slack_max=*/0, /*capacity=*/3000, /*fix_start_cumul_to_zero=*/true, "Distance"); RoutingDimension distanceDimension = routing.getMutableDimension("Distance"); distanceDimension.setGlobalSpanCostCoefficient(100); // [END distance_constraint] // Setting first solution heuristic. // [START parameters] RoutingSearchParameters searchParameters = main.defaultRoutingSearchParameters() .toBuilder() .setFirstSolutionStrategy(FirstSolutionStrategy.Value.PATH_CHEAPEST_ARC) .setLocalSearchMetaheuristic(LocalSearchMetaheuristic.Value.GUIDED_LOCAL_SEARCH) .setLogSearch(true) .setTimeLimit(Duration.newBuilder().setSeconds(5).build()) .build(); // [END parameters] // Solve the problem. // [START solve] Assignment solution = routing.solveWithParameters(searchParameters); // [END solve] // Print solution on console. // [START print_solution] printSolution(manager, routing, solution); // [END print_solution] } private VrpWithTimeLimit() {} } // [END program]
4,756
35.875969
96
java
or-tools
or-tools-master/ortools/graph/samples/AssignmentLinearSumAssignment.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START program] package com.google.ortools.graph.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.graph.LinearSumAssignment; import java.util.stream.IntStream; // [END import] /** Minimal Linear Sum Assignment problem. */ public class AssignmentLinearSumAssignment { public static void main(String[] args) { Loader.loadNativeLibraries(); // [START solver] LinearSumAssignment assignment = new LinearSumAssignment(); // [END solver] // [START data] final int[][] costs = { {90, 76, 75, 70}, {35, 85, 55, 65}, {125, 95, 90, 105}, {45, 110, 95, 115}, }; final int numWorkers = 4; final int numTasks = 4; final int[] allWorkers = IntStream.range(0, numWorkers).toArray(); final int[] allTasks = IntStream.range(0, numTasks).toArray(); // [END data] // [START constraints] // Add each arc. for (int w : allWorkers) { for (int t : allTasks) { if (costs[w][t] != 0) { assignment.addArcWithCost(w, t, costs[w][t]); } } } // [END constraints] // [START solve] LinearSumAssignment.Status status = assignment.solve(); // [END solve] // [START print_solution] if (status == LinearSumAssignment.Status.OPTIMAL) { System.out.println("Total cost: " + assignment.getOptimalCost()); for (int worker : allWorkers) { System.out.println("Worker " + worker + " assigned to task " + assignment.getRightMate(worker) + ". Cost: " + assignment.getAssignmentCost(worker)); } } else { System.out.println("Solving the min cost flow problem failed."); System.out.println("Solver status: " + status); } // [END print_solution] } private AssignmentLinearSumAssignment() {} } // [END program]
2,425
30.921053
99
java
or-tools
or-tools-master/ortools/graph/samples/AssignmentMinFlow.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START program] package com.google.ortools.graph.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.graph.MinCostFlow; import com.google.ortools.graph.MinCostFlowBase; // [END import] /** Minimal Assignment Min Flow. */ public class AssignmentMinFlow { public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); // [START solver] // Instantiate a SimpleMinCostFlow solver. MinCostFlow minCostFlow = new MinCostFlow(); // [END solver] // [START data] // Define four parallel arrays: sources, destinations, capacities, and unit costs // between each pair. int[] startNodes = new int[] {0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 6, 7, 8}; int[] endNodes = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 5, 6, 7, 8, 5, 6, 7, 8, 5, 6, 7, 8, 9, 9, 9, 9}; int[] capacities = new int[] {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; int[] unitCosts = new int[] { 0, 0, 0, 0, 90, 76, 75, 70, 35, 85, 55, 65, 125, 95, 90, 105, 45, 110, 95, 115, 0, 0, 0, 0}; int source = 0; int sink = 9; int tasks = 4; // Define an array of supplies at each node. int[] supplies = new int[] {tasks, 0, 0, 0, 0, 0, 0, 0, 0, -tasks}; // [END data] // [START constraints] // Add each arc. for (int i = 0; i < startNodes.length; ++i) { int arc = minCostFlow.addArcWithCapacityAndUnitCost( startNodes[i], endNodes[i], capacities[i], unitCosts[i]); if (arc != i) { throw new Exception("Internal error"); } } // Add node supplies. for (int i = 0; i < supplies.length; ++i) { minCostFlow.setNodeSupply(i, supplies[i]); } // [END constraints] // [START solve] // Find the min cost flow. MinCostFlowBase.Status status = minCostFlow.solve(); // [END solve] // [START print_solution] if (status == MinCostFlow.Status.OPTIMAL) { System.out.println("Total cost: " + minCostFlow.getOptimalCost()); System.out.println(); for (int i = 0; i < minCostFlow.getNumArcs(); ++i) { // Can ignore arcs leading out of source or into sink. if (minCostFlow.getTail(i) != source && minCostFlow.getHead(i) != sink) { // Arcs in the solution have a flow value of 1. Their start and end nodes // give an assignment of worker to task. if (minCostFlow.getFlow(i) > 0) { System.out.println("Worker " + minCostFlow.getTail(i) + " assigned to task " + minCostFlow.getHead(i) + " Cost: " + minCostFlow.getUnitCost(i)); } } } } else { System.out.println("Solving the min cost flow problem failed."); System.out.println("Solver status: " + status); } // [END print_solution] } private AssignmentMinFlow() {} } // [END program]
3,511
35.583333
100
java
or-tools
or-tools-master/ortools/graph/samples/BalanceMinFlow.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START program] package com.google.ortools.graph.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.graph.MinCostFlow; import com.google.ortools.graph.MinCostFlowBase; // [END import] /** Minimal Assignment Min Flow. */ public class BalanceMinFlow { public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); // [START solver] // Instantiate a SimpleMinCostFlow solver. MinCostFlow minCostFlow = new MinCostFlow(); // [END solver] // [START data] // Define the directed graph for the flow. // int[] teamA = new int[] {1, 3, 5}; // int[] teamB = new int[] {2, 4, 6}; int[] startNodes = new int[] {0, 0, 11, 11, 11, 12, 12, 12, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 8, 9, 10}; int[] endNodes = new int[] {11, 12, 1, 3, 5, 2, 4, 6, 7, 8, 9, 10, 7, 8, 9, 10, 7, 8, 9, 10, 7, 8, 9, 10, 7, 8, 9, 10, 7, 8, 9, 10, 13, 13, 13, 13}; int[] capacities = new int[] {2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; int[] unitCosts = new int[] {0, 0, 0, 0, 0, 0, 0, 0, 90, 76, 75, 70, 35, 85, 55, 65, 125, 95, 90, 105, 45, 110, 95, 115, 60, 105, 80, 75, 45, 65, 110, 95, 0, 0, 0, 0}; int source = 0; int sink = 13; int tasks = 4; // Define an array of supplies at each node. int[] supplies = new int[] {tasks, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -tasks}; // [END data] // [START constraints] // Add each arc. for (int i = 0; i < startNodes.length; ++i) { int arc = minCostFlow.addArcWithCapacityAndUnitCost( startNodes[i], endNodes[i], capacities[i], unitCosts[i]); if (arc != i) { throw new Exception("Internal error"); } } // Add node supplies. for (int i = 0; i < supplies.length; ++i) { minCostFlow.setNodeSupply(i, supplies[i]); } // [END constraints] // [START solve] // Find the min cost flow. MinCostFlowBase.Status status = minCostFlow.solve(); // [END solve] // [START print_solution] if (status == MinCostFlow.Status.OPTIMAL) { System.out.println("Total cost: " + minCostFlow.getOptimalCost()); System.out.println(); for (int i = 0; i < minCostFlow.getNumArcs(); ++i) { // Can ignore arcs leading out of source or intermediate nodes, or into sink. if (minCostFlow.getTail(i) != source && minCostFlow.getTail(i) != 11 && minCostFlow.getTail(i) != 12 && minCostFlow.getHead(i) != sink) { // Arcs in the solution have a flow value of 1. Their start and end nodes // give an assignment of worker to task. if (minCostFlow.getFlow(i) > 0) { System.out.println("Worker " + minCostFlow.getTail(i) + " assigned to task " + minCostFlow.getHead(i) + " Cost: " + minCostFlow.getUnitCost(i)); } } } } else { System.out.println("Solving the min cost flow problem failed."); System.out.println("Solver status: " + status); } // [END print_solution] } private BalanceMinFlow() {} } // [END program]
3,809
37.484848
99
java
or-tools
or-tools-master/ortools/graph/samples/SimpleMaxFlowProgram.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START program] package com.google.ortools.graph.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.graph.MaxFlow; // [END import] /** Minimal MaxFlow program. */ public final class SimpleMaxFlowProgram { public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); // [START solver] // Instantiate a SimpleMaxFlow solver. MaxFlow maxFlow = new MaxFlow(); // [END solver] // [START data] // Define three parallel arrays: start_nodes, end_nodes, and the capacities // between each pair. For instance, the arc from node 0 to node 1 has a // capacity of 20. // From Taha's 'Introduction to Operations Research', // example 6.4-2. int[] startNodes = new int[] {0, 0, 0, 1, 1, 2, 2, 3, 3}; int[] endNodes = new int[] {1, 2, 3, 2, 4, 3, 4, 2, 4}; int[] capacities = new int[] {20, 30, 10, 40, 30, 10, 20, 5, 20}; // [END data] // [START constraints] // Add each arc. for (int i = 0; i < startNodes.length; ++i) { int arc = maxFlow.addArcWithCapacity(startNodes[i], endNodes[i], capacities[i]); if (arc != i) { throw new Exception("Internal error"); } } // [END constraints] // [START solve] // Find the maximum flow between node 0 and node 4. MaxFlow.Status status = maxFlow.solve(0, 4); // [END solve] // [START print_solution] if (status == MaxFlow.Status.OPTIMAL) { System.out.println("Max. flow: " + maxFlow.getOptimalFlow()); System.out.println(); System.out.println(" Arc Flow / Capacity"); for (int i = 0; i < maxFlow.getNumArcs(); ++i) { System.out.println(maxFlow.getTail(i) + " -> " + maxFlow.getHead(i) + " " + maxFlow.getFlow(i) + " / " + maxFlow.getCapacity(i)); } } else { System.out.println("Solving the max flow problem failed. Solver status: " + status); } // [END print_solution] } private SimpleMaxFlowProgram() {} } // [END program]
2,623
34.459459
90
java
or-tools
or-tools-master/ortools/graph/samples/SimpleMinCostFlowProgram.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START program] // From Bradley, Hax, and Maganti, 'Applied Mathematical Programming', figure 8.1. package com.google.ortools.graph.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.graph.MinCostFlow; import com.google.ortools.graph.MinCostFlowBase; // [END import] /** Minimal MinCostFlow program. */ public class SimpleMinCostFlowProgram { public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); // [START solver] // Instantiate a SimpleMinCostFlow solver. MinCostFlow minCostFlow = new MinCostFlow(); // [END solver] // [START data] // Define four parallel arrays: sources, destinations, capacities, and unit costs // between each pair. For instance, the arc from node 0 to node 1 has a // capacity of 15. // Problem taken From Taha's 'Introduction to Operations Research', // example 6.4-2. int[] startNodes = new int[] {0, 0, 1, 1, 1, 2, 2, 3, 4}; int[] endNodes = new int[] {1, 2, 2, 3, 4, 3, 4, 4, 2}; int[] capacities = new int[] {15, 8, 20, 4, 10, 15, 4, 20, 5}; int[] unitCosts = new int[] {4, 4, 2, 2, 6, 1, 3, 2, 3}; // Define an array of supplies at each node. int[] supplies = new int[] {20, 0, 0, -5, -15}; // [END data] // [START constraints] // Add each arc. for (int i = 0; i < startNodes.length; ++i) { int arc = minCostFlow.addArcWithCapacityAndUnitCost( startNodes[i], endNodes[i], capacities[i], unitCosts[i]); if (arc != i) { throw new Exception("Internal error"); } } // Add node supplies. for (int i = 0; i < supplies.length; ++i) { minCostFlow.setNodeSupply(i, supplies[i]); } // [END constraints] // [START solve] // Find the min cost flow. MinCostFlowBase.Status status = minCostFlow.solve(); // [END solve] // [START print_solution] if (status == MinCostFlow.Status.OPTIMAL) { System.out.println("Minimum cost: " + minCostFlow.getOptimalCost()); System.out.println(); System.out.println(" Edge Flow / Capacity Cost"); for (int i = 0; i < minCostFlow.getNumArcs(); ++i) { long cost = minCostFlow.getFlow(i) * minCostFlow.getUnitCost(i); System.out.println(minCostFlow.getTail(i) + " -> " + minCostFlow.getHead(i) + " " + minCostFlow.getFlow(i) + " / " + minCostFlow.getCapacity(i) + " " + cost); } } else { System.out.println("Solving the min cost flow problem failed."); System.out.println("Solver status: " + status); } // [END print_solution] } private SimpleMinCostFlowProgram() {} } // [END program]
3,272
36.193182
95
java
or-tools
or-tools-master/ortools/java/com/google/ortools/Loader.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools; import com.sun.jna.Platform; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.FileSystem; import java.nio.file.FileSystemAlreadyExistsException; import java.nio.file.FileSystems; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.Collections; import java.util.Objects; /** Load native libraries needed for using ortools-java.*/ public class Loader { private static final String RESOURCE_PATH = "ortools-" + Platform.RESOURCE_PREFIX + "/"; /** Try to locate the native libraries directory.*/ private static URI getNativeResourceURI() throws IOException { ClassLoader loader = Loader.class.getClassLoader(); URL resourceURL = loader.getResource(RESOURCE_PATH); Objects.requireNonNull(resourceURL, String.format("Resource %s was not found in ClassLoader %s", RESOURCE_PATH, loader)); URI resourceURI; try { resourceURI = resourceURL.toURI(); } catch (URISyntaxException e) { throw new IOException(e); } return resourceURI; } @FunctionalInterface private interface PathConsumer<T extends IOException> { void accept(Path path) throws T; } /** * Extract native resources in a temp directory. * @param resourceURI Native resource location. * @return The directory path containing all extracted libraries. */ private static Path unpackNativeResources(URI resourceURI) throws IOException { Path tempPath; tempPath = Files.createTempDirectory("ortools-java"); tempPath.toFile().deleteOnExit(); PathConsumer<?> visitor; visitor = (Path sourcePath) -> Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Path newPath = tempPath.resolve(sourcePath.getParent().relativize(file).toString()); Files.copy(file, newPath); newPath.toFile().deleteOnExit(); return FileVisitResult.CONTINUE; } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { Path newPath = tempPath.resolve(sourcePath.getParent().relativize(dir).toString()); Files.copy(dir, newPath); newPath.toFile().deleteOnExit(); return FileVisitResult.CONTINUE; } }); FileSystem fs; try { fs = FileSystems.newFileSystem(resourceURI, Collections.emptyMap()); } catch (FileSystemAlreadyExistsException e) { fs = FileSystems.getFileSystem(resourceURI); if (fs == null) { throw new IllegalArgumentException(); } } Path p = fs.provider().getPath(resourceURI); visitor.accept(p); return tempPath; } /** Unpack and Load the native libraries needed for using ortools-java.*/ private static boolean loaded = false; public static synchronized void loadNativeLibraries() { if (!loaded) { try { URI resourceURI = getNativeResourceURI(); Path tempPath = unpackNativeResources(resourceURI); // Load the native library System.load(tempPath.resolve(RESOURCE_PATH) .resolve(System.mapLibraryName("jniortools")) .toString()); loaded = true; } catch (IOException e) { throw new RuntimeException(e); } } } }
4,166
33.725
97
java
or-tools
or-tools-master/ortools/java/com/google/ortools/constraintsolver/IntIntToLongFunction.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.constraintsolver; /** * Represents a function that accepts two int-valued arguments and produces a * long-valued result. This is the {@code int}{@code int}-to-{@code long} primitive * specialization for {@link Function}. * * <p>This is a functional interface * whose functional method is {@link #applyAsLong(long, long)}. * @see Function * @see IntToLongFunction. */ @FunctionalInterface public interface IntIntToLongFunction { /** * Applies this function to the given arguments. * * @param left the first argument * @param right the second argument * @return the function result */ long applyAsLong(int left, int right); }
1,274
33.459459
84
java
or-tools
or-tools-master/ortools/java/com/google/ortools/constraintsolver/JavaDecisionBuilder.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.constraintsolver; /** * This class acts as a intermediate step between a c++ decision builder * and a java one. Its main purpose is to catch the java exception launched * when a failure occurs during the Next() call, and to return silently * a FailDecision that will propagate the failure back to the C++ code. * */ public class JavaDecisionBuilder extends DecisionBuilder { /** This methods wraps the calls to next() and catches fail exceptions. */ @Override public final Decision nextWrap(Solver solver) { try { return next(solver); } catch (Solver.FailException e) { return solver.makeFailDecision(); } } /** * This is the new method to subclass when defining a java decision builder. */ public Decision next(Solver solver) throws Solver.FailException { return null; } }
1,446
35.175
78
java
or-tools
or-tools-master/ortools/java/com/google/ortools/constraintsolver/LongTernaryOperator.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.constraintsolver; /** * Represents an operation upon three {@code long}-valued operands and producing a * {@code long}-valued result. This is the primitive type specialization of * TernaryOperator for {@code long}. * * <p>This is a functional interface * whose functional method is {@link #applyAsLong(long, long, long)}. * @see BinaryOperator * @see LongUnaryOperator. */ @FunctionalInterface public interface LongTernaryOperator { /** * Applies this operator to the given operands. * * @param left the first operand * @param center the second operand * @param right the third operand * @return the operator result */ long applyAsLong(long left, long center, long right); }
1,328
33.973684
82
java
or-tools
or-tools-master/ortools/java/com/google/ortools/constraintsolver/LongTernaryPredicate.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.constraintsolver; /** * Represents a predicate (boolean-valued function) uppon * three {@code long}-valued operands. This is the {@code long}-consuming primitive type * specialization of {@link Predicate}. * * <p>This is a functional interface * whose functional method is {@link #test(long, long, long)}. * @see Predicate */ @FunctionalInterface public interface LongTernaryPredicate { /** * Evaluates this predicate on the given arguments. * * @param left the first operand * @param center the second operand * @param right the third operand * @return {@code true} if the input argument matches the predicate, * otherwise {@code false} */ boolean test(long left, long center, long right); /** * Returns a predicate that represents the logical negation of this * predicate. * * @return a predicate that represents the logical negation of this * predicate */ default LongTernaryPredicate negate() { return (left, center, right) -> !test(left, center, right); } }
1,646
32.612245
88
java
or-tools
or-tools-master/ortools/java/com/google/ortools/modelbuilder/AffineExpression.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.modelbuilder; /** A specialized linear expression: a * x + b */ public final class AffineExpression implements LinearExpr { private final int varIndex; private final double coefficient; private final double offset; public AffineExpression(int varIndex, double coefficient, double offset) { this.varIndex = varIndex; this.coefficient = coefficient; this.offset = offset; } // LinearArgument interface. @Override public LinearExpr build() { return this; } // LinearExpr interface. @Override public int numElements() { return 1; } @Override public int getVariableIndex(int index) { if (index != 0) { throw new IllegalArgumentException("wrong index in LinearExpr.getIndex(): " + index); } return varIndex; } @Override public double getCoefficient(int index) { if (index != 0) { throw new IllegalArgumentException("wrong index in LinearExpr.getCoefficient(): " + index); } return coefficient; } @Override public double getOffset() { return offset; } }
1,675
26.47541
97
java
or-tools
or-tools-master/ortools/java/com/google/ortools/modelbuilder/ConstantExpression.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.modelbuilder; /** A specialized constant linear expression. */ public final class ConstantExpression implements LinearExpr { private final double offset; public ConstantExpression(double offset) { this.offset = offset; } // LinearArgument interface. @Override public LinearExpr build() { return this; } // LinearExpr interface. @Override public int numElements() { return 0; } @Override public int getVariableIndex(int index) { throw new IllegalArgumentException("wrong index in LinearExpr.getVariable(): " + index); } @Override public double getCoefficient(int index) { throw new IllegalArgumentException("wrong index in LinearExpr.getCoefficient(): " + index); } @Override public double getOffset() { return offset; } @Override public String toString() { return String.format("%f", offset); } }
1,496
25.732143
95
java
or-tools
or-tools-master/ortools/java/com/google/ortools/modelbuilder/LinearArgument.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.modelbuilder; /** * A object that can build a LinearExpr object. * * <p>This class is used in all modeling methods of the CpModel class. */ public interface LinearArgument { /** Builds a linear expression. */ LinearExpr build(); }
857
33.32
75
java
or-tools
or-tools-master/ortools/java/com/google/ortools/modelbuilder/LinearConstraint.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.modelbuilder; /** Wrapper around a linear constraint stored in the ModelBuilderHelper instance. */ public class LinearConstraint { public LinearConstraint(ModelBuilderHelper helper) { this.helper = helper; this.index = helper.addLinearConstraint(); } /** Returns the index of the constraint in the model. */ public int getIndex() { return index; } /** Returns the constraint builder. */ public ModelBuilderHelper getHelper() { return helper; } /** Returns the lower bound of the variable. */ public double getLowerBound() { return helper.getConstraintLowerBound(index); } /** Returns the lower bound of the variable. */ public void setLowerBound(double lb) { helper.setConstraintLowerBound(index, lb); } /** Returns the upper bound of the variable. */ public double getUpperBound() { return helper.getConstraintUpperBound(index); } /** Returns the upper bound of the variable. */ public void setUpperBound(double ub) { helper.setConstraintUpperBound(index, ub); } /** Returns the name of the variable given upon creation. */ public String getName() { return helper.getConstraintName(index); } // Sets the name of the variable. */ public void setName(String name) { helper.setConstraintName(index, name); } // Adds var * coeff to the constraint. public void addTerm(Variable var, double coeff) { helper.addConstraintTerm(index, var.getIndex(), coeff); } /** Inline setter */ public LinearConstraint withName(String name) { setName(name); return this; } private final ModelBuilderHelper helper; private final int index; }
2,269
28.480519
84
java
or-tools
or-tools-master/ortools/java/com/google/ortools/modelbuilder/LinearExpr.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.modelbuilder; /** A linear expression (sum (ai * xi) + b). It specifies methods to help parsing the expression. */ public interface LinearExpr extends LinearArgument { /** Returns the number of terms (excluding the constant one) in this expression. */ int numElements(); /** Returns the index of the ith variable. */ int getVariableIndex(int index); /** Returns the ith coefficient. */ double getCoefficient(int index); /** Returns the constant part of the expression. */ double getOffset(); /** Returns a builder */ static LinearExprBuilder newBuilder() { return new LinearExprBuilder(); } /** Shortcut for newBuilder().add(value).build() */ static LinearExpr constant(double value) { return newBuilder().add(value).build(); } /** Shortcut for newBuilder().addTerm(expr, coeff).build() */ static LinearExpr term(LinearArgument expr, double coeff) { return newBuilder().addTerm(expr, coeff).build(); } /** Shortcut for newBuilder().addTerm(expr, coeff).add(offset).build() */ static LinearExpr affine(LinearArgument expr, double coeff, double offset) { return newBuilder().addTerm(expr, coeff).add(offset).build(); } /** Shortcut for newBuilder().addSum(exprs).build() */ static LinearExpr sum(LinearArgument[] exprs) { return newBuilder().addSum(exprs).build(); } /** Shortcut for newBuilder().addWeightedSum(exprs, coeffs).build() */ static LinearExpr weightedSum(LinearArgument[] exprs, double[] coeffs) { return newBuilder().addWeightedSum(exprs, coeffs).build(); } }
2,175
35.266667
100
java
or-tools
or-tools-master/ortools/java/com/google/ortools/modelbuilder/LinearExprBuilder.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.modelbuilder; import java.util.Map; import java.util.TreeMap; /** Builder class for the LinearExpr container. */ public final class LinearExprBuilder implements LinearArgument { private final TreeMap<Integer, Double> coefficients; private double offset; LinearExprBuilder() { this.coefficients = new TreeMap<>(); this.offset = 0; } public LinearExprBuilder add(LinearArgument expr) { addTerm(expr, 1); return this; } public LinearExprBuilder add(double constant) { offset = offset + constant; return this; } public LinearExprBuilder addTerm(LinearArgument expr, double coeff) { final LinearExpr e = expr.build(); final int numElements = e.numElements(); for (int i = 0; i < numElements; ++i) { coefficients.merge(e.getVariableIndex(i), e.getCoefficient(i) * coeff, Double::sum); } offset = offset + e.getOffset() * coeff; return this; } public LinearExprBuilder addSum(LinearArgument[] exprs) { for (final LinearArgument expr : exprs) { addTerm(expr, 1); } return this; } public LinearExprBuilder addWeightedSum(LinearArgument[] exprs, double[] coeffs) { for (int i = 0; i < exprs.length; ++i) { addTerm(exprs[i], coeffs[i]); } return this; } public LinearExprBuilder addWeightedSum(LinearArgument[] exprs, int[] coeffs) { for (int i = 0; i < exprs.length; ++i) { addTerm(exprs[i], coeffs[i]); } return this; } public LinearExprBuilder addWeightedSum(LinearArgument[] exprs, long[] coeffs) { for (int i = 0; i < exprs.length; ++i) { addTerm(exprs[i], (double) coeffs[i]); } return this; } @Override public LinearExpr build() { int numElements = 0; int lastVarIndex = -1; double lastCoeff = 0; for (Map.Entry<Integer, Double> entry : coefficients.entrySet()) { if (entry.getValue() != 0) { numElements++; lastVarIndex = entry.getKey(); lastCoeff = entry.getValue(); } } if (numElements == 0) { return new ConstantExpression(offset); } else if (numElements == 1) { return new AffineExpression(lastVarIndex, lastCoeff, offset); } else { int[] varIndices = new int[numElements]; double[] coeffs = new double[numElements]; int index = 0; for (Map.Entry<Integer, Double> entry : coefficients.entrySet()) { if (entry.getValue() != 0) { varIndices[index] = entry.getKey(); coeffs[index] = entry.getValue(); index++; } } return new WeightedSumExpression(varIndices, coeffs, offset); } } }
3,242
29.027778
90
java
or-tools
or-tools-master/ortools/java/com/google/ortools/modelbuilder/ModelBuilder.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.modelbuilder; import java.util.LinkedHashMap; import java.util.Map; /** * Main modeling class. * * <p>Proposes a factory to create all modeling objects understood by the SAT solver. */ public final class ModelBuilder { static class ModelBuilderException extends RuntimeException { public ModelBuilderException(String methodName, String msg) { // Call constructor of parent Exception super(methodName + ": " + msg); } } /** Exception thrown when parallel arrays have mismatched lengths. */ public static class MismatchedArrayLengths extends ModelBuilderException { public MismatchedArrayLengths(String methodName, String array1Name, String array2Name) { super(methodName, array1Name + " and " + array2Name + " have mismatched lengths"); } } /** Exception thrown when an array has a wrong length. */ public static class WrongLength extends ModelBuilderException { public WrongLength(String methodName, String msg) { super(methodName, msg); } } public ModelBuilder() { helper = new ModelBuilderHelper(); constantMap = new LinkedHashMap<>(); } // Integer variables. /** Creates a variable with domain [lb, ub]. */ public Variable newVar(double lb, double ub, boolean isIntegral, String name) { return new Variable(helper, lb, ub, isIntegral, name); } /** Creates an continuous variable with domain [lb, ub]. */ public Variable newNumVar(double lb, double ub, String name) { return new Variable(helper, lb, ub, false, name); } /** Creates an integer variable with domain [lb, ub]. */ public Variable newIntVar(double lb, double ub, String name) { return new Variable(helper, lb, ub, true, name); } /** Creates a Boolean variable with the given name. */ public Variable newBoolVar(String name) { return new Variable(helper, 0, 1, true, name); } /** Creates a constant variable. */ public Variable newConstant(double value) { if (constantMap.containsKey(value)) { return new Variable(helper, constantMap.get(value)); } Variable cste = new Variable(helper, value, value, false, ""); // bounds and name. constantMap.put(value, cste.getIndex()); return cste; } /** Rebuilds a variable from its index. */ public Variable varFromIndex(int index) { return new Variable(helper, index); } // Linear constraints. /** Adds {@code lb <= expr <= ub}. */ public LinearConstraint addLinearConstraint(LinearArgument expr, double lb, double ub) { LinearConstraint lin = new LinearConstraint(helper); final LinearExpr e = expr.build(); for (int i = 0; i < e.numElements(); ++i) { helper.addConstraintTerm(lin.getIndex(), e.getVariableIndex(i), e.getCoefficient(i)); } double offset = e.getOffset(); if (lb == Double.NEGATIVE_INFINITY || lb == Double.POSITIVE_INFINITY) { lin.setLowerBound(lb); } else { lin.setLowerBound(lb - offset); } if (ub == Double.NEGATIVE_INFINITY || ub == Double.POSITIVE_INFINITY) { lin.setUpperBound(ub); } else { lin.setUpperBound(ub - offset); } return lin; } /** Returns the number of variables in the model. */ public int numVariables() { return helper.numVariables(); } /** Adds {@code expr == value}. */ public LinearConstraint addEquality(LinearArgument expr, double value) { return addLinearConstraint(expr, value, value); } /** Adds {@code left == right}. */ public LinearConstraint addEquality(LinearArgument left, LinearArgument right) { LinearExprBuilder difference = LinearExpr.newBuilder(); difference.addTerm(left, 1); difference.addTerm(right, -1); return addLinearConstraint(difference, 0.0, 0.0); } /** Adds {@code expr <= value}. */ public LinearConstraint addLessOrEqual(LinearArgument expr, double value) { return addLinearConstraint(expr, Double.NEGATIVE_INFINITY, value); } /** Adds {@code left <= right}. */ public LinearConstraint addLessOrEqual(LinearArgument left, LinearArgument right) { LinearExprBuilder difference = LinearExpr.newBuilder(); difference.addTerm(left, 1); difference.addTerm(right, -1); return addLinearConstraint(difference, Double.NEGATIVE_INFINITY, 0.0); } /** Adds {@code expr >= value}. */ public LinearConstraint addGreaterOrEqual(LinearArgument expr, double value) { return addLinearConstraint(expr, value, Double.POSITIVE_INFINITY); } /** Adds {@code left >= right}. */ public LinearConstraint addGreaterOrEqual(LinearArgument left, LinearArgument right) { LinearExprBuilder difference = LinearExpr.newBuilder(); difference.addTerm(left, 1); difference.addTerm(right, -1); return addLinearConstraint(difference, 0.0, Double.POSITIVE_INFINITY); } /** Returns the number of constraints in the model. */ public int numConstraints() { return helper.numConstraints(); } /** Minimize expression */ public void minimize(LinearArgument obj) { optimize(obj, false); } /** Minimize expression */ public void maximize(LinearArgument obj) { optimize(obj, true); } /** Sets the objective expression. */ public void optimize(LinearArgument obj, boolean maximize) { helper.clearObjective(); LinearExpr e = obj.build(); LinkedHashMap<Integer, Double> coeffMap = new LinkedHashMap<>(); for (int i = 0; i < e.numElements(); ++i) { coeffMap.merge(e.getVariableIndex(i), e.getCoefficient(i), Double::sum); } for (Map.Entry<Integer, Double> entry : coeffMap.entrySet()) { if (entry.getValue() != 0) { helper.setVarObjectiveCoefficient(entry.getKey(), entry.getValue()); } } helper.setObjectiveOffset(e.getOffset()); helper.setMaximize(maximize); } /** returns the objective offset. */ double getObjectiveOffset() { return helper.getObjectiveOffset(); } /** Sets the objective offset. */ void setObjectiveOffset(double offset) { helper.setObjectiveOffset(offset); } // Model getters, import, export. /** Returns the name of the model. */ public String getName() { return helper.getName(); } /** Sets the name of the model. */ public void setName(String name) { helper.setName(name); } /** * Write the model as a protocol buffer to 'file'. * * @param file file to write the model to. If the filename ends with 'txt', the model will be * written as a text file, otherwise, the binary format will be used. * @return true if the model was correctly written. */ public boolean exportToFile(String file) { return helper.writeModelToFile(file); } public String exportToMpsString(boolean obfuscate) { return helper.exportToMpsString(obfuscate); } public String exportToLpString(boolean obfuscate) { return helper.exportToLpString(obfuscate); } public boolean importFromMpsString(String mpsString) { return helper.importFromMpsString(mpsString); } public boolean importFromMpsFile(String mpsFile) { return helper.importFromMpsString(mpsFile); } public boolean importFromLpString(String lpString) { return helper.importFromLpString(lpString); } public boolean importFromLpFile(String lpFile) { return helper.importFromMpsString(lpFile); } // Getters. /** Returns the model builder helper. */ public ModelBuilderHelper getHelper() { return helper; } private final ModelBuilderHelper helper; private final Map<Double, Integer> constantMap; }
8,112
31.067194
95
java
or-tools
or-tools-master/ortools/java/com/google/ortools/modelbuilder/ModelSolver.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.modelbuilder; import java.time.Duration; import java.util.function.Consumer; /** Model solver class */ public final class ModelSolver { static class ModelSolverException extends RuntimeException { public ModelSolverException(String methodName, String msg) { // Call constructor of parent Exception super(methodName + ": " + msg); } } /** Creates the solver with the supplied solver backend. */ public ModelSolver(String solverName) { this.helper = new ModelSolverHelper(solverName); this.logCallback = null; } /** Solves given model, and returns the status of the response. */ public SolveStatus solve(ModelBuilder model) { if (logCallback == null) { helper.clearLogCallback(); } else { helper.setLogCallback(logCallback); } helper.solve(model.getHelper()); if (!helper.hasResponse()) { return SolveStatus.UNKNOWN_STATUS; } return helper.getStatus(); } /** Enables or disables the underlying solver output. */ public void enableOutput(boolean enable) { helper.enableOutput(enable); } /** Sets the time limit for the solve in seconds. */ public void setTimeLimit(Duration limit) { helper.setTimeLimitInSeconds((double) limit.toMillis() / 1000.0); } /** Sets solver specific parameters as string. */ public void setSolverSpecificParameters(String parameters) { helper.setSolverSpecificParameters(parameters); } /** Returns whether solver specified during the ctor was found and correctly installed. */ public boolean solverIsSupported() { return helper.solverIsSupported(); } /** Tries to interrupt the solve. Returns true if the feature is supported. */ public boolean interruptSolve() { return helper.interruptSolve(); } /** Returns true if solve() was called, and a response was returned. */ public boolean hasResponse() { return helper.hasResponse(); } /** Returns true if solve() was called, and a solution was returned. */ public boolean hasSolution() { return helper.hasSolution(); } /** Checks that the solver has found a solution, and returns the objective value. */ public double getObjectiveValue() { if (!helper.hasSolution()) { throw new ModelSolverException( "ModelSolver.getObjectiveValue()", "solve() was not called or no solution was found"); } return helper.getObjectiveValue(); } /** Checks that the solver has found a solution, and returns the objective value. */ public double getBestObjectiveBound() { if (!helper.hasSolution()) { throw new ModelSolverException( "ModelSolver.getBestObjectiveBound()", "solve() was not called or no solution was found"); } return helper.getBestObjectiveBound(); } /** Checks that the solver has found a solution, and value of the given variable. */ public double getValue(Variable var) { if (!helper.hasSolution()) { throw new ModelSolverException( "ModelSolver.getValue())", "solve() was not called or no solution was found"); } return helper.getVariableValue(var.getIndex()); } /** Checks that the solver has found a solution, and reduced cost of the given variable. */ public double getReducedCost(Variable var) { if (!helper.hasSolution()) { throw new ModelSolverException( "ModelSolver.getReducedCost())", "solve() was not called or no solution was found"); } return helper.getReducedCost(var.getIndex()); } /** Checks that the solver has found a solution, and dual value of the given constraint. */ public double getDualValue(LinearConstraint ct) { if (!helper.hasSolution()) { throw new ModelSolverException( "ModelSolver.getDualValue())", "solve() was not called or no solution was found"); } return helper.getDualValue(ct.getIndex()); } /** Sets the log callback for the solver. */ public void setLogCallback(Consumer<String> cb) { this.logCallback = cb; } /** Returns the elapsed time since the creation of the solver. */ public double getWallTime() { return helper.getWallTime(); } /** Returns the user time since the creation of the solver. */ public double getUserTime() { return helper.getUserTime(); } private final ModelSolverHelper helper; private Consumer<String> logCallback; }
4,950
33.144828
100
java
or-tools
or-tools-master/ortools/java/com/google/ortools/modelbuilder/Variable.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.modelbuilder; /** An integer variable. */ public class Variable implements LinearArgument { Variable(ModelBuilderHelper helper, double lb, double ub, boolean isIntegral, String name) { this.helper = helper; this.index = helper.addVar(); this.helper.setVarName(index, name); this.helper.setVarIntegrality(index, isIntegral); this.helper.setVarLowerBound(index, lb); this.helper.setVarUpperBound(index, ub); } Variable(ModelBuilderHelper helper, int index) { this.helper = helper; this.index = index; } /** Returns the index of the variable in the underlying ModelBuilderHelper. */ public int getIndex() { return index; } // LinearArgument interface @Override public LinearExpr build() { return new AffineExpression(index, 1.0, 0.0); } /** Returns the lower bound of the variable. */ public double getLowerBound() { return helper.getVarLowerBound(index); } /** Sets the lower bound of the variable. */ public void setLowerBound(double lowerBound) { helper.setVarLowerBound(index, lowerBound); } /** Returns the upper bound of the variable. */ public double getUpperBound() { return helper.getVarUpperBound(index); } /** Sets the upper bound of the variable. */ public void setUpperBound(double upperBound) { helper.setVarUpperBound(index, upperBound); } /** Returns whether the variable is integral. */ public boolean getIntegrality() { return helper.getVarIntegrality(index); } /** Sets the integrality of the variable. */ public void setIntegrality(boolean isIntegral) { helper.setVarIntegrality(index, isIntegral); } /** Returns the objective coefficient of the variable. */ public double getObjectiveCoefficient() { return helper.getVarObjectiveCoefficient(index); } /** Sets the objective coefficient of the variable in the objective. */ public void setObjectiveCoefficient(double objectiveCoefficient) { helper.setVarObjectiveCoefficient(index, objectiveCoefficient); } /** Returns the name of the variable given upon creation. */ public String getName() { return helper.getVarName(index); } public void setName(String name) { helper.setVarName(index, name); } @Override public String toString() { if (getName().isEmpty()) { if (getLowerBound() == getUpperBound()) { return String.format("%f", getLowerBound()); } else { return String.format("var_%d(%f, %f)", getIndex(), getLowerBound(), getUpperBound()); } } else { return String.format("%s(%f, %f)", getName(), getLowerBound(), getUpperBound()); } } protected final ModelBuilderHelper helper; protected final int index; }
3,334
29.87963
94
java
or-tools
or-tools-master/ortools/java/com/google/ortools/modelbuilder/WeightedSumExpression.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.modelbuilder; /** A specialized linear expression: sum(ai * xi) + b. */ public final class WeightedSumExpression implements LinearExpr { private final int[] variablesIndices; private final double[] coefficients; private final double offset; public WeightedSumExpression(int[] variablesIndices, double[] coefficients, double offset) { this.variablesIndices = variablesIndices; this.coefficients = coefficients; this.offset = offset; } @Override public LinearExpr build() { return this; } @Override public int numElements() { return variablesIndices.length; } @Override public int getVariableIndex(int index) { if (index < 0 || index >= variablesIndices.length) { throw new IllegalArgumentException("wrong index in LinearExpr.getVariable(): " + index); } return variablesIndices[index]; } @Override public double getCoefficient(int index) { if (index < 0 || index >= variablesIndices.length) { throw new IllegalArgumentException("wrong index in LinearExpr.getCoefficient(): " + index); } return coefficients[index]; } @Override public double getOffset() { return offset; } }
1,797
29.474576
97
java
or-tools
or-tools-master/ortools/java/com/google/ortools/sat/AffineExpression.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.sat; /** A specialized linear expression: a * x + b */ public final class AffineExpression implements LinearExpr { private final int varIndex; private final long coefficient; private final long offset; public AffineExpression(int varIndex, long coefficient, long offset) { this.varIndex = varIndex; this.coefficient = coefficient; this.offset = offset; } // LinearArgument interface. @Override public LinearExpr build() { return this; } // LinearExpr interface. @Override public int numElements() { return 1; } @Override public int getVariableIndex(int index) { if (index != 0) { throw new IllegalArgumentException("wrong index in LinearExpr.getIndex(): " + index); } return varIndex; } @Override public long getCoefficient(int index) { if (index != 0) { throw new IllegalArgumentException("wrong index in LinearExpr.getCoefficient(): " + index); } return coefficient; } @Override public long getOffset() { return offset; } }
1,654
26.131148
97
java
or-tools
or-tools-master/ortools/java/com/google/ortools/sat/AutomatonConstraint.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.sat; import com.google.ortools.sat.CpModelProto; /** * Specialized automaton constraint. * * <p>This constraint allows adding transitions to the automaton constraint incrementally. */ public class AutomatonConstraint extends Constraint { public AutomatonConstraint(CpModelProto.Builder builder) { super(builder); } /// Adds a transitions to the automaton. AutomatonConstraint addTransition(int tail, int head, long label) { getBuilder() .getAutomatonBuilder() .addTransitionTail(tail) .addTransitionLabel(label) .addTransitionHead(head); return this; } }
1,233
31.473684
90
java
or-tools
or-tools-master/ortools/java/com/google/ortools/sat/BoolVar.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.sat; import com.google.ortools.sat.CpModelProto; import com.google.ortools.util.Domain; /** An Boolean variable. */ public final class BoolVar extends IntVar implements Literal { BoolVar(CpModelProto.Builder builder, Domain domain, String name) { super(builder, domain, name); this.negation = null; } BoolVar(CpModelProto.Builder builder, int index) { super(builder, index); this.negation = null; } /** Returns the negation of a boolean variable. */ @Override public Literal not() { if (negation == null) { negation = new NotBoolVar(this); } return negation; } @Override public String toString() { if (varBuilder.getName().isEmpty()) { if (varBuilder.getDomainCount() == 2 && varBuilder.getDomain(0) == varBuilder.getDomain(1)) { if (varBuilder.getDomain(0) == 0) { return "false"; } else { return "true"; } } else { return String.format("boolvar_%d(%s)", getIndex(), displayBounds()); } } else { if (varBuilder.getDomainCount() == 2 && varBuilder.getDomain(0) == varBuilder.getDomain(1)) { if (varBuilder.getDomain(0) == 0) { return String.format("%s(false)", varBuilder.getName()); } else { return String.format("%s(true)", varBuilder.getName()); } } else { return String.format("%s(%s)", getName(), displayBounds()); } } } private NotBoolVar negation = null; }
2,097
30.313433
99
java
or-tools
or-tools-master/ortools/java/com/google/ortools/sat/CircuitConstraint.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.sat; import com.google.ortools.sat.CircuitConstraintProto; import com.google.ortools.sat.CpModelProto; /** * Specialized circuit constraint. * * <p>This constraint allows adding arcs to the circuit constraint incrementally. */ public class CircuitConstraint extends Constraint { public CircuitConstraint(CpModelProto.Builder builder) { super(builder); } /** * Add an arc to the graph of the circuit constraint. * * @param tail the index of the tail node. * @param head the index of the head node. * @param literal it will be set to true if the arc is selected. */ public CircuitConstraint addArc(int tail, int head, Literal literal) { CircuitConstraintProto.Builder circuit = getBuilder().getCircuitBuilder(); circuit.addTails(tail); circuit.addHeads(head); circuit.addLiterals(literal.getIndex()); return this; } }
1,492
32.931818
81
java
or-tools
or-tools-master/ortools/java/com/google/ortools/sat/ConstantExpression.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.sat; /** A specialized constant linear expression. */ public final class ConstantExpression implements LinearExpr { private final long offset; public ConstantExpression(long offset) { this.offset = offset; } // LinearArgument interface. @Override public LinearExpr build() { return this; } // LinearExpr interface. @Override public int numElements() { return 0; } @Override public int getVariableIndex(int index) { throw new IllegalArgumentException("wrong index in LinearExpr.getVariable(): " + index); } @Override public long getCoefficient(int index) { throw new IllegalArgumentException("wrong index in LinearExpr.getCoefficient(): " + index); } @Override public long getOffset() { return offset; } @Override public String toString() { return String.format("%d", offset); } }
1,479
25.428571
95
java
or-tools
or-tools-master/ortools/java/com/google/ortools/sat/Constraint.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.sat; import com.google.ortools.sat.ConstraintProto; import com.google.ortools.sat.CpModelProto; /** * Wrapper around a ConstraintProto. * * <p>Constraints created by the CpModel class are automatically added to the model. One needs this * class to add an enforcement literal to a constraint. */ public class Constraint { public Constraint(CpModelProto.Builder builder) { this.constraintIndex = builder.getConstraintsCount(); this.constraintBuilder = builder.addConstraintsBuilder(); } /** Adds a literal to the constraint. */ public void onlyEnforceIf(Literal lit) { constraintBuilder.addEnforcementLiteral(lit.getIndex()); } /** Adds a list of literals to the constraint. */ public void onlyEnforceIf(Literal[] lits) { for (Literal lit : lits) { constraintBuilder.addEnforcementLiteral(lit.getIndex()); } } /** Returns the index of the constraint in the model. */ public int getIndex() { return constraintIndex; } /** Returns the constraint builder. */ public ConstraintProto.Builder getBuilder() { return constraintBuilder; } private final int constraintIndex; private final ConstraintProto.Builder constraintBuilder; }
1,817
31.464286
99
java
or-tools
or-tools-master/ortools/java/com/google/ortools/sat/CpModel.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.sat; import com.google.ortools.sat.AllDifferentConstraintProto; import com.google.ortools.sat.AutomatonConstraintProto; import com.google.ortools.sat.BoolArgumentProto; import com.google.ortools.sat.CpModelProto; import com.google.ortools.sat.CpObjectiveProto; import com.google.ortools.sat.CumulativeConstraintProto; import com.google.ortools.sat.DecisionStrategyProto; import com.google.ortools.sat.ElementConstraintProto; import com.google.ortools.sat.FloatObjectiveProto; import com.google.ortools.sat.InverseConstraintProto; import com.google.ortools.sat.LinearArgumentProto; import com.google.ortools.sat.LinearConstraintProto; import com.google.ortools.sat.LinearExpressionProto; import com.google.ortools.sat.NoOverlapConstraintProto; import com.google.ortools.sat.ReservoirConstraintProto; import com.google.ortools.sat.TableConstraintProto; import com.google.ortools.util.Domain; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.Map; /** * Main modeling class. * * <p>Proposes a factory to create all modeling objects understood by the SAT solver. */ public final class CpModel { static class CpModelException extends RuntimeException { public CpModelException(String methodName, String msg) { // Call constructor of parent Exception super(methodName + ": " + msg); } } /** Exception thrown when parallel arrays have mismatched lengths. */ public static class MismatchedArrayLengths extends CpModelException { public MismatchedArrayLengths(String methodName, String array1Name, String array2Name) { super(methodName, array1Name + " and " + array2Name + " have mismatched lengths"); } } /** Exception thrown when an array has a wrong length. */ public static class WrongLength extends CpModelException { public WrongLength(String methodName, String msg) { super(methodName, msg); } } public CpModel() { modelBuilder = CpModelProto.newBuilder(); constantMap = new LinkedHashMap<>(); } // Integer variables. /** Creates an integer variable with domain [lb, ub]. */ public IntVar newIntVar(long lb, long ub, String name) { return new IntVar(modelBuilder, new Domain(lb, ub), name); } /** * Creates an integer variable with given domain. * * @param domain an instance of the Domain class. * @param name the name of the variable * @return a variable with the given domain. */ public IntVar newIntVarFromDomain(Domain domain, String name) { return new IntVar(modelBuilder, domain, name); } /** Creates a Boolean variable with the given name. */ public BoolVar newBoolVar(String name) { return new BoolVar(modelBuilder, new Domain(0, 1), name); } /** Creates a constant variable. */ public IntVar newConstant(long value) { if (constantMap.containsKey(value)) { return new IntVar(modelBuilder, constantMap.get(value)); } IntVar cste = new IntVar(modelBuilder, new Domain(value), ""); // bounds and name. constantMap.put(value, cste.getIndex()); return cste; } /** Returns the true literal. */ public Literal trueLiteral() { if (constantMap.containsKey(1L)) { return new BoolVar(modelBuilder, constantMap.get(1L)); } BoolVar cste = new BoolVar(modelBuilder, new Domain(1), ""); // bounds and name. constantMap.put(1L, cste.getIndex()); return cste; } /** Returns the false literal. */ public Literal falseLiteral() { if (constantMap.containsKey(0L)) { return new BoolVar(modelBuilder, constantMap.get(0L)); } BoolVar cste = new BoolVar(modelBuilder, new Domain(0), ""); // bounds and name. constantMap.put(0L, cste.getIndex()); return cste; } // Boolean Constraints. /** Adds {@code Or(literals) == true}. */ public Constraint addBoolOr(Literal[] literals) { return addBoolOr(Arrays.asList(literals)); } /** Adds {@code Or(literals) == true}. */ public Constraint addBoolOr(Iterable<Literal> literals) { Constraint ct = new Constraint(modelBuilder); BoolArgumentProto.Builder boolOr = ct.getBuilder().getBoolOrBuilder(); for (Literal lit : literals) { boolOr.addLiterals(lit.getIndex()); } return ct; } /** Same as addBoolOr. {@code Sum(literals) >= 1}. */ public Constraint addAtLeastOne(Literal[] literals) { return addBoolOr(Arrays.asList(literals)); } /** Same as addBoolOr. {@code Sum(literals) >= 1}. */ public Constraint addAtLeastOne(Iterable<Literal> literals) { return addBoolOr(literals); } /** Adds {@code AtMostOne(literals): Sum(literals) <= 1}. */ public Constraint addAtMostOne(Literal[] literals) { return addAtMostOne(Arrays.asList(literals)); } /** Adds {@code AtMostOne(literals): Sum(literals) <= 1}. */ public Constraint addAtMostOne(Iterable<Literal> literals) { Constraint ct = new Constraint(modelBuilder); BoolArgumentProto.Builder atMostOne = ct.getBuilder().getAtMostOneBuilder(); for (Literal lit : literals) { atMostOne.addLiterals(lit.getIndex()); } return ct; } /** Adds {@code ExactlyOne(literals): Sum(literals) == 1}. */ public Constraint addExactlyOne(Literal[] literals) { return addExactlyOne(Arrays.asList(literals)); } /** Adds {@code ExactlyOne(literals): Sum(literals) == 1}. */ public Constraint addExactlyOne(Iterable<Literal> literals) { Constraint ct = new Constraint(modelBuilder); BoolArgumentProto.Builder exactlyOne = ct.getBuilder().getExactlyOneBuilder(); for (Literal lit : literals) { exactlyOne.addLiterals(lit.getIndex()); } return ct; } /** Adds {@code And(literals) == true}. */ public Constraint addBoolAnd(Literal[] literals) { return addBoolAnd(Arrays.asList(literals)); } /** Adds {@code And(literals) == true}. */ public Constraint addBoolAnd(Iterable<Literal> literals) { Constraint ct = new Constraint(modelBuilder); BoolArgumentProto.Builder boolAnd = ct.getBuilder().getBoolAndBuilder(); for (Literal lit : literals) { boolAnd.addLiterals(lit.getIndex()); } return ct; } /** Adds {@code XOr(literals) == true}. */ public Constraint addBoolXor(Literal[] literals) { return addBoolXor(Arrays.asList(literals)); } /** Adds {@code XOr(literals) == true}. */ public Constraint addBoolXor(Iterable<Literal> literals) { Constraint ct = new Constraint(modelBuilder); BoolArgumentProto.Builder boolXOr = ct.getBuilder().getBoolXorBuilder(); for (Literal lit : literals) { boolXOr.addLiterals(lit.getIndex()); } return ct; } /** Adds {@code a => b}. */ public Constraint addImplication(Literal a, Literal b) { return addBoolOr(new Literal[] {a.not(), b}); } // Linear constraints. /** Adds {@code expr in domain}. */ public Constraint addLinearExpressionInDomain(LinearArgument expr, Domain domain) { Constraint ct = new Constraint(modelBuilder); LinearConstraintProto.Builder lin = ct.getBuilder().getLinearBuilder(); final LinearExpr e = expr.build(); for (int i = 0; i < e.numElements(); ++i) { lin.addVars(e.getVariableIndex(i)).addCoeffs(e.getCoefficient(i)); } long offset = e.getOffset(); for (long b : domain.flattenedIntervals()) { if (b == Long.MIN_VALUE || b == Long.MAX_VALUE) { lin.addDomain(b); } else { lin.addDomain(b - offset); } } return ct; } /** Adds {@code lb <= expr <= ub}. */ public Constraint addLinearConstraint(LinearArgument expr, long lb, long ub) { return addLinearExpressionInDomain(expr, new Domain(lb, ub)); } /** Adds {@code expr == value}. */ public Constraint addEquality(LinearArgument expr, long value) { return addLinearExpressionInDomain(expr, new Domain(value)); } /** Adds {@code left == right}. */ public Constraint addEquality(LinearArgument left, LinearArgument right) { LinearExprBuilder difference = LinearExpr.newBuilder(); difference.addTerm(left, 1); difference.addTerm(right, -1); return addLinearExpressionInDomain(difference, new Domain(0)); } /** Adds {@code expr <= value}. */ public Constraint addLessOrEqual(LinearArgument expr, long value) { return addLinearExpressionInDomain(expr, new Domain(Long.MIN_VALUE, value)); } /** Adds {@code left <= right}. */ public Constraint addLessOrEqual(LinearArgument left, LinearArgument right) { LinearExprBuilder difference = LinearExpr.newBuilder(); difference.addTerm(left, 1); difference.addTerm(right, -1); return addLinearExpressionInDomain(difference, new Domain(Long.MIN_VALUE, 0)); } /** Adds {@code expr < value}. */ public Constraint addLessThan(LinearArgument expr, long value) { return addLinearExpressionInDomain(expr, new Domain(Long.MIN_VALUE, value - 1)); } /** Adds {@code left < right}. */ public Constraint addLessThan(LinearArgument left, LinearArgument right) { LinearExprBuilder difference = LinearExpr.newBuilder(); difference.addTerm(left, 1); difference.addTerm(right, -1); return addLinearExpressionInDomain(difference, new Domain(Long.MIN_VALUE, -1)); } /** Adds {@code expr >= value}. */ public Constraint addGreaterOrEqual(LinearArgument expr, long value) { return addLinearExpressionInDomain(expr, new Domain(value, Long.MAX_VALUE)); } /** Adds {@code left >= right}. */ public Constraint addGreaterOrEqual(LinearArgument left, LinearArgument right) { LinearExprBuilder difference = LinearExpr.newBuilder(); difference.addTerm(left, 1); difference.addTerm(right, -1); return addLinearExpressionInDomain(difference, new Domain(0, Long.MAX_VALUE)); } /** Adds {@code expr > value}. */ public Constraint addGreaterThan(LinearArgument expr, long value) { return addLinearExpressionInDomain(expr, new Domain(value + 1, Long.MAX_VALUE)); } /** Adds {@code left > right}. */ public Constraint addGreaterThan(LinearArgument left, LinearArgument right) { LinearExprBuilder difference = LinearExpr.newBuilder(); difference.addTerm(left, 1); difference.addTerm(right, -1); return addLinearExpressionInDomain(difference, new Domain(1, Long.MAX_VALUE)); } /** Adds {@code expr != value}. */ public Constraint addDifferent(LinearArgument expr, long value) { return addLinearExpressionInDomain(expr, Domain.fromFlatIntervals( new long[] {Long.MIN_VALUE, value - 1, value + 1, Long.MAX_VALUE})); } /** Adds {@code left != right}. */ public Constraint addDifferent(LinearArgument left, LinearArgument right) { LinearExprBuilder difference = LinearExpr.newBuilder(); difference.addTerm(left, 1); difference.addTerm(right, -1); return addLinearExpressionInDomain( difference, Domain.fromFlatIntervals(new long[] {Long.MIN_VALUE, -1, 1, Long.MAX_VALUE})); } // Integer constraints. /** * Adds {@code AllDifferent(expressions)}. * * <p>This constraint forces all affine expressions to have different values. * * @param expressions a list of affine integer expressions * @return an instance of the Constraint class */ public Constraint addAllDifferent(LinearArgument[] expressions) { return addAllDifferent(Arrays.asList(expressions)); } /** * Adds {@code AllDifferent(expressions)}. * * @see addAllDifferent(LinearArgument[]). */ public Constraint addAllDifferent(Iterable<? extends LinearArgument> expressions) { Constraint ct = new Constraint(modelBuilder); AllDifferentConstraintProto.Builder allDiff = ct.getBuilder().getAllDiffBuilder(); for (LinearArgument expr : expressions) { allDiff.addExprs(getLinearExpressionProtoBuilderFromLinearArgument(expr, /*negate=*/false)); } return ct; } /** Adds the element constraint: {@code variables[index] == target}. */ public Constraint addElement(IntVar index, IntVar[] variables, IntVar target) { Constraint ct = new Constraint(modelBuilder); ElementConstraintProto.Builder element = ct.getBuilder().getElementBuilder().setIndex(index.getIndex()); for (IntVar var : variables) { element.addVars(var.getIndex()); } element.setTarget(target.getIndex()); return ct; } /** Adds the element constraint: {@code values[index] == target}. */ public Constraint addElement(IntVar index, long[] values, IntVar target) { Constraint ct = new Constraint(modelBuilder); ElementConstraintProto.Builder element = ct.getBuilder().getElementBuilder().setIndex(index.getIndex()); for (long v : values) { element.addVars(newConstant(v).getIndex()); } element.setTarget(target.getIndex()); return ct; } /** Adds the element constraint: {@code values[index] == target}. */ public Constraint addElement(IntVar index, int[] values, IntVar target) { Constraint ct = new Constraint(modelBuilder); ElementConstraintProto.Builder element = ct.getBuilder().getElementBuilder().setIndex(index.getIndex()); for (long v : values) { element.addVars(newConstant(v).getIndex()); } element.setTarget(target.getIndex()); return ct; } /** * Adds {@code Circuit()}. * * <p>Adds an empty circuit constraint. * * <p>A circuit is a unique Hamiltonian path in a subgraph of the total graph. In case a node 'i' * is not in the path, then there must be a loop arc {@code 'i -> i'} associated with a true * literal. Otherwise this constraint will fail. */ public CircuitConstraint addCircuit() { return new CircuitConstraint(modelBuilder); } /** * Adds {@code MultipleCircuit()}. * * <p>Adds an empty multiple circuit constraint. * * <p>A multiple circuit is set of cycles in a subgraph of the total graph. The node index by 0 * must be part of all cycles of length > 1. Each node with index > 0 belongs to exactly one * cycle. If such node does not belong in any cycle of length > 1, then there must be a looping * arc on this node attached to a literal that will be true. Otherwise, the constraint will fail. */ public MultipleCircuitConstraint addMultipleCircuit() { return new MultipleCircuitConstraint(modelBuilder); } /** * Adds {@code AllowedAssignments(variables)}. * * <p>An AllowedAssignments constraint is a constraint on an array of variables that forces, when * all variables are fixed to a single value, that the corresponding list of values is equal to * one of the tuples of the tupleList. * * @param variables a list of variables * @return an instance of the TableConstraint class without any tuples. Tuples can be added * directly to the table constraint. */ public TableConstraint addAllowedAssignments(IntVar[] variables) { return addAllowedAssignments(Arrays.asList(variables)); } /** * Adds {@code AllowedAssignments(variables)}. * * @see addAllowedAssignments(IntVar[]) */ public TableConstraint addAllowedAssignments(Iterable<IntVar> variables) { TableConstraint ct = new TableConstraint(modelBuilder); TableConstraintProto.Builder table = ct.getBuilder().getTableBuilder(); for (IntVar var : variables) { table.addVars(var.getIndex()); } table.setNegated(false); return ct; } /** * Adds {@code ForbiddenAssignments(variables)}. * * <p>A ForbiddenAssignments constraint is a constraint on an array of variables where the list of * impossible combinations is provided in the tuples list. * * @param variables a list of variables * @return an instance of the TableConstraint class without any tuples. Tuples can be added * directly to the table constraint. */ public TableConstraint addForbiddenAssignments(IntVar[] variables) { return addForbiddenAssignments(Arrays.asList(variables)); } /** * Adds {@code ForbiddenAssignments(variables)}. * * @see addForbiddenAssignments(IntVar[]) */ public TableConstraint addForbiddenAssignments(Iterable<IntVar> variables) { TableConstraint ct = new TableConstraint(modelBuilder); TableConstraintProto.Builder table = ct.getBuilder().getTableBuilder(); for (IntVar var : variables) { table.addVars(var.getIndex()); } table.setNegated(true); return ct; } /** * Adds an automaton constraint. * * <p>An automaton constraint takes a list of variables (of size n), an initial state, a set of * final states, and a set of transitions that will be added incrementally directly on the * returned AutomatonConstraint instance. A transition is a triplet ('tail', 'transition', * 'head'), where 'tail' and 'head' are states, and 'transition' is the label of an arc from * 'head' to 'tail', corresponding to the value of one variable in the list of variables. * * <p>This automaton will be unrolled into a flow with n + 1 phases. Each phase contains the * possible states of the automaton. The first state contains the initial state. The last phase * contains the final states. * * <p>Between two consecutive phases i and i + 1, the automaton creates a set of arcs. For each * transition (tail, label, head), it will add an arc from the state 'tail' of phase i and the * state 'head' of phase i + 1. This arc labeled by the value 'label' of the variables * 'variables[i]'. That is, this arc can only be selected if 'variables[i]' is assigned the value * 'label'. * * <p>A feasible solution of this constraint is an assignment of variables such that, starting * from the initial state in phase 0, there is a path labeled by the values of the variables that * ends in one of the final states in the final phase. * * @param transitionVariables a non empty list of variables whose values correspond to the labels * of the arcs traversed by the automaton * @param startingState the initial state of the automaton * @param finalStates a non empty list of admissible final states * @return an instance of the Constraint class */ public AutomatonConstraint addAutomaton( IntVar[] transitionVariables, long startingState, long[] finalStates) { AutomatonConstraint ct = new AutomatonConstraint(modelBuilder); AutomatonConstraintProto.Builder automaton = ct.getBuilder().getAutomatonBuilder(); for (IntVar var : transitionVariables) { automaton.addVars(var.getIndex()); } automaton.setStartingState(startingState); for (long c : finalStates) { automaton.addFinalStates(c); } return ct; } /** * Adds {@code Inverse(variables, inverseVariables)}. * * <p>An inverse constraint enforces that if 'variables[i]' is assigned a value 'j', then * inverseVariables[j] is assigned a value 'i'. And vice versa. * * @param variables an array of integer variables * @param inverseVariables an array of integer variables * @return an instance of the Constraint class * @throws MismatchedArrayLengths if variables and inverseVariables have different length */ public Constraint addInverse(IntVar[] variables, IntVar[] inverseVariables) { if (variables.length != inverseVariables.length) { throw new MismatchedArrayLengths("CpModel.addInverse", "variables", "inverseVariables"); } Constraint ct = new Constraint(modelBuilder); InverseConstraintProto.Builder inverse = ct.getBuilder().getInverseBuilder(); for (IntVar var : variables) { inverse.addFDirect(var.getIndex()); } for (IntVar var : inverseVariables) { inverse.addFInverse(var.getIndex()); } return ct; } /** * Adds a reservoir constraint with optional refill/emptying events. * * <p>Maintain a reservoir level within bounds. The water level starts at 0, and at any time, it * must be within [min_level, max_level]. * * <p>Given an event (time, levelChange, active), if active is true, and if time is assigned a * value t, then the level of the reservoir changes by levelChange (which is constant) at time t. * Therefore, at any time t: * * <p>sum(levelChanges[i] * actives[i] if times[i] <= t) in [min_level, max_level] * * <p>Note that min level must be <= 0, and the max level must be >= 0. Please use fixed * level_changes to simulate an initial state. * * @param minLevel at any time, the level of the reservoir must be greater of equal than the min * level. minLevel must me <= 0. * @param maxLevel at any time, the level of the reservoir must be less or equal than the max * level. maxLevel must be >= 0. * @return an instance of the ReservoirConstraint class * @throws IllegalArgumentException if minLevel > 0 * @throws IllegalArgumentException if maxLevel < 0 */ public ReservoirConstraint addReservoirConstraint(long minLevel, long maxLevel) { if (minLevel > 0) { throw new IllegalArgumentException("CpModel.addReservoirConstraint: minLevel must be <= 0"); } if (maxLevel < 0) { throw new IllegalArgumentException("CpModel.addReservoirConstraint: maxLevel must be >= 0"); } ReservoirConstraint ct = new ReservoirConstraint(this); ReservoirConstraintProto.Builder reservoir = ct.getBuilder().getReservoirBuilder(); reservoir.setMinLevel(minLevel).setMaxLevel(maxLevel); return ct; } /** Adds {@code var == i + offset <=> booleans[i] == true for all i in [0, booleans.length)}. */ public void addMapDomain(IntVar var, Literal[] booleans, long offset) { for (int i = 0; i < booleans.length; ++i) { addEquality(var, offset + i).onlyEnforceIf(booleans[i]); addDifferent(var, offset + i).onlyEnforceIf(booleans[i].not()); } } /** Adds {@code target == Min(vars)}. */ public Constraint addMinEquality(LinearArgument target, LinearArgument[] exprs) { Constraint ct = new Constraint(modelBuilder); LinearArgumentProto.Builder linMax = ct.getBuilder().getLinMaxBuilder(); linMax.setTarget(getLinearExpressionProtoBuilderFromLinearArgument(target, /*negate=*/true)); for (LinearArgument expr : exprs) { linMax.addExprs(getLinearExpressionProtoBuilderFromLinearArgument(expr, /*negate=*/true)); } return ct; } /** Adds {@code target == Min(exprs)}. */ public Constraint addMinEquality( LinearArgument target, Iterable<? extends LinearArgument> exprs) { Constraint ct = new Constraint(modelBuilder); LinearArgumentProto.Builder linMax = ct.getBuilder().getLinMaxBuilder(); linMax.setTarget(getLinearExpressionProtoBuilderFromLinearArgument(target, /*negate=*/true)); for (LinearArgument expr : exprs) { linMax.addExprs(getLinearExpressionProtoBuilderFromLinearArgument(expr, /*negate=*/true)); } return ct; } /** Adds {@code target == Max(vars)}. */ public Constraint addMaxEquality(LinearArgument target, LinearArgument[] exprs) { Constraint ct = new Constraint(modelBuilder); LinearArgumentProto.Builder linMax = ct.getBuilder().getLinMaxBuilder(); linMax.setTarget(getLinearExpressionProtoBuilderFromLinearArgument(target, /*negate=*/false)); for (LinearArgument expr : exprs) { linMax.addExprs(getLinearExpressionProtoBuilderFromLinearArgument(expr, /*negate=*/false)); } return ct; } /** Adds {@code target == Max(exprs)}. */ public Constraint addMaxEquality( LinearArgument target, Iterable<? extends LinearArgument> exprs) { Constraint ct = new Constraint(modelBuilder); LinearArgumentProto.Builder linMax = ct.getBuilder().getLinMaxBuilder(); linMax.setTarget(getLinearExpressionProtoBuilderFromLinearArgument(target, /*negate=*/false)); for (LinearArgument expr : exprs) { linMax.addExprs(getLinearExpressionProtoBuilderFromLinearArgument(expr, /*negate=*/false)); } return ct; } /** Adds {@code target == num / denom}, rounded towards 0. */ public Constraint addDivisionEquality( LinearArgument target, LinearArgument num, LinearArgument denom) { Constraint ct = new Constraint(modelBuilder); ct.getBuilder() .getIntDivBuilder() .setTarget(getLinearExpressionProtoBuilderFromLinearArgument(target, /*negate=*/false)) .addExprs(getLinearExpressionProtoBuilderFromLinearArgument(num, /*negate=*/false)) .addExprs(getLinearExpressionProtoBuilderFromLinearArgument(denom, /*negate=*/false)); return ct; } /** Adds {@code target == Abs(expr)}. */ public Constraint addAbsEquality(LinearArgument target, LinearArgument expr) { Constraint ct = new Constraint(modelBuilder); LinearArgumentProto.Builder linMax = ct.getBuilder().getLinMaxBuilder(); linMax.setTarget(getLinearExpressionProtoBuilderFromLinearArgument(target, /*negate=*/false)); linMax.addExprs(getLinearExpressionProtoBuilderFromLinearArgument(expr, /*negate=*/false)); linMax.addExprs(getLinearExpressionProtoBuilderFromLinearArgument(expr, /*negate=*/true)); return ct; } /** Adds {@code target == var % mod}. */ public Constraint addModuloEquality( LinearArgument target, LinearArgument var, LinearArgument mod) { Constraint ct = new Constraint(modelBuilder); ct.getBuilder() .getIntModBuilder() .setTarget(getLinearExpressionProtoBuilderFromLinearArgument(target, /*negate=*/false)) .addExprs(getLinearExpressionProtoBuilderFromLinearArgument(var, /*negate=*/false)) .addExprs(getLinearExpressionProtoBuilderFromLinearArgument(mod, /*negate=*/false)); return ct; } /** Adds {@code target == var % mod}. */ public Constraint addModuloEquality(LinearArgument target, LinearArgument var, long mod) { Constraint ct = new Constraint(modelBuilder); ct.getBuilder() .getIntModBuilder() .setTarget(getLinearExpressionProtoBuilderFromLinearArgument(target, /*negate=*/false)) .addExprs(getLinearExpressionProtoBuilderFromLinearArgument(var, /*negate=*/false)) .addExprs(getLinearExpressionProtoBuilderFromLong(mod)); return ct; } /** Adds {@code target == Product(exprs)}. */ public Constraint addMultiplicationEquality(LinearArgument target, LinearArgument[] exprs) { Constraint ct = new Constraint(modelBuilder); LinearArgumentProto.Builder intProd = ct.getBuilder().getIntProdBuilder(); intProd.setTarget(getLinearExpressionProtoBuilderFromLinearArgument(target, /*negate=*/false)); for (LinearArgument expr : exprs) { intProd.addExprs(getLinearExpressionProtoBuilderFromLinearArgument(expr, /*negate=*/false)); } return ct; } /** Adds {@code target == left * right}. */ public Constraint addMultiplicationEquality( LinearArgument target, LinearArgument left, LinearArgument right) { Constraint ct = new Constraint(modelBuilder); LinearArgumentProto.Builder intProd = ct.getBuilder().getIntProdBuilder(); intProd.setTarget(getLinearExpressionProtoBuilderFromLinearArgument(target, /*negate=*/false)); intProd.addExprs(getLinearExpressionProtoBuilderFromLinearArgument(left, /*negate=*/false)); intProd.addExprs(getLinearExpressionProtoBuilderFromLinearArgument(right, /*negate=*/false)); return ct; } // Scheduling support. /** * Creates an interval variable from three affine expressions start, size, and end. * * <p>An interval variable is a constraint, that is itself used in other constraints like * NoOverlap. * * <p>Internally, it ensures that {@code start + size == end}. * * @param start the start of the interval. It needs to be an affine or constant expression. * @param size the size of the interval. It needs to be an affine or constant expression. * @param end the end of the interval. It needs to be an affine or constant expression. * @param name the name of the interval variable * @return An IntervalVar object */ public IntervalVar newIntervalVar( LinearArgument start, LinearArgument size, LinearArgument end, String name) { addEquality(LinearExpr.newBuilder().add(start).add(size), end); return new IntervalVar(modelBuilder, getLinearExpressionProtoBuilderFromLinearArgument(start, /*negate=*/false), getLinearExpressionProtoBuilderFromLinearArgument(size, /*negate=*/false), getLinearExpressionProtoBuilderFromLinearArgument(end, /*negate=*/false), name); } /** * Creates an interval variable from an affine expression start, and a fixed size. * * <p>An interval variable is a constraint, that is itself used in other constraints like * NoOverlap. * * @param start the start of the interval. It needs to be an affine or constant expression. * @param size the fixed size of the interval. * @param name the name of the interval variable. * @return An IntervalVar object */ public IntervalVar newFixedSizeIntervalVar(LinearArgument start, long size, String name) { return new IntervalVar(modelBuilder, getLinearExpressionProtoBuilderFromLinearArgument(start, /*negate=*/false), getLinearExpressionProtoBuilderFromLong(size), getLinearExpressionProtoBuilderFromLinearArgument( LinearExpr.newBuilder().add(start).add(size), /*negate=*/false), name); } /** Creates a fixed interval from its start and its size. */ public IntervalVar newFixedInterval(long start, long size, String name) { return new IntervalVar(modelBuilder, getLinearExpressionProtoBuilderFromLong(start), getLinearExpressionProtoBuilderFromLong(size), getLinearExpressionProtoBuilderFromLong(start + size), name); } /** * Creates an optional interval variable from three affine expressions start, size, end, and * isPresent. * * <p>An optional interval variable is a constraint, that is itself used in other constraints like * NoOverlap. This constraint is protected by an {@code isPresent} literal that indicates if it is * active or not. * * <p>Internally, it ensures that {@code isPresent => start + size == end}. * * @param start the start of the interval. It needs to be an affine or constant expression. * @param size the size of the interval. It needs to be an affine or constant expression. * @param end the end of the interval. It needs to be an affine or constant expression. * @param isPresent a literal that indicates if the interval is active or not. A inactive interval * is simply ignored by all constraints. * @param name The name of the interval variable * @return an IntervalVar object */ public IntervalVar newOptionalIntervalVar(LinearArgument start, LinearArgument size, LinearArgument end, Literal isPresent, String name) { addEquality(LinearExpr.newBuilder().add(start).add(size), end).onlyEnforceIf(isPresent); return new IntervalVar(modelBuilder, getLinearExpressionProtoBuilderFromLinearArgument(start, /*negate=*/false), getLinearExpressionProtoBuilderFromLinearArgument(size, /*negate=*/false), getLinearExpressionProtoBuilderFromLinearArgument(end, /*negate=*/false), isPresent.getIndex(), name); } /** * Creates an optional interval variable from an affine expression start, and a fixed size. * * <p>An interval variable is a constraint, that is itself used in other constraints like * NoOverlap. * * @param start the start of the interval. It needs to be an affine or constant expression. * @param size the fixed size of the interval. * @param isPresent a literal that indicates if the interval is active or not. A inactive interval * is simply ignored by all constraints. * @param name the name of the interval variable. * @return An IntervalVar object */ public IntervalVar newOptionalFixedSizeIntervalVar( LinearArgument start, long size, Literal isPresent, String name) { return new IntervalVar(modelBuilder, getLinearExpressionProtoBuilderFromLinearArgument(start, /*negate=*/false), getLinearExpressionProtoBuilderFromLong(size), getLinearExpressionProtoBuilderFromLinearArgument( LinearExpr.newBuilder().add(start).add(size), /*negate=*/false), isPresent.getIndex(), name); } /** Creates an optional fixed interval from start and size, and an isPresent literal. */ public IntervalVar newOptionalFixedInterval( long start, long size, Literal isPresent, String name) { return new IntervalVar(modelBuilder, getLinearExpressionProtoBuilderFromLong(start), getLinearExpressionProtoBuilderFromLong(size), getLinearExpressionProtoBuilderFromLong(start + size), isPresent.getIndex(), name); } /** * Adds {@code NoOverlap(intervalVars)}. * * <p>A NoOverlap constraint ensures that all present intervals do not overlap in time. * * @param intervalVars the list of interval variables to constrain * @return an instance of the Constraint class */ public Constraint addNoOverlap(IntervalVar[] intervalVars) { return addNoOverlap(Arrays.asList(intervalVars)); } /** * Adds {@code NoOverlap(intervalVars)}. * * @see addNoOverlap(IntervalVar[]). */ public Constraint addNoOverlap(Iterable<IntervalVar> intervalVars) { Constraint ct = new Constraint(modelBuilder); NoOverlapConstraintProto.Builder noOverlap = ct.getBuilder().getNoOverlapBuilder(); for (IntervalVar var : intervalVars) { noOverlap.addIntervals(var.getIndex()); } return ct; } /** * Adds {@code NoOverlap2D(xIntervals, yIntervals)}. * * <p>A NoOverlap2D constraint ensures that all present rectangles do not overlap on a plan. Each * rectangle is aligned with the X and Y axis, and is defined by two intervals which represent its * projection onto the X and Y axis. * * <p>Furthermore, one box is optional if at least one of the x or y interval is optional. * * @return an instance of the NoOverlap2dConstraint class. This class allows adding rectangles * incrementally. */ public NoOverlap2dConstraint addNoOverlap2D() { return new NoOverlap2dConstraint(modelBuilder); } /** * Adds {@code Cumulative(capacity)}. * * <p>This constraint enforces that: * * <p>{@code forall t: sum(demands[i] if (start(intervals[t]) <= t < end(intervals[t])) and (t is * present)) <= capacity}. * * @param capacity the maximum capacity of the cumulative constraint. It must be a positive affine * expression. * @return an instance of the CumulativeConstraint class. this class allows adding (interval, * demand) pairs incrementally. */ public CumulativeConstraint addCumulative(LinearArgument capacity) { CumulativeConstraint ct = new CumulativeConstraint(this); CumulativeConstraintProto.Builder cumul = ct.getBuilder().getCumulativeBuilder(); cumul.setCapacity(getLinearExpressionProtoBuilderFromLinearArgument(capacity, false)); return ct; } /** * Adds {@code Cumulative(capacity)}. * * @see #addCumulative(LinearArgument capacity) */ public CumulativeConstraint addCumulative(long capacity) { CumulativeConstraint ct = new CumulativeConstraint(this); CumulativeConstraintProto.Builder cumul = ct.getBuilder().getCumulativeBuilder(); cumul.setCapacity(getLinearExpressionProtoBuilderFromLong(capacity)); return ct; } /** Adds hinting to a variable */ public void addHint(IntVar var, long value) { modelBuilder.getSolutionHintBuilder().addVars(var.getIndex()); modelBuilder.getSolutionHintBuilder().addValues(value); } /** Remove all solution hints */ public void clearHints() { modelBuilder.clearSolutionHint(); } /** Adds a literal to the model as assumption */ public void addAssumption(Literal lit) { modelBuilder.addAssumptions(lit.getIndex()); } /** Adds multiple literals to the model as assumptions */ public void addAssumptions(Literal[] literals) { for (Literal lit : literals) { addAssumption(lit); } } /** Remove all assumptions from the model */ public void clearAssumptions() { modelBuilder.clearAssumptions(); } // Objective. /** Adds a minimization objective of a linear expression. */ public void minimize(LinearArgument expr) { clearObjective(); CpObjectiveProto.Builder obj = modelBuilder.getObjectiveBuilder(); final LinearExpr e = expr.build(); for (int i = 0; i < e.numElements(); ++i) { obj.addVars(e.getVariableIndex(i)).addCoeffs(e.getCoefficient(i)); } obj.setOffset((double) e.getOffset()); } /** Adds a minimization objective of a linear expression. */ public void minimize(DoubleLinearExpr expr) { clearObjective(); FloatObjectiveProto.Builder obj = modelBuilder.getFloatingPointObjectiveBuilder(); for (int i = 0; i < expr.numElements(); ++i) { obj.addVars(expr.getVariableIndex(i)).addCoeffs(expr.getCoefficient(i)); } obj.setOffset(expr.getOffset()).setMaximize(false); } /** Adds a maximization objective of a linear expression. */ public void maximize(LinearArgument expr) { clearObjective(); CpObjectiveProto.Builder obj = modelBuilder.getObjectiveBuilder(); final LinearExpr e = expr.build(); for (int i = 0; i < e.numElements(); ++i) { obj.addVars(e.getVariableIndex(i)).addCoeffs(-e.getCoefficient(i)); } obj.setOffset((double) -e.getOffset()); obj.setScalingFactor(-1.0); } /** Adds a maximization objective of a linear expression. */ public void maximize(DoubleLinearExpr expr) { clearObjective(); FloatObjectiveProto.Builder obj = modelBuilder.getFloatingPointObjectiveBuilder(); for (int i = 0; i < expr.numElements(); ++i) { obj.addVars(expr.getVariableIndex(i)).addCoeffs(expr.getCoefficient(i)); } obj.setOffset(expr.getOffset()).setMaximize(true); } /** Clears the objective. */ public void clearObjective() { modelBuilder.clearObjective(); modelBuilder.clearFloatingPointObjective(); } /** Checks if the model contains an objective. */ public boolean hasObjective() { return modelBuilder.hasObjective() || modelBuilder.hasFloatingPointObjective(); } // DecisionStrategy /** Adds {@code DecisionStrategy(variables, varStr, domStr)}. */ public void addDecisionStrategy(IntVar[] variables, DecisionStrategyProto.VariableSelectionStrategy varStr, DecisionStrategyProto.DomainReductionStrategy domStr) { DecisionStrategyProto.Builder ds = modelBuilder.addSearchStrategyBuilder(); for (IntVar var : variables) { ds.addVariables(var.getIndex()); } ds.setVariableSelectionStrategy(varStr).setDomainReductionStrategy(domStr); } /** Returns some statistics on model as a string. */ public String modelStats() { return CpSatHelper.modelStats(model()); } /** Returns a non empty string explaining the issue if the model is invalid. */ public String validate() { return CpSatHelper.validateModel(model()); } /** * Write the model as a protocol buffer to 'file'. * * @param file file to write the model to. If the filename ends with 'txt', the * model will be written as a text file, otherwise, the binary format will be used. * * @return true if the model was correctly written. */ public Boolean exportToFile(String file) { return CpSatHelper.writeModelToFile(model(), file); } // Helpers LinearExpressionProto.Builder getLinearExpressionProtoBuilderFromLinearArgument( LinearArgument arg, boolean negate) { LinearExpressionProto.Builder builder = LinearExpressionProto.newBuilder(); final LinearExpr expr = arg.build(); final int numVariables = expr.numElements(); final long mult = negate ? -1 : 1; for (int i = 0; i < numVariables; ++i) { builder.addVars(expr.getVariableIndex(i)); builder.addCoeffs(expr.getCoefficient(i) * mult); } builder.setOffset(expr.getOffset() * mult); return builder; } LinearExpressionProto.Builder getLinearExpressionProtoBuilderFromLong(long value) { LinearExpressionProto.Builder builder = LinearExpressionProto.newBuilder(); builder.setOffset(value); return builder; } // Getters. public CpModelProto model() { return modelBuilder.build(); } public int negated(int index) { return -index - 1; } /** Returns the model builder. */ public CpModelProto.Builder getBuilder() { return modelBuilder; } private final CpModelProto.Builder modelBuilder; private final Map<Long, Integer> constantMap; }
41,098
38.518269
100
java
or-tools
or-tools-master/ortools/java/com/google/ortools/sat/CpSolver.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.sat; import com.google.ortools.sat.CpSolverResponse; import com.google.ortools.sat.CpSolverStatus; import com.google.ortools.sat.SatParameters; import java.util.List; import java.util.function.Consumer; /** * Wrapper around the SAT solver. * * <p>This class proposes different solve() methods, as well as accessors to get the values of * variables in the best solution, as well as general statistics of the search. */ public final class CpSolver { /** Main construction of the CpSolver class. */ public CpSolver() { this.solveParameters = SatParameters.newBuilder(); this.logCallback = null; this.solveWrapper = null; } /** Solves the given model, and returns the solve status. */ public CpSolverStatus solve(CpModel model) { return solveWithSolutionCallback(model, null); } /** * Solves the given model, calls the solution callback at each incumbent solution, and returns the * solve status. */ public CpSolverStatus solve(CpModel model, CpSolverSolutionCallback cb) { // Setup search. createSolveWrapper(); // Synchronized. solveWrapper.setParameters(solveParameters.build()); if (cb != null) { solveWrapper.addSolutionCallback(cb); } if (logCallback != null) { solveWrapper.addLogCallback(logCallback); } solveResponse = solveWrapper.solve(model.model()); // Cleanup search. if (cb != null) { solveWrapper.clearSolutionCallback(cb); } releaseSolveWrapper(); // Synchronized. return solveResponse.getStatus(); } /** * Solves the given model, passes each incumber solution to the solution callback if not null, and * returns the solve status. * * @deprecated Use the solve() method with the same signature. */ @Deprecated public CpSolverStatus solveWithSolutionCallback(CpModel model, CpSolverSolutionCallback cb) { return solve(model, cb); } /** * Searches for all solutions of a satisfiability problem. * * <p>This method searches for all feasible solutions of a given model. Then it feeds the * solutions to the callback. * * <p>Note that the model cannot have an objective. * * @param model the model to solve * @param cb the callback that will be called at each solution * @return the status of the solve (FEASIBLE, INFEASIBLE...) * @deprecated Use the solve() method with the same signature, after setting the * enumerate_all_solution parameter to true. */ @Deprecated public CpSolverStatus searchAllSolutions(CpModel model, CpSolverSolutionCallback cb) { boolean oldValue = solveParameters.getEnumerateAllSolutions(); solveParameters.setEnumerateAllSolutions(true); solve(model, cb); solveParameters.setEnumerateAllSolutions(oldValue); return solveResponse.getStatus(); } private synchronized void createSolveWrapper() { solveWrapper = new SolveWrapper(); } private synchronized void releaseSolveWrapper() { solveWrapper = null; } /** Stops the search asynchronously. */ public synchronized void stopSearch() { if (solveWrapper != null) { solveWrapper.stopSearch(); } } /** Returns the best objective value found during search. */ public double objectiveValue() { return solveResponse.getObjectiveValue(); } /** * Returns the best lower bound found when minimizing, of the best upper bound found when * maximizing. */ public double bestObjectiveBound() { return solveResponse.getBestObjectiveBound(); } /** Returns the value of a linear expression in the last solution found. */ public long value(LinearArgument expr) { final LinearExpr e = expr.build(); long result = e.getOffset(); for (int i = 0; i < e.numElements(); ++i) { result += solveResponse.getSolution(e.getVariableIndex(i)) * e.getCoefficient(i); } return result; } /** Returns the Boolean value of a literal in the last solution found. */ public Boolean booleanValue(Literal var) { int index = var.getIndex(); if (index >= 0) { return solveResponse.getSolution(index) != 0; } else { return solveResponse.getSolution(-index - 1) == 0; } } /** Returns the internal response protobuf that is returned internally by the SAT solver. */ public CpSolverResponse response() { return solveResponse; } /** Returns the number of branches explored during search. */ public long numBranches() { return solveResponse.getNumBranches(); } /** Returns the number of conflicts created during search. */ public long numConflicts() { return solveResponse.getNumConflicts(); } /** Returns the wall time of the search. */ public double wallTime() { return solveResponse.getWallTime(); } /** Returns the user time of the search. */ public double userTime() { return solveResponse.getUserTime(); } public List<Integer> sufficientAssumptionsForInfeasibility() { return solveResponse.getSufficientAssumptionsForInfeasibilityList(); } /** Returns the builder of the parameters of the SAT solver for modification. */ public SatParameters.Builder getParameters() { return solveParameters; } /** Sets the log callback for the solver. */ public void setLogCallback(Consumer<String> cb) { this.logCallback = cb; } /** Returns some statistics on the solution found as a string. */ public String responseStats() { return CpSatHelper.solverResponseStats(solveResponse); } /** * Returns some information on how the solution was found, or the reason why the model or the * parameters are invalid. */ public String getSolutionInfo() { return solveResponse.getSolutionInfo(); } private CpSolverResponse solveResponse; private final SatParameters.Builder solveParameters; private Consumer<String> logCallback; private SolveWrapper solveWrapper; }
6,485
30.485437
100
java
or-tools
or-tools-master/ortools/java/com/google/ortools/sat/CpSolverSolutionCallback.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.sat; /** * Parent class to create a callback called at each solution. * * <p>From the parent class, it inherits the methods: * * <p>{@code long numBooleans()} to query the number of boolean variables created. * * <p>{@code long numBranches()} to query the number of branches explored so far. * * <p>{@code long numConflicts()} to query the number of conflicts created so far. * * <p>{@code long numBinaryPropagations()} to query the number of boolean propagations in the SAT * solver so far. * * <p>{@code long numIntegerPropagations()} to query the number of integer propagations in the SAT * solver so far. * * <p>{@code double wallTime()} to query wall time passed in the search so far. * * <p>{@code double userTime()} to query the user time passed in the search so far. * * <p>{@code long objectiveValue()} to get the best objective value found so far. */ public class CpSolverSolutionCallback extends SolutionCallback { /** Returns the value of the linear expression in the current solution. */ public long value(LinearArgument expr) { final LinearExpr e = expr.build(); long result = e.getOffset(); for (int i = 0; i < e.numElements(); ++i) { result += solutionIntegerValue(e.getVariableIndex(i)) * e.getCoefficient(i); } return result; } /** Returns the Boolean value of the literal in the current solution. */ public Boolean booleanValue(Literal literal) { return solutionBooleanValue(literal.getIndex()); } /** Callback method to override. It will be called at each new solution. */ @Override public void onSolutionCallback() {} }
2,231
36.830508
98
java
or-tools
or-tools-master/ortools/java/com/google/ortools/sat/CumulativeConstraint.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.sat; import com.google.ortools.sat.CumulativeConstraintProto; /** * Specialized cumulative constraint. * * <p>This constraint allows adding (interval, demand) pairs to the cumulative constraint * incrementally. */ public class CumulativeConstraint extends Constraint { public CumulativeConstraint(CpModel model) { super(model.getBuilder()); this.model = model; } /// Adds a pair (interval, demand) to the constraint. public CumulativeConstraint addDemand(IntervalVar interval, LinearArgument demand) { CumulativeConstraintProto.Builder cumul = getBuilder().getCumulativeBuilder(); cumul.addIntervals(interval.getIndex()); cumul.addDemands(model.getLinearExpressionProtoBuilderFromLinearArgument(demand, false)); return this; } /// Adds a pair (interval, demand) to the constraint. public CumulativeConstraint addDemand(IntervalVar interval, long demand) { CumulativeConstraintProto.Builder cumul = getBuilder().getCumulativeBuilder(); cumul.addIntervals(interval.getIndex()); cumul.addDemands(model.getLinearExpressionProtoBuilderFromLong(demand)); return this; } /** * Adds all pairs (intervals[i], demands[i]) to the constraint. * * @param intervals an array of interval variables * @param deamds an array of linear expression * @return itself * @throws CpModel.MismatchedArrayLengths if intervals and demands have different length */ public CumulativeConstraint addDemands(IntervalVar[] intervals, LinearArgument[] demands) { if (intervals.length != demands.length) { throw new CpModel.MismatchedArrayLengths( "CumulativeConstraint.addDemands", "intervals", "demands"); } for (int i = 0; i < intervals.length; i++) { addDemand(intervals[i], demands[i]); } return this; } /** * Adds all pairs (intervals[i], demands[i]) to the constraint. * * @param intervals an array of interval variables * @param deamds an array of long values * @return itself * @throws CpModel.MismatchedArrayLengths if intervals and demands have different length */ public CumulativeConstraint addDemands(IntervalVar[] intervals, long[] demands) { if (intervals.length != demands.length) { throw new CpModel.MismatchedArrayLengths( "CumulativeConstraint.addDemands", "intervals", "demands"); } for (int i = 0; i < intervals.length; i++) { addDemand(intervals[i], demands[i]); } return this; } /** * Adds all pairs (intervals[i], demands[i]) to the constraint. * * @param intervals an array of interval variables * @param deamds an array of integer values * @return itself * @throws CpModel.MismatchedArrayLengths if intervals and demands have different length */ public CumulativeConstraint addDemands(IntervalVar[] intervals, int[] demands) { if (intervals.length != demands.length) { throw new CpModel.MismatchedArrayLengths( "CumulativeConstraint.addDemands", "intervals", "demands"); } for (int i = 0; i < intervals.length; i++) { addDemand(intervals[i], demands[i]); } return this; } private final CpModel model; }
3,790
35.104762
93
java
or-tools
or-tools-master/ortools/java/com/google/ortools/sat/DoubleLinearExpr.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.sat; /** A linear expression interface that can be parsed. */ public class DoubleLinearExpr { private final int[] variableIndices; private final double[] coefficients; private double offset; /** Creates a sum expression. */ static DoubleLinearExpr sum(IntVar[] variables) { return sumWithOffset(variables, 0.0); } /** Creates a sum expression. */ static DoubleLinearExpr sum(Literal[] literals) { // We need the scalar product for the negative coefficient of negated Boolean variables. return sumWithOffset(literals, 0.0); } /** Creates a sum expression with a double offset. */ static DoubleLinearExpr sumWithOffset(IntVar[] variables, double offset) { return new DoubleLinearExpr(variables, offset); } /** Creates a sum expression with a double offset. */ static DoubleLinearExpr sumWithOffset(Literal[] literals, double offset) { // We need the scalar product for the negative coefficient of negated Boolean variables. return new DoubleLinearExpr(literals, offset); } /** Creates a scalar product. */ static DoubleLinearExpr weightedSum(IntVar[] variables, double[] coefficients) { return weightedSumWithOffset(variables, coefficients, 0.0); } /** Creates a scalar product. */ static DoubleLinearExpr weightedSum(Literal[] literals, double[] coefficients) { return weightedSumWithOffset(literals, coefficients, 0.0); } /** Creates a scalar product. */ static DoubleLinearExpr weightedSumWithOffset( IntVar[] variables, double[] coefficients, double offset) { if (variables.length != coefficients.length) { throw new CpModel.MismatchedArrayLengths( "DoubleLinearExpr.weightedSum", "variables", "coefficients"); } return new DoubleLinearExpr(variables, coefficients, offset); } /** Creates a scalar product with a double offset. */ static DoubleLinearExpr weightedSumWithOffset( Literal[] literals, double[] coefficients, double offset) { if (literals.length != coefficients.length) { throw new CpModel.MismatchedArrayLengths( "DoubleLinearExpr.weightedSum", "literals", "coefficients"); } return new DoubleLinearExpr(literals, coefficients, offset); } /** Creates a linear term (var * coefficient). */ static DoubleLinearExpr term(IntVar variable, double coefficient) { return new DoubleLinearExpr(variable, coefficient, 0.0); } /** Creates a linear term (lit * coefficient). */ static DoubleLinearExpr term(Literal lit, double coefficient) { return new DoubleLinearExpr(lit, coefficient, 0.0); } /** Creates an affine expression (var * coefficient + offset). */ static DoubleLinearExpr affine(IntVar variable, double coefficient, double offset) { return new DoubleLinearExpr(variable, coefficient, offset); } /** Creates an affine expression (lit * coefficient + offset). */ static DoubleLinearExpr affine(Literal lit, double coefficient, double offset) { return new DoubleLinearExpr(lit, coefficient, offset); } /** Creates an constant expression. */ static DoubleLinearExpr constant(double value) { return new DoubleLinearExpr(new IntVar[0], value); } /** Returns the number of elements in the interface. */ public int numElements() { return variableIndices.length; } /** Returns the ith variable. */ public int getVariableIndex(int index) { if (index < 0 || index >= variableIndices.length) { throw new IllegalArgumentException("wrong index in LinearExpr.getVariable(): " + index); } return variableIndices[index]; } /** Returns the ith coefficient. */ public double getCoefficient(int index) { if (index < 0 || index >= variableIndices.length) { throw new IllegalArgumentException("wrong index in LinearExpr.getCoefficient(): " + index); } return coefficients[index]; } /** Returns the constant part of the expression. */ public double getOffset() { return offset; } public DoubleLinearExpr(IntVar[] variables, double[] coefficients, double offset) { this.variableIndices = new int[variables.length]; for (int i = 0; i < variables.length; ++i) { this.variableIndices[i] = variables[i].getIndex(); } this.coefficients = coefficients; this.offset = offset; } public DoubleLinearExpr(Literal[] literals, double[] coefficients, double offset) { int size = literals.length; this.variableIndices = new int[size]; this.coefficients = new double[size]; this.offset = offset; for (int i = 0; i < size; ++i) { Literal lit = literals[i]; double coeff = coefficients[i]; if (lit.getIndex() >= 0) { this.variableIndices[i] = lit.getIndex(); this.coefficients[i] = coeff; } else { this.variableIndices[i] = lit.not().getIndex(); this.coefficients[i] = -coeff; this.offset -= coeff; } } } public DoubleLinearExpr(IntVar var, double coefficient, double offset) { this.variableIndices = new int[] {var.getIndex()}; this.coefficients = new double[] {coefficient}; this.offset = offset; } public DoubleLinearExpr(Literal lit, double coefficient, double offset) { if (lit.getIndex() >= 0) { this.variableIndices = new int[] {lit.getIndex()}; this.coefficients = new double[] {coefficient}; this.offset = offset; } else { this.variableIndices = new int[] {lit.not().getIndex()}; this.coefficients = new double[] {-coefficient}; this.offset = offset + coefficient; } } public DoubleLinearExpr(IntVar[] vars, double offset) { int size = vars.length; this.variableIndices = new int[size]; this.coefficients = new double[size]; this.offset = offset; for (int i = 0; i < size; ++i) { this.variableIndices[i] = vars[i].getIndex(); this.coefficients[i] = 1; } } public DoubleLinearExpr(Literal[] literals, double offset) { int size = literals.length; this.variableIndices = new int[size]; this.coefficients = new double[size]; this.offset = offset; for (int i = 0; i < size; ++i) { Literal lit = literals[i]; if (lit.getIndex() >= 0) { this.variableIndices[i] = lit.getIndex(); this.coefficients[i] = 1; } else { // NotBoolVar. this.variableIndices[i] = lit.not().getIndex(); this.coefficients[i] = -1.0; this.offset -= 1.0; } } } }
7,056
33.763547
97
java
or-tools
or-tools-master/ortools/java/com/google/ortools/sat/IntVar.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.sat; import com.google.ortools.sat.CpModelProto; import com.google.ortools.sat.IntegerVariableProto; import com.google.ortools.util.Domain; /** An integer variable. */ public class IntVar implements LinearArgument { IntVar(CpModelProto.Builder builder, Domain domain, String name) { this.modelBuilder = builder; this.variableIndex = modelBuilder.getVariablesCount(); this.varBuilder = modelBuilder.addVariablesBuilder(); this.varBuilder.setName(name); for (long b : domain.flattenedIntervals()) { this.varBuilder.addDomain(b); } } IntVar(CpModelProto.Builder builder, int index) { this.modelBuilder = builder; this.variableIndex = index; this.varBuilder = modelBuilder.getVariablesBuilder(index); } /** Returns the name of the variable given upon creation. */ public String getName() { return varBuilder.getName(); } /** Returns the index of the variable in the underlying CpModelProto. */ public int getIndex() { return variableIndex; } /** Returns the variable protobuf builder. */ public IntegerVariableProto.Builder getBuilder() { return varBuilder; } // LinearArgument interface @Override public LinearExpr build() { return new AffineExpression(variableIndex, 1, 0); } /** Returns the domain as a string without the enclosing []. */ public String displayBounds() { String out = ""; for (int i = 0; i < varBuilder.getDomainCount(); i += 2) { if (i != 0) { out += ", "; } if (varBuilder.getDomain(i) == varBuilder.getDomain(i + 1)) { out += String.format("%d", varBuilder.getDomain(i)); } else { out += String.format("%d..%d", varBuilder.getDomain(i), varBuilder.getDomain(i + 1)); } } return out; } /** Returns the domain of the variable. */ public Domain getDomain() { return CpSatHelper.variableDomain(varBuilder.build()); } @Override public String toString() { if (varBuilder.getName().isEmpty()) { if (varBuilder.getDomainCount() == 2 && varBuilder.getDomain(0) == varBuilder.getDomain(1)) { return String.format("%d", varBuilder.getDomain(0)); } else { return String.format("var_%d(%s)", getIndex(), displayBounds()); } } else { return String.format("%s(%s)", getName(), displayBounds()); } } protected final CpModelProto.Builder modelBuilder; protected final int variableIndex; protected final IntegerVariableProto.Builder varBuilder; }
3,117
31.14433
99
java
or-tools
or-tools-master/ortools/java/com/google/ortools/sat/IntervalVar.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.sat; import com.google.ortools.sat.ConstraintProto; import com.google.ortools.sat.CpModelProto; import com.google.ortools.sat.IntervalConstraintProto; import com.google.ortools.sat.LinearExpressionProto; /** An interval variable. This class must be constructed from the CpModel class. */ public final class IntervalVar { IntervalVar(CpModelProto.Builder builder, LinearExpressionProto.Builder startBuilder, LinearExpressionProto.Builder sizeBuilder, LinearExpressionProto.Builder endBuilder, String name) { this.modelBuilder = builder; this.constraintIndex = modelBuilder.getConstraintsCount(); ConstraintProto.Builder ct = modelBuilder.addConstraintsBuilder(); ct.setName(name); this.intervalBuilder = ct.getIntervalBuilder(); this.intervalBuilder.setStart(startBuilder); this.intervalBuilder.setSize(sizeBuilder); this.intervalBuilder.setEnd(endBuilder); } IntervalVar(CpModelProto.Builder builder, LinearExpressionProto.Builder startBuilder, LinearExpressionProto.Builder sizeBuilder, LinearExpressionProto.Builder endBuilder, int isPresentIndex, String name) { this.modelBuilder = builder; this.constraintIndex = modelBuilder.getConstraintsCount(); ConstraintProto.Builder ct = modelBuilder.addConstraintsBuilder(); ct.setName(name); ct.addEnforcementLiteral(isPresentIndex); this.intervalBuilder = ct.getIntervalBuilder(); this.intervalBuilder.setStart(startBuilder); this.intervalBuilder.setSize(sizeBuilder); this.intervalBuilder.setEnd(endBuilder); } @Override public String toString() { return modelBuilder.getConstraints(constraintIndex).toString(); } /** Returns the index of the interval constraint in the model. */ public int getIndex() { return constraintIndex; } /** Returns the interval builder. */ public IntervalConstraintProto.Builder getBuilder() { return intervalBuilder; } /** Returns the name passed in the constructor. */ public String getName() { return modelBuilder.getConstraints(constraintIndex).getName(); } /** Returns the start expression. */ public LinearExpr getStartExpr() { return LinearExpr.rebuildFromLinearExpressionProto(intervalBuilder.getStart()); } /** Returns the size expression. */ public LinearExpr getSizeExpr() { return LinearExpr.rebuildFromLinearExpressionProto(intervalBuilder.getSize()); } /** Returns the end expression. */ public LinearExpr getEndExpr() { return LinearExpr.rebuildFromLinearExpressionProto(intervalBuilder.getEnd()); } private final CpModelProto.Builder modelBuilder; private final int constraintIndex; private final IntervalConstraintProto.Builder intervalBuilder; }
3,343
36.573034
90
java
or-tools
or-tools-master/ortools/java/com/google/ortools/sat/LinearArgument.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.sat; /** * A object that can build a LinearExpr object. * * <p>This class is used in all modeling methods of the CpModel class. */ public interface LinearArgument { /** Builds a linear expression. */ LinearExpr build(); }
848
32.96
75
java
or-tools
or-tools-master/ortools/java/com/google/ortools/sat/LinearExpr.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.sat; import com.google.ortools.sat.LinearExpressionProto; /** A linear expression (sum (ai * xi) + b). It specifies methods to help parsing the expression. */ public interface LinearExpr extends LinearArgument { /** Returns the number of terms (excluding the constant one) in this expression. */ int numElements(); /** Returns the index of the ith variable. */ int getVariableIndex(int index); /** Returns the ith coefficient. */ long getCoefficient(int index); /** Returns the constant part of the expression. */ long getOffset(); /** Returns a builder */ static LinearExprBuilder newBuilder() { return new LinearExprBuilder(); } /** Shortcut for newBuilder().add(value).build() */ static LinearExpr constant(long value) { return newBuilder().add(value).build(); } /** Shortcut for newBuilder().addTerm(expr, coeff).build() */ static LinearExpr term(LinearArgument expr, long coeff) { return newBuilder().addTerm(expr, coeff).build(); } /** Shortcut for newBuilder().addTerm(expr, coeff).add(offset).build() */ static LinearExpr affine(LinearArgument expr, long coeff, long offset) { return newBuilder().addTerm(expr, coeff).add(offset).build(); } /** Shortcut for newBuilder().addSum(exprs).build() */ static LinearExpr sum(LinearArgument[] exprs) { return newBuilder().addSum(exprs).build(); } /** Shortcut for newBuilder().addWeightedSum(exprs, coeffs).build() */ static LinearExpr weightedSum(LinearArgument[] exprs, long[] coeffs) { return newBuilder().addWeightedSum(exprs, coeffs).build(); } static LinearExpr rebuildFromLinearExpressionProto(LinearExpressionProto proto) { int numElements = proto.getVarsCount(); if (numElements == 0) { return new ConstantExpression(proto.getOffset()); } else if (numElements == 1) { return new AffineExpression(proto.getVars(0), proto.getCoeffs(0), proto.getOffset()); } else { int[] varsIndices = new int[numElements]; long[] coeffs = new long[numElements]; long offset = proto.getOffset(); for (int i = 0; i < numElements; ++i) { varsIndices[i] = proto.getVars(i); coeffs[i] = proto.getCoeffs(i); } return new WeightedSumExpression(varsIndices, coeffs, offset); } } }
2,907
35.35
100
java
or-tools
or-tools-master/ortools/java/com/google/ortools/sat/LinearExprBuilder.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.sat; import java.util.Map; import java.util.TreeMap; /** Builder class for the LinearExpr container. */ public final class LinearExprBuilder implements LinearArgument { private final TreeMap<Integer, Long> coefficients; private long offset; LinearExprBuilder() { this.coefficients = new TreeMap<>(); this.offset = 0; } public LinearExprBuilder add(LinearArgument expr) { addTerm(expr, 1); return this; } public LinearExprBuilder add(long constant) { offset = offset + constant; return this; } public LinearExprBuilder addTerm(LinearArgument expr, long coeff) { final LinearExpr e = expr.build(); final int numElements = e.numElements(); for (int i = 0; i < numElements; ++i) { coefficients.merge(e.getVariableIndex(i), e.getCoefficient(i) * coeff, Long::sum); } offset = offset + e.getOffset() * coeff; return this; } public LinearExprBuilder addSum(LinearArgument[] exprs) { for (final LinearArgument expr : exprs) { addTerm(expr, 1); } return this; } public LinearExprBuilder addWeightedSum(LinearArgument[] exprs, long[] coeffs) { for (int i = 0; i < exprs.length; ++i) { addTerm(exprs[i], coeffs[i]); } return this; } public LinearExprBuilder addWeightedSum(LinearArgument[] exprs, int[] coeffs) { for (int i = 0; i < exprs.length; ++i) { addTerm(exprs[i], coeffs[i]); } return this; } @Override public LinearExpr build() { int numElements = 0; int lastVarIndex = -1; long lastCoeff = 0; for (Map.Entry<Integer, Long> entry : coefficients.entrySet()) { if (entry.getValue() != 0) { numElements++; lastVarIndex = entry.getKey(); lastCoeff = entry.getValue(); } } if (numElements == 0) { return new ConstantExpression(offset); } else if (numElements == 1) { return new AffineExpression(lastVarIndex, lastCoeff, offset); } else { int[] varIndices = new int[numElements]; long[] coeffs = new long[numElements]; int index = 0; for (Map.Entry<Integer, Long> entry : coefficients.entrySet()) { if (entry.getValue() != 0) { varIndices[index] = entry.getKey(); coeffs[index] = entry.getValue(); index++; } } return new WeightedSumExpression(varIndices, coeffs, offset); } } }
3,010
28.811881
88
java
or-tools
or-tools-master/ortools/java/com/google/ortools/sat/Literal.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.sat; /** Interface to describe a boolean variable or its negation. */ public interface Literal extends LinearArgument { public int getIndex(); /** Returns the Boolean negation of the current literal. */ public Literal not(); }
852
36.086957
75
java
or-tools
or-tools-master/ortools/java/com/google/ortools/sat/MultipleCircuitConstraint.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.sat; import com.google.ortools.sat.CpModelProto; import com.google.ortools.sat.RoutesConstraintProto; /** * Specialized multiple circuit constraint. * * <p>This constraint allows adding arcs to the multiple circuit constraint incrementally. */ public class MultipleCircuitConstraint extends Constraint { public MultipleCircuitConstraint(CpModelProto.Builder builder) { super(builder); } /** * Add an arc to the graph of the multiple circuit constraint. * * @param tail the index of the tail node. * @param head the index of the head node. * @param literal it will be set to true if the arc is selected. */ public MultipleCircuitConstraint addArc(int tail, int head, Literal literal) { RoutesConstraintProto.Builder circuit = getBuilder().getRoutesBuilder(); circuit.addTails(tail); circuit.addHeads(head); circuit.addLiterals(literal.getIndex()); return this; } }
1,540
34.022727
90
java
or-tools
or-tools-master/ortools/java/com/google/ortools/sat/NoOverlap2dConstraint.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.sat; import com.google.ortools.sat.CpModelProto; import com.google.ortools.sat.NoOverlap2DConstraintProto; /** * Specialized NoOverlap2D constraint. * * <p>This constraint allows adding rectanles to the NoOverlap2D constraint incrementally. */ public class NoOverlap2dConstraint extends Constraint { public NoOverlap2dConstraint(CpModelProto.Builder builder) { super(builder); } /// Adds a rectangle (xInterval, yInterval) to the constraint. public NoOverlap2dConstraint addRectangle(IntervalVar xInterval, IntervalVar yInterval) { NoOverlap2DConstraintProto.Builder noOverlap2d = getBuilder().getNoOverlap2DBuilder(); noOverlap2d.addXIntervals(xInterval.getIndex()); noOverlap2d.addYIntervals(yInterval.getIndex()); return this; } }
1,388
36.540541
91
java
or-tools
or-tools-master/ortools/java/com/google/ortools/sat/NotBoolVar.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.sat; /** * The negation of a boolean variable. This class should not be used directly, Literal must be used * instead. */ public final class NotBoolVar implements Literal { public NotBoolVar(BoolVar boolVar) { this.boolVar = boolVar; } /** returns the index in the literal in the underlying CpModelProto. */ @Override public int getIndex() { return -boolVar.getIndex() - 1; } /** Returns the negation of this literal. */ @Override public Literal not() { return boolVar; } // LinearArgument interface. @Override public LinearExpr build() { return new AffineExpression(boolVar.getIndex(), -1, 1); } /** Returns a short string describing this literal. */ @Override public String toString() { return "not(" + boolVar + ")"; } private final BoolVar boolVar; }
1,439
27.235294
99
java
or-tools
or-tools-master/ortools/java/com/google/ortools/sat/ReservoirConstraint.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.sat; import com.google.ortools.sat.ReservoirConstraintProto; /** * Specialized reservoir constraint. * * <p>This constraint allows adding events (time, levelChange, isActive (optional)) to the reservoir * constraint incrementally. */ public class ReservoirConstraint extends Constraint { public ReservoirConstraint(CpModel model) { super(model.getBuilder()); this.model = model; } /** * Adds a mandatory event * * <p>It will increase the used capacity by `levelChange` at time `time`. `time` must be an affine * expression. */ public ReservoirConstraint addEvent(LinearArgument time, long levelChange) { ReservoirConstraintProto.Builder reservoir = getBuilder().getReservoirBuilder(); reservoir.addTimeExprs( model.getLinearExpressionProtoBuilderFromLinearArgument(time, /*negate=*/false)); reservoir.addLevelChanges(levelChange); reservoir.addActiveLiterals(model.trueLiteral().getIndex()); return this; } /** * Adds a mandatory event at a fixed time * * <p>It will increase the used capacity by `levelChange` at time `time`. */ public ReservoirConstraint addEvent(long time, long levelChange) { ReservoirConstraintProto.Builder reservoir = getBuilder().getReservoirBuilder(); reservoir.addTimeExprs(model.getLinearExpressionProtoBuilderFromLong(time)); reservoir.addLevelChanges(levelChange); reservoir.addActiveLiterals(model.trueLiteral().getIndex()); return this; } /** * Adds an optional event * * <p>If `isActive` is true, It will increase the used capacity by `levelChange` at time `time`. * `time` must be an affine expression. */ public ReservoirConstraint addOptionalEvent(LinearExpr time, long levelChange, Literal isActive) { ReservoirConstraintProto.Builder reservoir = getBuilder().getReservoirBuilder(); reservoir.addTimeExprs( model.getLinearExpressionProtoBuilderFromLinearArgument(time, /*negate=*/false)); reservoir.addLevelChanges(levelChange); reservoir.addActiveLiterals(isActive.getIndex()); return this; } /** * Adds an optional event at a fixed time * * <p>If `isActive` is true, It will increase the used capacity by `levelChange` at time `time`. */ public ReservoirConstraint addOptionalEvent(long time, long levelChange, Literal isActive) { ReservoirConstraintProto.Builder reservoir = getBuilder().getReservoirBuilder(); reservoir.addTimeExprs(model.getLinearExpressionProtoBuilderFromLong(time)); reservoir.addLevelChanges(levelChange); reservoir.addActiveLiterals(isActive.getIndex()); return this; } private final CpModel model; }
3,281
36.295455
100
java
or-tools
or-tools-master/ortools/java/com/google/ortools/sat/TableConstraint.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.sat; import com.google.ortools.sat.CpModelProto; import com.google.ortools.sat.TableConstraintProto; /** * Specialized assignment constraint. * * <p>This constraint allows adding tuples to the allowed/forbidden assignment constraint * incrementally. */ public class TableConstraint extends Constraint { public TableConstraint(CpModelProto.Builder builder) { super(builder); } /** * Adds a tuple of possible/forbidden values to the constraint. * * @param tuple the tuple to add to the constraint. * @throws CpModel.WrongLength if the tuple does not have the same length as the array of * variables of the constraint. */ public TableConstraint addTuple(int[] tuple) { TableConstraintProto.Builder table = getBuilder().getTableBuilder(); if (tuple.length != table.getVarsCount()) { throw new CpModel.WrongLength( "addTuple", "tuple does not have the same length as the variables"); } for (int value : tuple) { table.addValues(value); } return this; } /** * Adds a tuple of possible/forbidden values to the constraint. * * @param tuple the tuple to add to the constraint. * @throws CpModel.WrongLength if the tuple does not have the same length as the array of * variables of the constraint. */ public TableConstraint addTuple(long[] tuple) { TableConstraintProto.Builder table = getBuilder().getTableBuilder(); if (tuple.length != table.getVarsCount()) { throw new CpModel.WrongLength( "addTuple", "tuple does not have the same length as the variables"); } for (long value : tuple) { table.addValues(value); } return this; } /** * Adds a list of tuples of possible/forbidden values to the constraint. * * @param tuples the list of tuples to add to the constraint. * @throws CpModel.WrongLength if one tuple does not have the same length as the array of * variables of the constraint. */ public TableConstraint addTuples(int[][] tuples) { TableConstraintProto.Builder table = getBuilder().getTableBuilder(); for (int[] tuple : tuples) { if (tuple.length != table.getVarsCount()) { throw new CpModel.WrongLength( "addTuples", "a tuple does not have the same length as the variables"); } for (int value : tuple) { table.addValues(value); } } return this; } /** * Adds a list of tuples of possible/forbidden values to the constraint. * * @param tuples the list of tuples to add to the constraint. * @throws CpModel.WrongLength if one tuple does not have the same length as the array of * variables of the constraint. */ public TableConstraint addTuples(long[][] tuples) { TableConstraintProto.Builder table = getBuilder().getTableBuilder(); for (long[] tuple : tuples) { if (tuple.length != table.getVarsCount()) { throw new CpModel.WrongLength( "addTuples", "a tuple does not have the same length as the variables"); } for (long value : tuple) { table.addValues(value); } } return this; } }
3,761
33.2
91
java
or-tools
or-tools-master/ortools/java/com/google/ortools/sat/WeightedSumExpression.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ortools.sat; /** A specialized linear expression: sum(ai * xi) + b. */ public final class WeightedSumExpression implements LinearExpr { private final int[] variablesIndices; private final long[] coefficients; private final long offset; public WeightedSumExpression(int[] variablesIndices, long[] coefficients, long offset) { this.variablesIndices = variablesIndices; this.coefficients = coefficients; this.offset = offset; } @Override public LinearExpr build() { return this; } @Override public int numElements() { return variablesIndices.length; } @Override public int getVariableIndex(int index) { if (index < 0 || index >= variablesIndices.length) { throw new IllegalArgumentException("wrong index in LinearExpr.getVariable(): " + index); } return variablesIndices[index]; } @Override public long getCoefficient(int index) { if (index < 0 || index >= variablesIndices.length) { throw new IllegalArgumentException("wrong index in LinearExpr.getCoefficient(): " + index); } return coefficients[index]; } @Override public long getOffset() { return offset; } }
1,776
29.118644
97
java
or-tools
or-tools-master/ortools/linear_solver/samples/AssignmentGroupsMip.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START program] package com.google.ortools.linearsolver.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.linearsolver.MPConstraint; import com.google.ortools.linearsolver.MPObjective; import com.google.ortools.linearsolver.MPSolver; import com.google.ortools.linearsolver.MPVariable; import java.util.stream.IntStream; // [END import] /** MIP example that solves an assignment problem. */ public class AssignmentGroupsMip { public static void main(String[] args) { Loader.loadNativeLibraries(); // Data // [START data] double[][] costs = { {90, 76, 75, 70, 50, 74}, {35, 85, 55, 65, 48, 101}, {125, 95, 90, 105, 59, 120}, {45, 110, 95, 115, 104, 83}, {60, 105, 80, 75, 59, 62}, {45, 65, 110, 95, 47, 31}, {38, 51, 107, 41, 69, 99}, {47, 85, 57, 71, 92, 77}, {39, 63, 97, 49, 118, 56}, {47, 101, 71, 60, 88, 109}, {17, 39, 103, 64, 61, 92}, {101, 45, 83, 59, 92, 27}, }; int numWorkers = costs.length; int numTasks = costs[0].length; final int[] allWorkers = IntStream.range(0, numWorkers).toArray(); final int[] allTasks = IntStream.range(0, numTasks).toArray(); // [END data] // Allowed groups of workers: // [START allowed_groups] int[][] group1 = { // group of worker 0-3 {2, 3}, {1, 3}, {1, 2}, {0, 1}, {0, 2}, }; int[][] group2 = { // group of worker 4-7 {6, 7}, {5, 7}, {5, 6}, {4, 5}, {4, 7}, }; int[][] group3 = { // group of worker 8-11 {10, 11}, {9, 11}, {9, 10}, {8, 10}, {8, 11}, }; // [END allowed_groups] // Solver // [START solver] // Create the linear solver with the SCIP backend. MPSolver solver = MPSolver.createSolver("SCIP"); if (solver == null) { System.out.println("Could not create solver SCIP"); return; } // [END solver] // Variables // [START variables] // x[i][j] is an array of 0-1 variables, which will be 1 // if worker i is assigned to task j. MPVariable[][] x = new MPVariable[numWorkers][numTasks]; for (int worker : allWorkers) { for (int task : allTasks) { x[worker][task] = solver.makeBoolVar("x[" + worker + "," + task + "]"); } } // [END variables] // Constraints // [START constraints] // Each worker is assigned to at most one task. for (int worker : allWorkers) { MPConstraint constraint = solver.makeConstraint(0, 1, ""); for (int task : allTasks) { constraint.setCoefficient(x[worker][task], 1); } } // Each task is assigned to exactly one worker. for (int task : allTasks) { MPConstraint constraint = solver.makeConstraint(1, 1, ""); for (int worker : allWorkers) { constraint.setCoefficient(x[worker][task], 1); } } // [END constraints] // [START assignments] // Create variables for each worker, indicating whether they work on some task. MPVariable[] work = new MPVariable[numWorkers]; for (int worker : allWorkers) { work[worker] = solver.makeBoolVar("work[" + worker + "]"); } for (int worker : allWorkers) { // MPVariable[] vars = new MPVariable[numTasks]; MPConstraint constraint = solver.makeConstraint(0, 0, ""); for (int task : allTasks) { // vars[task] = x[worker][task]; constraint.setCoefficient(x[worker][task], 1); } // solver.addEquality(work[worker], LinearExpr.sum(vars)); constraint.setCoefficient(work[worker], -1); } // Group1 MPConstraint constraintG1 = solver.makeConstraint(1, 1, ""); for (int i = 0; i < group1.length; ++i) { // a*b can be transformed into 0 <= a + b - 2*p <= 1 with p in [0,1] // p is True if a AND b, False otherwise MPConstraint constraint = solver.makeConstraint(0, 1, ""); constraint.setCoefficient(work[group1[i][0]], 1); constraint.setCoefficient(work[group1[i][1]], 1); MPVariable p = solver.makeBoolVar("g1_p" + i); constraint.setCoefficient(p, -2); constraintG1.setCoefficient(p, 1); } // Group2 MPConstraint constraintG2 = solver.makeConstraint(1, 1, ""); for (int i = 0; i < group2.length; ++i) { // a*b can be transformed into 0 <= a + b - 2*p <= 1 with p in [0,1] // p is True if a AND b, False otherwise MPConstraint constraint = solver.makeConstraint(0, 1, ""); constraint.setCoefficient(work[group2[i][0]], 1); constraint.setCoefficient(work[group2[i][1]], 1); MPVariable p = solver.makeBoolVar("g2_p" + i); constraint.setCoefficient(p, -2); constraintG2.setCoefficient(p, 1); } // Group3 MPConstraint constraintG3 = solver.makeConstraint(1, 1, ""); for (int i = 0; i < group3.length; ++i) { // a*b can be transformed into 0 <= a + b - 2*p <= 1 with p in [0,1] // p is True if a AND b, False otherwise MPConstraint constraint = solver.makeConstraint(0, 1, ""); constraint.setCoefficient(work[group3[i][0]], 1); constraint.setCoefficient(work[group3[i][1]], 1); MPVariable p = solver.makeBoolVar("g3_p" + i); constraint.setCoefficient(p, -2); constraintG3.setCoefficient(p, 1); } // [END assignments] // Objective // [START objective] MPObjective objective = solver.objective(); for (int worker : allWorkers) { for (int task : allTasks) { objective.setCoefficient(x[worker][task], costs[worker][task]); } } objective.setMinimization(); // [END objective] // Solve // [START solve] MPSolver.ResultStatus resultStatus = solver.solve(); // [END solve] // Print solution. // [START print_solution] // Check that the problem has a feasible solution. if (resultStatus == MPSolver.ResultStatus.OPTIMAL || resultStatus == MPSolver.ResultStatus.FEASIBLE) { System.out.println("Total cost: " + objective.value() + "\n"); for (int worker : allWorkers) { for (int task : allTasks) { // Test if x[i][j] is 0 or 1 (with tolerance for floating point // arithmetic). if (x[worker][task].solutionValue() > 0.5) { System.out.println("Worker " + worker + " assigned to task " + task + ". Cost: " + costs[worker][task]); } } } } else { System.err.println("No solution found."); } // [END print_solution] } private AssignmentGroupsMip() {} } // [END program]
7,283
31.810811
83
java
or-tools
or-tools-master/ortools/linear_solver/samples/AssignmentMip.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START program] package com.google.ortools.linearsolver.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.linearsolver.MPConstraint; import com.google.ortools.linearsolver.MPObjective; import com.google.ortools.linearsolver.MPSolver; import com.google.ortools.linearsolver.MPVariable; // [END import] /** MIP example that solves an assignment problem. */ public class AssignmentMip { public static void main(String[] args) { Loader.loadNativeLibraries(); // Data // [START data_model] double[][] costs = { {90, 80, 75, 70}, {35, 85, 55, 65}, {125, 95, 90, 95}, {45, 110, 95, 115}, {50, 100, 90, 100}, }; int numWorkers = costs.length; int numTasks = costs[0].length; // [END data_model] // Solver // [START solver] // Create the linear solver with the SCIP backend. MPSolver solver = MPSolver.createSolver("SCIP"); if (solver == null) { System.out.println("Could not create solver SCIP"); return; } // [END solver] // Variables // [START variables] // x[i][j] is an array of 0-1 variables, which will be 1 // if worker i is assigned to task j. MPVariable[][] x = new MPVariable[numWorkers][numTasks]; for (int i = 0; i < numWorkers; ++i) { for (int j = 0; j < numTasks; ++j) { x[i][j] = solver.makeIntVar(0, 1, ""); } } // [END variables] // Constraints // [START constraints] // Each worker is assigned to at most one task. for (int i = 0; i < numWorkers; ++i) { MPConstraint constraint = solver.makeConstraint(0, 1, ""); for (int j = 0; j < numTasks; ++j) { constraint.setCoefficient(x[i][j], 1); } } // Each task is assigned to exactly one worker. for (int j = 0; j < numTasks; ++j) { MPConstraint constraint = solver.makeConstraint(1, 1, ""); for (int i = 0; i < numWorkers; ++i) { constraint.setCoefficient(x[i][j], 1); } } // [END constraints] // Objective // [START objective] MPObjective objective = solver.objective(); for (int i = 0; i < numWorkers; ++i) { for (int j = 0; j < numTasks; ++j) { objective.setCoefficient(x[i][j], costs[i][j]); } } objective.setMinimization(); // [END objective] // Solve // [START solve] MPSolver.ResultStatus resultStatus = solver.solve(); // [END solve] // Print solution. // [START print_solution] // Check that the problem has a feasible solution. if (resultStatus == MPSolver.ResultStatus.OPTIMAL || resultStatus == MPSolver.ResultStatus.FEASIBLE) { System.out.println("Total cost: " + objective.value() + "\n"); for (int i = 0; i < numWorkers; ++i) { for (int j = 0; j < numTasks; ++j) { // Test if x[i][j] is 0 or 1 (with tolerance for floating point // arithmetic). if (x[i][j].solutionValue() > 0.5) { System.out.println( "Worker " + i + " assigned to task " + j + ". Cost = " + costs[i][j]); } } } } else { System.err.println("No solution found."); } // [END print_solution] } private AssignmentMip() {} } // [END program]
3,880
30.811475
87
java
or-tools
or-tools-master/ortools/linear_solver/samples/AssignmentTaskSizesMip.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START program] package com.google.ortools.linearsolver.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.linearsolver.MPConstraint; import com.google.ortools.linearsolver.MPObjective; import com.google.ortools.linearsolver.MPSolver; import com.google.ortools.linearsolver.MPVariable; import java.util.stream.IntStream; // [END import] /** MIP example that solves an assignment problem. */ public class AssignmentTaskSizesMip { public static void main(String[] args) { Loader.loadNativeLibraries(); // Data // [START data] double[][] costs = { {90, 76, 75, 70, 50, 74, 12, 68}, {35, 85, 55, 65, 48, 101, 70, 83}, {125, 95, 90, 105, 59, 120, 36, 73}, {45, 110, 95, 115, 104, 83, 37, 71}, {60, 105, 80, 75, 59, 62, 93, 88}, {45, 65, 110, 95, 47, 31, 81, 34}, {38, 51, 107, 41, 69, 99, 115, 48}, {47, 85, 57, 71, 92, 77, 109, 36}, {39, 63, 97, 49, 118, 56, 92, 61}, {47, 101, 71, 60, 88, 109, 52, 90}, }; int numWorkers = costs.length; int numTasks = costs[0].length; final int[] allWorkers = IntStream.range(0, numWorkers).toArray(); final int[] allTasks = IntStream.range(0, numTasks).toArray(); final int[] taskSizes = {10, 7, 3, 12, 15, 4, 11, 5}; // Maximum total of task sizes for any worker final int totalSizeMax = 15; // [END data] // Solver // [START solver] // Create the linear solver with the SCIP backend. MPSolver solver = MPSolver.createSolver("SCIP"); if (solver == null) { System.out.println("Could not create solver SCIP"); return; } // [END solver] // Variables // [START variables] // x[i][j] is an array of 0-1 variables, which will be 1 // if worker i is assigned to task j. MPVariable[][] x = new MPVariable[numWorkers][numTasks]; for (int worker : allWorkers) { for (int task : allTasks) { x[worker][task] = solver.makeBoolVar("x[" + worker + "," + task + "]"); } } // [END variables] // Constraints // [START constraints] // Each worker is assigned to at most max task size. for (int worker : allWorkers) { MPConstraint constraint = solver.makeConstraint(0, totalSizeMax, ""); for (int task : allTasks) { constraint.setCoefficient(x[worker][task], taskSizes[task]); } } // Each task is assigned to exactly one worker. for (int task : allTasks) { MPConstraint constraint = solver.makeConstraint(1, 1, ""); for (int worker : allWorkers) { constraint.setCoefficient(x[worker][task], 1); } } // [END constraints] // Objective // [START objective] MPObjective objective = solver.objective(); for (int worker : allWorkers) { for (int task : allTasks) { objective.setCoefficient(x[worker][task], costs[worker][task]); } } objective.setMinimization(); // [END objective] // Solve // [START solve] MPSolver.ResultStatus resultStatus = solver.solve(); // [END solve] // Print solution. // [START print_solution] // Check that the problem has a feasible solution. if (resultStatus == MPSolver.ResultStatus.OPTIMAL || resultStatus == MPSolver.ResultStatus.FEASIBLE) { System.out.println("Total cost: " + objective.value() + "\n"); for (int worker : allWorkers) { for (int task : allTasks) { // Test if x[i][j] is 0 or 1 (with tolerance for floating point // arithmetic). if (x[worker][task].solutionValue() > 0.5) { System.out.println("Worker " + worker + " assigned to task " + task + ". Cost: " + costs[worker][task]); } } } } else { System.err.println("No solution found."); } // [END print_solution] } private AssignmentTaskSizesMip() {} } // [END program]
4,539
32.62963
79
java
or-tools
or-tools-master/ortools/linear_solver/samples/AssignmentTeamsMip.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START program] package com.google.ortools.linearsolver.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.linearsolver.MPConstraint; import com.google.ortools.linearsolver.MPObjective; import com.google.ortools.linearsolver.MPSolver; import com.google.ortools.linearsolver.MPVariable; import java.util.stream.IntStream; // [END import] /** MIP example that solves an assignment problem. */ public class AssignmentTeamsMip { public static void main(String[] args) { Loader.loadNativeLibraries(); // Data // [START data] double[][] costs = { {90, 76, 75, 70}, {35, 85, 55, 65}, {125, 95, 90, 105}, {45, 110, 95, 115}, {60, 105, 80, 75}, {45, 65, 110, 95}, }; int numWorkers = costs.length; int numTasks = costs[0].length; final int[] allWorkers = IntStream.range(0, numWorkers).toArray(); final int[] allTasks = IntStream.range(0, numTasks).toArray(); final int[] team1 = {0, 2, 4}; final int[] team2 = {1, 3, 5}; // Maximum total of tasks for any team final int teamMax = 2; // [END data] // Solver // [START solver] // Create the linear solver with the SCIP backend. MPSolver solver = MPSolver.createSolver("SCIP"); if (solver == null) { System.out.println("Could not create solver SCIP"); return; } // [END solver] // Variables // [START variables] // x[i][j] is an array of 0-1 variables, which will be 1 // if worker i is assigned to task j. MPVariable[][] x = new MPVariable[numWorkers][numTasks]; for (int worker : allWorkers) { for (int task : allTasks) { x[worker][task] = solver.makeBoolVar("x[" + worker + "," + task + "]"); } } // [END variables] // Constraints // [START constraints] // Each worker is assigned to at most one task. for (int worker : allWorkers) { MPConstraint constraint = solver.makeConstraint(0, 1, ""); for (int task : allTasks) { constraint.setCoefficient(x[worker][task], 1); } } // Each task is assigned to exactly one worker. for (int task : allTasks) { MPConstraint constraint = solver.makeConstraint(1, 1, ""); for (int worker : allWorkers) { constraint.setCoefficient(x[worker][task], 1); } } // Each team takes at most two tasks. MPConstraint team1Tasks = solver.makeConstraint(0, teamMax, ""); for (int worker : team1) { for (int task : allTasks) { team1Tasks.setCoefficient(x[worker][task], 1); } } MPConstraint team2Tasks = solver.makeConstraint(0, teamMax, ""); for (int worker : team2) { for (int task : allTasks) { team2Tasks.setCoefficient(x[worker][task], 1); } } // [END constraints] // Objective // [START objective] MPObjective objective = solver.objective(); for (int worker : allWorkers) { for (int task : allTasks) { objective.setCoefficient(x[worker][task], costs[worker][task]); } } objective.setMinimization(); // [END objective] // Solve // [START solve] MPSolver.ResultStatus resultStatus = solver.solve(); // [END solve] // Print solution. // [START print_solution] // Check that the problem has a feasible solution. if (resultStatus == MPSolver.ResultStatus.OPTIMAL || resultStatus == MPSolver.ResultStatus.FEASIBLE) { System.out.println("Total cost: " + objective.value() + "\n"); for (int worker : allWorkers) { for (int task : allTasks) { // Test if x[i][j] is 0 or 1 (with tolerance for floating point // arithmetic). if (x[worker][task].solutionValue() > 0.5) { System.out.println("Worker " + worker + " assigned to task " + task + ". Cost: " + costs[worker][task]); } } } } else { System.err.println("No solution found."); } // [END print_solution] } private AssignmentTeamsMip() {} } // [END program]
4,677
30.823129
79
java
or-tools
or-tools-master/ortools/linear_solver/samples/BasicExample.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Minimal example to call the GLOP solver. // [START program] package com.google.ortools.linearsolver.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.linearsolver.MPConstraint; import com.google.ortools.linearsolver.MPObjective; import com.google.ortools.linearsolver.MPSolver; import com.google.ortools.linearsolver.MPVariable; // [END import] /** Minimal Linear Programming example to showcase calling the solver. */ public final class BasicExample { public static void main(String[] args) { Loader.loadNativeLibraries(); // [START solver] // Create the linear solver with the GLOP backend. MPSolver solver = MPSolver.createSolver("GLOP"); // [END solver] // [START variables] // Create the variables x and y. MPVariable x = solver.makeNumVar(0.0, 1.0, "x"); MPVariable y = solver.makeNumVar(0.0, 2.0, "y"); System.out.println("Number of variables = " + solver.numVariables()); // [END variables] // [START constraints] // Create a linear constraint, 0 <= x + y <= 2. MPConstraint ct = solver.makeConstraint(0.0, 2.0, "ct"); ct.setCoefficient(x, 1); ct.setCoefficient(y, 1); System.out.println("Number of constraints = " + solver.numConstraints()); // [END constraints] // [START objective] // Create the objective function, 3 * x + y. MPObjective objective = solver.objective(); objective.setCoefficient(x, 3); objective.setCoefficient(y, 1); objective.setMaximization(); // [END objective] // [START solve] solver.solve(); // [END solve] // [START print_solution] System.out.println("Solution:"); System.out.println("Objective value = " + objective.value()); System.out.println("x = " + x.solutionValue()); System.out.println("y = " + y.solutionValue()); // [END print_solution] } private BasicExample() {} } // [END program]
2,511
32.945946
77
java
or-tools
or-tools-master/ortools/linear_solver/samples/BinPackingMip.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // MIP example that solves a bin packing problem. // [START program] package com.google.ortools.linearsolver.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.linearsolver.MPConstraint; import com.google.ortools.linearsolver.MPObjective; import com.google.ortools.linearsolver.MPSolver; import com.google.ortools.linearsolver.MPVariable; // [END import] /** Bin packing problem. */ public class BinPackingMip { // [START program_part1] // [START data_model] static class DataModel { public final double[] weights = {48, 30, 19, 36, 36, 27, 42, 42, 36, 24, 30}; public final int numItems = weights.length; public final int numBins = weights.length; public final int binCapacity = 100; } // [END data_model] public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); // [START data] final DataModel data = new DataModel(); // [END data] // [END program_part1] // [START solver] // Create the linear solver with the SCIP backend. MPSolver solver = MPSolver.createSolver("SCIP"); if (solver == null) { System.out.println("Could not create solver SCIP"); return; } // [END solver] // [START program_part2] // [START variables] MPVariable[][] x = new MPVariable[data.numItems][data.numBins]; for (int i = 0; i < data.numItems; ++i) { for (int j = 0; j < data.numBins; ++j) { x[i][j] = solver.makeIntVar(0, 1, ""); } } MPVariable[] y = new MPVariable[data.numBins]; for (int j = 0; j < data.numBins; ++j) { y[j] = solver.makeIntVar(0, 1, ""); } // [END variables] // [START constraints] double infinity = java.lang.Double.POSITIVE_INFINITY; for (int i = 0; i < data.numItems; ++i) { MPConstraint constraint = solver.makeConstraint(1, 1, ""); for (int j = 0; j < data.numBins; ++j) { constraint.setCoefficient(x[i][j], 1); } } // The bin capacity contraint for bin j is // sum_i w_i x_ij <= C*y_j // To define this constraint, first subtract the left side from the right to get // 0 <= C*y_j - sum_i w_i x_ij // // Note: Since sum_i w_i x_ij is positive (and y_j is 0 or 1), the right side must // be less than or equal to C. But it's not necessary to add this constraint // because it is forced by the other constraints. for (int j = 0; j < data.numBins; ++j) { MPConstraint constraint = solver.makeConstraint(0, infinity, ""); constraint.setCoefficient(y[j], data.binCapacity); for (int i = 0; i < data.numItems; ++i) { constraint.setCoefficient(x[i][j], -data.weights[i]); } } // [END constraints] // [START objective] MPObjective objective = solver.objective(); for (int j = 0; j < data.numBins; ++j) { objective.setCoefficient(y[j], 1); } objective.setMinimization(); // [END objective] // [START solve] final MPSolver.ResultStatus resultStatus = solver.solve(); // [END solve] // [START print_solution] // Check that the problem has an optimal solution. if (resultStatus == MPSolver.ResultStatus.OPTIMAL) { System.out.println("Number of bins used: " + objective.value()); double totalWeight = 0; for (int j = 0; j < data.numBins; ++j) { if (y[j].solutionValue() == 1) { System.out.println("\nBin " + j + "\n"); double binWeight = 0; for (int i = 0; i < data.numItems; ++i) { if (x[i][j].solutionValue() == 1) { System.out.println("Item " + i + " - weight: " + data.weights[i]); binWeight += data.weights[i]; } } System.out.println("Packed bin weight: " + binWeight); totalWeight += binWeight; } } System.out.println("\nTotal packed weight: " + totalWeight); } else { System.err.println("The problem does not have an optimal solution."); } // [END print_solution] } private BinPackingMip() {} } // [END program_part2] // [END program]
4,699
34.074627
86
java
or-tools
or-tools-master/ortools/linear_solver/samples/LinearProgrammingExample.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START program] package com.google.ortools.linearsolver.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.linearsolver.MPConstraint; import com.google.ortools.linearsolver.MPObjective; import com.google.ortools.linearsolver.MPSolver; import com.google.ortools.linearsolver.MPVariable; // [END import] /** Simple linear programming example. */ public final class LinearProgrammingExample { public static void main(String[] args) { Loader.loadNativeLibraries(); // [START solver] MPSolver solver = MPSolver.createSolver("GLOP"); // [END solver] // [START variables] double infinity = java.lang.Double.POSITIVE_INFINITY; // x and y are continuous non-negative variables. MPVariable x = solver.makeNumVar(0.0, infinity, "x"); MPVariable y = solver.makeNumVar(0.0, infinity, "y"); System.out.println("Number of variables = " + solver.numVariables()); // [END variables] // [START constraints] // x + 2*y <= 14. MPConstraint c0 = solver.makeConstraint(-infinity, 14.0, "c0"); c0.setCoefficient(x, 1); c0.setCoefficient(y, 2); // 3*x - y >= 0. MPConstraint c1 = solver.makeConstraint(0.0, infinity, "c1"); c1.setCoefficient(x, 3); c1.setCoefficient(y, -1); // x - y <= 2. MPConstraint c2 = solver.makeConstraint(-infinity, 2.0, "c2"); c2.setCoefficient(x, 1); c2.setCoefficient(y, -1); System.out.println("Number of constraints = " + solver.numConstraints()); // [END constraints] // [START objective] // Maximize 3 * x + 4 * y. MPObjective objective = solver.objective(); objective.setCoefficient(x, 3); objective.setCoefficient(y, 4); objective.setMaximization(); // [END objective] // [START solve] final MPSolver.ResultStatus resultStatus = solver.solve(); // [END solve] // [START print_solution] if (resultStatus == MPSolver.ResultStatus.OPTIMAL) { System.out.println("Solution:"); System.out.println("Objective value = " + objective.value()); System.out.println("x = " + x.solutionValue()); System.out.println("y = " + y.solutionValue()); } else { System.err.println("The problem does not have an optimal solution!"); } // [END print_solution] // [START advanced] System.out.println("\nAdvanced usage:"); System.out.println("Problem solved in " + solver.wallTime() + " milliseconds"); System.out.println("Problem solved in " + solver.iterations() + " iterations"); // [END advanced] } private LinearProgrammingExample() {} } // [END program]
3,202
34.197802
83
java
or-tools
or-tools-master/ortools/linear_solver/samples/MipVarArray.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // MIP example that uses a variable array. // [START program] package com.google.ortools.linearsolver.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.linearsolver.MPConstraint; import com.google.ortools.linearsolver.MPObjective; import com.google.ortools.linearsolver.MPSolver; import com.google.ortools.linearsolver.MPVariable; // [END import] // [START program_part1] /** MIP example with a variable array. */ public class MipVarArray { // [START data_model] static class DataModel { public final double[][] constraintCoeffs = { {5, 7, 9, 2, 1}, {18, 4, -9, 10, 12}, {4, 7, 3, 8, 5}, {5, 13, 16, 3, -7}, }; public final double[] bounds = {250, 285, 211, 315}; public final double[] objCoeffs = {7, 8, 2, 9, 6}; public final int numVars = 5; public final int numConstraints = 4; } // [END data_model] public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); // [START data] final DataModel data = new DataModel(); // [END data] // [END program_part1] // [START solver] // Create the linear solver with the SCIP backend. MPSolver solver = MPSolver.createSolver("SCIP"); if (solver == null) { System.out.println("Could not create solver SCIP"); return; } // [END solver] // [START program_part2] // [START variables] double infinity = java.lang.Double.POSITIVE_INFINITY; MPVariable[] x = new MPVariable[data.numVars]; for (int j = 0; j < data.numVars; ++j) { x[j] = solver.makeIntVar(0.0, infinity, ""); } System.out.println("Number of variables = " + solver.numVariables()); // [END variables] // [START constraints] // Create the constraints. for (int i = 0; i < data.numConstraints; ++i) { MPConstraint constraint = solver.makeConstraint(0, data.bounds[i], ""); for (int j = 0; j < data.numVars; ++j) { constraint.setCoefficient(x[j], data.constraintCoeffs[i][j]); } } System.out.println("Number of constraints = " + solver.numConstraints()); // [END constraints] // [START objective] MPObjective objective = solver.objective(); for (int j = 0; j < data.numVars; ++j) { objective.setCoefficient(x[j], data.objCoeffs[j]); } objective.setMaximization(); // [END objective] // [START solve] final MPSolver.ResultStatus resultStatus = solver.solve(); // [END solve] // [START print_solution] // Check that the problem has an optimal solution. if (resultStatus == MPSolver.ResultStatus.OPTIMAL) { System.out.println("Objective value = " + objective.value()); for (int j = 0; j < data.numVars; ++j) { System.out.println("x[" + j + "] = " + x[j].solutionValue()); } System.out.println(); System.out.println("Problem solved in " + solver.wallTime() + " milliseconds"); System.out.println("Problem solved in " + solver.iterations() + " iterations"); System.out.println("Problem solved in " + solver.nodes() + " branch-and-bound nodes"); } else { System.err.println("The problem does not have an optimal solution."); } // [END print_solution] } private MipVarArray() {} } // [END program_part2] // [END program]
3,909
33.60177
92
java
or-tools
or-tools-master/ortools/linear_solver/samples/MultipleKnapsackMip.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START program] // Solve a multiple knapsack problem using a MIP solver. package com.google.ortools.linearsolver.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.linearsolver.MPConstraint; import com.google.ortools.linearsolver.MPObjective; import com.google.ortools.linearsolver.MPSolver; import com.google.ortools.linearsolver.MPVariable; import java.util.stream.IntStream; // [END import] /** Multiple knapsack problem. */ public class MultipleKnapsackMip { public static void main(String[] args) { Loader.loadNativeLibraries(); // Instantiate the data problem. // [START data] final double[] weights = {48, 30, 42, 36, 36, 48, 42, 42, 36, 24, 30, 30, 42, 36, 36}; final double[] values = {10, 30, 25, 50, 35, 30, 15, 40, 30, 35, 45, 10, 20, 30, 25}; final int numItems = weights.length; final int[] allItems = IntStream.range(0, numItems).toArray(); final double[] binCapacities = {100, 100, 100, 100, 100}; final int numBins = binCapacities.length; final int[] allBins = IntStream.range(0, numBins).toArray(); // [END data] // [START solver] // Create the linear solver with the SCIP backend. MPSolver solver = MPSolver.createSolver("SCIP"); if (solver == null) { System.out.println("Could not create solver SCIP"); return; } // [END solver] // Variables. // [START variables] MPVariable[][] x = new MPVariable[numItems][numBins]; for (int i : allItems) { for (int b : allBins) { x[i][b] = solver.makeBoolVar("x_" + i + "_" + b); } } // [END variables] // Constraints. // [START constraints] // Each item is assigned to at most one bin. for (int i : allItems) { MPConstraint constraint = solver.makeConstraint(0, 1, ""); for (int b : allBins) { constraint.setCoefficient(x[i][b], 1); } } // The amount packed in each bin cannot exceed its capacity. for (int b : allBins) { MPConstraint constraint = solver.makeConstraint(0, binCapacities[b], ""); for (int i : allItems) { constraint.setCoefficient(x[i][b], weights[i]); } } // [END constraints] // Objective. // [START objective] // Maximize total value of packed items. MPObjective objective = solver.objective(); for (int i : allItems) { for (int b : allBins) { objective.setCoefficient(x[i][b], values[i]); } } objective.setMaximization(); // [END objective] // [START solve] final MPSolver.ResultStatus status = solver.solve(); // [END solve] // [START print_solution] // Check that the problem has an optimal solution. if (status == MPSolver.ResultStatus.OPTIMAL) { System.out.println("Total packed value: " + objective.value()); double totalWeight = 0; for (int b : allBins) { double binWeight = 0; double binValue = 0; System.out.println("Bin " + b); for (int i : allItems) { if (x[i][b].solutionValue() == 1) { System.out.println("Item " + i + " weight: " + weights[i] + " value: " + values[i]); binWeight += weights[i]; binValue += values[i]; } } System.out.println("Packed bin weight: " + binWeight); System.out.println("Packed bin value: " + binValue); totalWeight += binWeight; } System.out.println("Total packed weight: " + totalWeight); } else { System.err.println("The problem does not have an optimal solution."); } // [END print_solution] } private MultipleKnapsackMip() {} } // [END program]
4,268
32.880952
96
java
or-tools
or-tools-master/ortools/linear_solver/samples/SimpleLpProgram.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Minimal example to call the GLOP solver. // [START program] package com.google.ortools.linearsolver.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.linearsolver.MPConstraint; import com.google.ortools.linearsolver.MPObjective; import com.google.ortools.linearsolver.MPSolver; import com.google.ortools.linearsolver.MPVariable; // [END import] /** Minimal Linear Programming example to showcase calling the solver. */ public final class SimpleLpProgram { public static void main(String[] args) { Loader.loadNativeLibraries(); // [START solver] // Create the linear solver with the GLOP backend. MPSolver solver = MPSolver.createSolver("GLOP"); if (solver == null) { System.out.println("Could not create solver SCIP"); return; } // [END solver] // [START variables] double infinity = java.lang.Double.POSITIVE_INFINITY; // Create the variables x and y. MPVariable x = solver.makeNumVar(0.0, infinity, "x"); MPVariable y = solver.makeNumVar(0.0, infinity, "y"); System.out.println("Number of variables = " + solver.numVariables()); // [END variables] // [START constraints] // x + 7 * y <= 17.5. MPConstraint c0 = solver.makeConstraint(-infinity, 17.5, "c0"); c0.setCoefficient(x, 1); c0.setCoefficient(y, 7); // x <= 3.5. MPConstraint c1 = solver.makeConstraint(-infinity, 3.5, "c1"); c1.setCoefficient(x, 1); c1.setCoefficient(y, 0); System.out.println("Number of constraints = " + solver.numConstraints()); // [END constraints] // [START objective] // Maximize x + 10 * y. MPObjective objective = solver.objective(); objective.setCoefficient(x, 1); objective.setCoefficient(y, 10); objective.setMaximization(); // [END objective] // [START solve] final MPSolver.ResultStatus resultStatus = solver.solve(); // [END solve] // [START print_solution] if (resultStatus == MPSolver.ResultStatus.OPTIMAL) { System.out.println("Solution:"); System.out.println("Objective value = " + objective.value()); System.out.println("x = " + x.solutionValue()); System.out.println("y = " + y.solutionValue()); } else { System.err.println("The problem does not have an optimal solution!"); } // [END print_solution] // [START advanced] System.out.println("\nAdvanced usage:"); System.out.println("Problem solved in " + solver.wallTime() + " milliseconds"); System.out.println("Problem solved in " + solver.iterations() + " iterations"); // [END advanced] } private SimpleLpProgram() {} } // [END program]
3,256
33.648936
83
java
or-tools
or-tools-master/ortools/linear_solver/samples/SimpleMipProgram.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Minimal example to call the MIP solver. // [START program] package com.google.ortools.linearsolver.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.linearsolver.MPConstraint; import com.google.ortools.linearsolver.MPObjective; import com.google.ortools.linearsolver.MPSolver; import com.google.ortools.linearsolver.MPVariable; // [END import] /** Minimal Mixed Integer Programming example to showcase calling the solver. */ public final class SimpleMipProgram { public static void main(String[] args) { Loader.loadNativeLibraries(); // [START solver] // Create the linear solver with the SCIP backend. MPSolver solver = MPSolver.createSolver("SCIP"); if (solver == null) { System.out.println("Could not create solver SCIP"); return; } // [END solver] // [START variables] double infinity = java.lang.Double.POSITIVE_INFINITY; // x and y are integer non-negative variables. MPVariable x = solver.makeIntVar(0.0, infinity, "x"); MPVariable y = solver.makeIntVar(0.0, infinity, "y"); System.out.println("Number of variables = " + solver.numVariables()); // [END variables] // [START constraints] // x + 7 * y <= 17.5. MPConstraint c0 = solver.makeConstraint(-infinity, 17.5, "c0"); c0.setCoefficient(x, 1); c0.setCoefficient(y, 7); // x <= 3.5. MPConstraint c1 = solver.makeConstraint(-infinity, 3.5, "c1"); c1.setCoefficient(x, 1); c1.setCoefficient(y, 0); System.out.println("Number of constraints = " + solver.numConstraints()); // [END constraints] // [START objective] // Maximize x + 10 * y. MPObjective objective = solver.objective(); objective.setCoefficient(x, 1); objective.setCoefficient(y, 10); objective.setMaximization(); // [END objective] // [START solve] final MPSolver.ResultStatus resultStatus = solver.solve(); // [END solve] // [START print_solution] if (resultStatus == MPSolver.ResultStatus.OPTIMAL) { System.out.println("Solution:"); System.out.println("Objective value = " + objective.value()); System.out.println("x = " + x.solutionValue()); System.out.println("y = " + y.solutionValue()); } else { System.err.println("The problem does not have an optimal solution!"); } // [END print_solution] // [START advanced] System.out.println("\nAdvanced usage:"); System.out.println("Problem solved in " + solver.wallTime() + " milliseconds"); System.out.println("Problem solved in " + solver.iterations() + " iterations"); System.out.println("Problem solved in " + solver.nodes() + " branch-and-bound nodes"); // [END advanced] } private SimpleMipProgram() {} } // [END program]
3,369
34.473684
90
java
or-tools
or-tools-master/ortools/linear_solver/samples/StiglerDiet.java
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START program] // The Stigler diet problem. package com.google.ortools.linearsolver.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.linearsolver.MPConstraint; import com.google.ortools.linearsolver.MPObjective; import com.google.ortools.linearsolver.MPSolver; import com.google.ortools.linearsolver.MPVariable; import java.util.ArrayList; import java.util.List; // [END import] /** Stigler diet example. */ public final class StiglerDiet { public static void main(String[] args) { Loader.loadNativeLibraries(); // [START data_model] // Nutrient minimums. List<Object[]> nutrients = new ArrayList<>(); nutrients.add(new Object[] {"Calories (kcal)", 3.0}); nutrients.add(new Object[] {"Protein (g)", 70.0}); nutrients.add(new Object[] {"Calcium (g)", 0.8}); nutrients.add(new Object[] {"Iron (mg)", 12.0}); nutrients.add(new Object[] {"Vitamin A (kIU)", 5.0}); nutrients.add(new Object[] {"Vitamin B1 (mg)", 1.8}); nutrients.add(new Object[] {"Vitamin B2 (mg)", 2.7}); nutrients.add(new Object[] {"Niacin (mg)", 18.0}); nutrients.add(new Object[] {"Vitamin C (mg)", 75.0}); List<Object[]> data = new ArrayList<>(); data.add(new Object[] {"Wheat Flour (Enriched)", "10 lb.", 36, new double[] {44.7, 1411, 2, 365, 0, 55.4, 33.3, 441, 0}}); data.add(new Object[] { "Macaroni", "1 lb.", 14.1, new double[] {11.6, 418, 0.7, 54, 0, 3.2, 1.9, 68, 0}}); data.add(new Object[] {"Wheat Cereal (Enriched)", "28 oz.", 24.2, new double[] {11.8, 377, 14.4, 175, 0, 14.4, 8.8, 114, 0}}); data.add(new Object[] { "Corn Flakes", "8 oz.", 7.1, new double[] {11.4, 252, 0.1, 56, 0, 13.5, 2.3, 68, 0}}); data.add(new Object[] { "Corn Meal", "1 lb.", 4.6, new double[] {36.0, 897, 1.7, 99, 30.9, 17.4, 7.9, 106, 0}}); data.add(new Object[] { "Hominy Grits", "24 oz.", 8.5, new double[] {28.6, 680, 0.8, 80, 0, 10.6, 1.6, 110, 0}}); data.add( new Object[] {"Rice", "1 lb.", 7.5, new double[] {21.2, 460, 0.6, 41, 0, 2, 4.8, 60, 0}}); data.add(new Object[] { "Rolled Oats", "1 lb.", 7.1, new double[] {25.3, 907, 5.1, 341, 0, 37.1, 8.9, 64, 0}}); data.add(new Object[] {"White Bread (Enriched)", "1 lb.", 7.9, new double[] {15.0, 488, 2.5, 115, 0, 13.8, 8.5, 126, 0}}); data.add(new Object[] {"Whole Wheat Bread", "1 lb.", 9.1, new double[] {12.2, 484, 2.7, 125, 0, 13.9, 6.4, 160, 0}}); data.add(new Object[] { "Rye Bread", "1 lb.", 9.1, new double[] {12.4, 439, 1.1, 82, 0, 9.9, 3, 66, 0}}); data.add(new Object[] { "Pound Cake", "1 lb.", 24.8, new double[] {8.0, 130, 0.4, 31, 18.9, 2.8, 3, 17, 0}}); data.add(new Object[] { "Soda Crackers", "1 lb.", 15.1, new double[] {12.5, 288, 0.5, 50, 0, 0, 0, 0, 0}}); data.add( new Object[] {"Milk", "1 qt.", 11, new double[] {6.1, 310, 10.5, 18, 16.8, 4, 16, 7, 177}}); data.add(new Object[] {"Evaporated Milk (can)", "14.5 oz.", 6.7, new double[] {8.4, 422, 15.1, 9, 26, 3, 23.5, 11, 60}}); data.add( new Object[] {"Butter", "1 lb.", 30.8, new double[] {10.8, 9, 0.2, 3, 44.2, 0, 0.2, 2, 0}}); data.add(new Object[] { "Oleomargarine", "1 lb.", 16.1, new double[] {20.6, 17, 0.6, 6, 55.8, 0.2, 0, 0, 0}}); data.add(new Object[] { "Eggs", "1 doz.", 32.6, new double[] {2.9, 238, 1.0, 52, 18.6, 2.8, 6.5, 1, 0}}); data.add(new Object[] {"Cheese (Cheddar)", "1 lb.", 24.2, new double[] {7.4, 448, 16.4, 19, 28.1, 0.8, 10.3, 4, 0}}); data.add(new Object[] { "Cream", "1/2 pt.", 14.1, new double[] {3.5, 49, 1.7, 3, 16.9, 0.6, 2.5, 0, 17}}); data.add(new Object[] { "Peanut Butter", "1 lb.", 17.9, new double[] {15.7, 661, 1.0, 48, 0, 9.6, 8.1, 471, 0}}); data.add(new Object[] { "Mayonnaise", "1/2 pt.", 16.7, new double[] {8.6, 18, 0.2, 8, 2.7, 0.4, 0.5, 0, 0}}); data.add(new Object[] {"Crisco", "1 lb.", 20.3, new double[] {20.1, 0, 0, 0, 0, 0, 0, 0, 0}}); data.add(new Object[] {"Lard", "1 lb.", 9.8, new double[] {41.7, 0, 0, 0, 0.2, 0, 0.5, 5, 0}}); data.add(new Object[] { "Sirloin Steak", "1 lb.", 39.6, new double[] {2.9, 166, 0.1, 34, 0.2, 2.1, 2.9, 69, 0}}); data.add(new Object[] { "Round Steak", "1 lb.", 36.4, new double[] {2.2, 214, 0.1, 32, 0.4, 2.5, 2.4, 87, 0}}); data.add( new Object[] {"Rib Roast", "1 lb.", 29.2, new double[] {3.4, 213, 0.1, 33, 0, 0, 2, 0, 0}}); data.add(new Object[] { "Chuck Roast", "1 lb.", 22.6, new double[] {3.6, 309, 0.2, 46, 0.4, 1, 4, 120, 0}}); data.add( new Object[] {"Plate", "1 lb.", 14.6, new double[] {8.5, 404, 0.2, 62, 0, 0.9, 0, 0, 0}}); data.add(new Object[] {"Liver (Beef)", "1 lb.", 26.8, new double[] {2.2, 333, 0.2, 139, 169.2, 6.4, 50.8, 316, 525}}); data.add(new Object[] { "Leg of Lamb", "1 lb.", 27.6, new double[] {3.1, 245, 0.1, 20, 0, 2.8, 3.9, 86, 0}}); data.add(new Object[] { "Lamb Chops (Rib)", "1 lb.", 36.6, new double[] {3.3, 140, 0.1, 15, 0, 1.7, 2.7, 54, 0}}); data.add(new Object[] { "Pork Chops", "1 lb.", 30.7, new double[] {3.5, 196, 0.2, 30, 0, 17.4, 2.7, 60, 0}}); data.add(new Object[] { "Pork Loin Roast", "1 lb.", 24.2, new double[] {4.4, 249, 0.3, 37, 0, 18.2, 3.6, 79, 0}}); data.add(new Object[] { "Bacon", "1 lb.", 25.6, new double[] {10.4, 152, 0.2, 23, 0, 1.8, 1.8, 71, 0}}); data.add(new Object[] { "Ham, smoked", "1 lb.", 27.4, new double[] {6.7, 212, 0.2, 31, 0, 9.9, 3.3, 50, 0}}); data.add(new Object[] { "Salt Pork", "1 lb.", 16, new double[] {18.8, 164, 0.1, 26, 0, 1.4, 1.8, 0, 0}}); data.add(new Object[] {"Roasting Chicken", "1 lb.", 30.3, new double[] {1.8, 184, 0.1, 30, 0.1, 0.9, 1.8, 68, 46}}); data.add(new Object[] { "Veal Cutlets", "1 lb.", 42.3, new double[] {1.7, 156, 0.1, 24, 0, 1.4, 2.4, 57, 0}}); data.add(new Object[] { "Salmon, Pink (can)", "16 oz.", 13, new double[] {5.8, 705, 6.8, 45, 3.5, 1, 4.9, 209, 0}}); data.add(new Object[] { "Apples", "1 lb.", 4.4, new double[] {5.8, 27, 0.5, 36, 7.3, 3.6, 2.7, 5, 544}}); data.add(new Object[] { "Bananas", "1 lb.", 6.1, new double[] {4.9, 60, 0.4, 30, 17.4, 2.5, 3.5, 28, 498}}); data.add( new Object[] {"Lemons", "1 doz.", 26, new double[] {1.0, 21, 0.5, 14, 0, 0.5, 0, 4, 952}}); data.add(new Object[] { "Oranges", "1 doz.", 30.9, new double[] {2.2, 40, 1.1, 18, 11.1, 3.6, 1.3, 10, 1998}}); data.add(new Object[] { "Green Beans", "1 lb.", 7.1, new double[] {2.4, 138, 3.7, 80, 69, 4.3, 5.8, 37, 862}}); data.add(new Object[] { "Cabbage", "1 lb.", 3.7, new double[] {2.6, 125, 4.0, 36, 7.2, 9, 4.5, 26, 5369}}); data.add(new Object[] { "Carrots", "1 bunch", 4.7, new double[] {2.7, 73, 2.8, 43, 188.5, 6.1, 4.3, 89, 608}}); data.add(new Object[] { "Celery", "1 stalk", 7.3, new double[] {0.9, 51, 3.0, 23, 0.9, 1.4, 1.4, 9, 313}}); data.add(new Object[] { "Lettuce", "1 head", 8.2, new double[] {0.4, 27, 1.1, 22, 112.4, 1.8, 3.4, 11, 449}}); data.add(new Object[] { "Onions", "1 lb.", 3.6, new double[] {5.8, 166, 3.8, 59, 16.6, 4.7, 5.9, 21, 1184}}); data.add(new Object[] { "Potatoes", "15 lb.", 34, new double[] {14.3, 336, 1.8, 118, 6.7, 29.4, 7.1, 198, 2522}}); data.add(new Object[] { "Spinach", "1 lb.", 8.1, new double[] {1.1, 106, 0, 138, 918.4, 5.7, 13.8, 33, 2755}}); data.add(new Object[] {"Sweet Potatoes", "1 lb.", 5.1, new double[] {9.6, 138, 2.7, 54, 290.7, 8.4, 5.4, 83, 1912}}); data.add(new Object[] {"Peaches (can)", "No. 2 1/2", 16.8, new double[] {3.7, 20, 0.4, 10, 21.5, 0.5, 1, 31, 196}}); data.add(new Object[] { "Pears (can)", "No. 2 1/2", 20.4, new double[] {3.0, 8, 0.3, 8, 0.8, 0.8, 0.8, 5, 81}}); data.add(new Object[] { "Pineapple (can)", "No. 2 1/2", 21.3, new double[] {2.4, 16, 0.4, 8, 2, 2.8, 0.8, 7, 399}}); data.add(new Object[] {"Asparagus (can)", "No. 2", 27.7, new double[] {0.4, 33, 0.3, 12, 16.3, 1.4, 2.1, 17, 272}}); data.add(new Object[] { "Green Beans (can)", "No. 2", 10, new double[] {1.0, 54, 2, 65, 53.9, 1.6, 4.3, 32, 431}}); data.add(new Object[] {"Pork and Beans (can)", "16 oz.", 7.1, new double[] {7.5, 364, 4, 134, 3.5, 8.3, 7.7, 56, 0}}); data.add(new Object[] { "Corn (can)", "No. 2", 10.4, new double[] {5.2, 136, 0.2, 16, 12, 1.6, 2.7, 42, 218}}); data.add(new Object[] { "Peas (can)", "No. 2", 13.8, new double[] {2.3, 136, 0.6, 45, 34.9, 4.9, 2.5, 37, 370}}); data.add(new Object[] { "Tomatoes (can)", "No. 2", 8.6, new double[] {1.3, 63, 0.7, 38, 53.2, 3.4, 2.5, 36, 1253}}); data.add(new Object[] {"Tomato Soup (can)", "10 1/2 oz.", 7.6, new double[] {1.6, 71, 0.6, 43, 57.9, 3.5, 2.4, 67, 862}}); data.add(new Object[] { "Peaches, Dried", "1 lb.", 15.7, new double[] {8.5, 87, 1.7, 173, 86.8, 1.2, 4.3, 55, 57}}); data.add(new Object[] { "Prunes, Dried", "1 lb.", 9, new double[] {12.8, 99, 2.5, 154, 85.7, 3.9, 4.3, 65, 257}}); data.add(new Object[] {"Raisins, Dried", "15 oz.", 9.4, new double[] {13.5, 104, 2.5, 136, 4.5, 6.3, 1.4, 24, 136}}); data.add(new Object[] { "Peas, Dried", "1 lb.", 7.9, new double[] {20.0, 1367, 4.2, 345, 2.9, 28.7, 18.4, 162, 0}}); data.add(new Object[] {"Lima Beans, Dried", "1 lb.", 8.9, new double[] {17.4, 1055, 3.7, 459, 5.1, 26.9, 38.2, 93, 0}}); data.add(new Object[] {"Navy Beans, Dried", "1 lb.", 5.9, new double[] {26.9, 1691, 11.4, 792, 0, 38.4, 24.6, 217, 0}}); data.add(new Object[] {"Coffee", "1 lb.", 22.4, new double[] {0, 0, 0, 0, 0, 4, 5.1, 50, 0}}); data.add(new Object[] {"Tea", "1/4 lb.", 17.4, new double[] {0, 0, 0, 0, 0, 0, 2.3, 42, 0}}); data.add( new Object[] {"Cocoa", "8 oz.", 8.6, new double[] {8.7, 237, 3, 72, 0, 2, 11.9, 40, 0}}); data.add(new Object[] { "Chocolate", "8 oz.", 16.2, new double[] {8.0, 77, 1.3, 39, 0, 0.9, 3.4, 14, 0}}); data.add(new Object[] {"Sugar", "10 lb.", 51.7, new double[] {34.9, 0, 0, 0, 0, 0, 0, 0, 0}}); data.add(new Object[] { "Corn Syrup", "24 oz.", 13.7, new double[] {14.7, 0, 0.5, 74, 0, 0, 0, 5, 0}}); data.add(new Object[] { "Molasses", "18 oz.", 13.6, new double[] {9.0, 0, 10.3, 244, 0, 1.9, 7.5, 146, 0}}); data.add(new Object[] {"Strawberry Preserves", "1 lb.", 20.5, new double[] {6.4, 11, 0.4, 7, 0.2, 0.2, 0.4, 3, 0}}); // [END data_model] // [START solver] // Create the linear solver with the GLOP backend. MPSolver solver = MPSolver.createSolver("GLOP"); if (solver == null) { System.out.println("Could not create solver GLOP"); return; } // [END solver] // [START variables] double infinity = java.lang.Double.POSITIVE_INFINITY; List<MPVariable> foods = new ArrayList<>(); for (int i = 0; i < data.size(); ++i) { foods.add(solver.makeNumVar(0.0, infinity, (String) data.get(i)[0])); } System.out.println("Number of variables = " + solver.numVariables()); // [END variables] // [START constraints] MPConstraint[] constraints = new MPConstraint[nutrients.size()]; for (int i = 0; i < nutrients.size(); ++i) { constraints[i] = solver.makeConstraint( (double) nutrients.get(i)[1], infinity, (String) nutrients.get(i)[0]); for (int j = 0; j < data.size(); ++j) { constraints[i].setCoefficient(foods.get(j), ((double[]) data.get(j)[3])[i]); } // constraints.add(constraint); } System.out.println("Number of constraints = " + solver.numConstraints()); // [END constraints] // [START objective] MPObjective objective = solver.objective(); for (int i = 0; i < data.size(); ++i) { objective.setCoefficient(foods.get(i), 1); } objective.setMinimization(); // [END objective] // [START solve] final MPSolver.ResultStatus resultStatus = solver.solve(); // [END solve] // [START print_solution] // Check that the problem has an optimal solution. if (resultStatus != MPSolver.ResultStatus.OPTIMAL) { System.err.println("The problem does not have an optimal solution!"); if (resultStatus == MPSolver.ResultStatus.FEASIBLE) { System.err.println("A potentially suboptimal solution was found."); } else { System.err.println("The solver could not solve the problem."); return; } } // Display the amounts (in dollars) to purchase of each food. double[] nutrientsResult = new double[nutrients.size()]; System.out.println("\nAnnual Foods:"); for (int i = 0; i < foods.size(); ++i) { if (foods.get(i).solutionValue() > 0.0) { System.out.println((String) data.get(i)[0] + ": $" + 365 * foods.get(i).solutionValue()); for (int j = 0; j < nutrients.size(); ++j) { nutrientsResult[j] += ((double[]) data.get(i)[3])[j] * foods.get(i).solutionValue(); } } } System.out.println("\nOptimal annual price: $" + 365 * objective.value()); System.out.println("\nNutrients per day:"); for (int i = 0; i < nutrients.size(); ++i) { System.out.println( nutrients.get(i)[0] + ": " + nutrientsResult[i] + " (min " + nutrients.get(i)[1] + ")"); } // [END print_solution] // [START advanced] System.out.println("\nAdvanced usage:"); System.out.println("Problem solved in " + solver.wallTime() + " milliseconds"); System.out.println("Problem solved in " + solver.iterations() + " iterations"); // [END advanced] } private StiglerDiet() {} } // [END program]
14,432
50.180851
100
java