### Build Examples with Bazel Source: https://developers.google.com/optimization/support/release_notes Build OR-Tools C++ examples using Bazel. Ensure Bazel version 0.4.5 or later is installed. Navigate to the `or-tools` directory and run the build command. ```bash bazel build examples/cpp/... ``` -------------------------------- ### Install .Net 6.0 SDK using Homebrew Source: https://developers.google.com/optimization/install/dotnet/binary_mac Install the .Net 6.0 SDK using Homebrew after Homebrew has been installed. ```bash brew cask install dotnet-sdk ``` -------------------------------- ### Install .Net 6.0 SDK Source: https://developers.google.com/optimization/install/dotnet/pkg_mac Install the .Net 6.0 SDK using Homebrew by running the `brew cask install dotnet-sdk` command in the Terminal. Test the installation with `dotnet --info`. ```bash brew cask install dotnet-sdk ``` ```bash dotnet --info ``` -------------------------------- ### VRP with Start and End Locations using Routing Solver Source: https://developers.google.com/optimization/examples Presents a Vehicle Routing Problem (VRP) example specifying start and end locations for vehicles. ```text Routing | Routing solver | Vehicle Routing Problem with start and end locations | | ``` -------------------------------- ### Build and Run .NET Example Source: https://developers.google.com/optimization/install/dotnet/pkg_mac Build and run the .NET OR-Tools example application. ```bash dotnet build -c Release ``` ```bash dotnet run -c Release ``` -------------------------------- ### Navigate to Java Examples Directory Source: https://developers.google.com/optimization/install/java/pkg_linux Changes the current directory to the examples directory within the cloned `java_or-tools` repository. ```bash cd java_or-tools ``` -------------------------------- ### C++ VRP with Custom Starts and Ends Source: https://developers.google.com/optimization/routing/routing_tasks Sets custom start and end nodes for vehicles in a Vehicle Routing Problem. Requires a DataModel and RoutingIndexManager setup. ```cpp #include "ortools/constraint_solver/routing_index_manager.h" #include "ortools/constraint_solver/routing_model.h" #include "ortools/constraint_solver/routing_parameters.h" #include "ortools/base/logging.h" namespace operations_research { // Data model for the routing problem. struct DataModel { std::vector> distance_matrix = { {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}, }; int num_vehicles = 4; std::vector starts = {1, 2, 15, 16}; std::vector ends = {0, 0, 0, 0}; }; void PrintSolution(const DataModel& data, const RoutingIndexManager& manager, const RoutingModel& routing, const Assignment& solution) { LOG(INFO) << "Objective: " << solution.objective_value() << std::endl; int64_t max_route_distance = 0; for (int vehicle_id = 0; vehicle_id < data.num_vehicles; ++vehicle_id) { int64_t route_distance = 0; int64_t route_load_max = 0; int64_t from_index = solution.Start(vehicle_id); std::ostringstream route; while (routing.IsEnd(from_index)) { int64_t previous_index = from_index; from_index = solution.Value(routing.NextVar(from_index)); route_distance += routing.GetArcCostForVehicle(previous_index, from_index, int64_t{vehicle_id}); } LOG(INFO) << route.str() << manager.IndexToNode(from_index).value(); LOG(INFO) << "Distance of the route: " << route_distance << "m"; max_route_distance = std::max(route_distance, max_route_distance); } LOG(INFO) << "Maximum of the route distances: " << max_route_distance << "m"; LOG(INFO) << ""; LOG(INFO) << "Problem solved in " << routing.solver()->wall_time() << "ms"; } void VrpStartsEnds() { // Instantiate the data problem. DataModel data; // Create Routing Index Manager RoutingIndexManager manager(data.distance_matrix.size(), data.num_vehicles, data.starts, data.ends); // Create Routing Model. RoutingModel routing(manager); // Create and register a transit callback. const int transit_callback_index = routing.RegisterTransitCallback( [&data, &manager](const int64_t from_index, const int64_t to_index) -> int64_t { // Convert from routing variable Index to distance matrix NodeIndex. const int from_node = manager.IndexToNode(from_index).value(); const int to_node = manager.IndexToNode(to_index).value(); return data.distance_matrix[from_node][to_node]; }); // Define cost of each arc. routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index); // Add Distance constraint. routing.AddDimension(transit_callback_index, 0, 2000, /*fix_start_cumul_to_zero=*/true, "Distance"); routing.GetMutableDimension("Distance")->SetGlobalSpanCostCoefficient(100); // Setting first solution heuristic. RoutingSearchParameters searchParameters = DefaultRoutingSearchParameters(); searchParameters.set_first_solution_strategy( FirstSolutionStrategy::PATH_CHEAPEST_ARC); // Solve the problem. const Assignment* solution = routing.SolveWithParameters(searchParameters); // Print solution on console. PrintSolution(data, manager, routing, *solution); } } // namespace operations_research int main(int /*argc*/, char* /*argv*/[]) { operations_research::VrpStartsEnds(); return EXIT_SUCCESS; } ``` -------------------------------- ### VRP with Drop Nodes Example Source: https://developers.google.com/optimization/routing/penalties Demonstrates a Vehicle Routing Problem where some nodes can be dropped. This C# example includes data model setup, routing, and solution printing. ```csharp using System; using System.Collections.Generic; using Google.OrTools.ConstraintSolver; using Google.Protobuf.WellKnownTypes; // Duration /// /// Minimal Vrp with drop nodes. /// public class VrpDropNodes { class DataModel { public 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 long[] Demands = { 0, 1, 1, 3, 6, 3, 6, 8, 8, 1, 2, 1, 2, 6, 6, 8, 8 }; public long[] VehicleCapacities = { 15, 15, 15, 15 }; public int VehicleNumber = 4; public int Depot = 0; }; /// /// Print the solution. /// static void PrintSolution(in DataModel data, in RoutingModel routing, in RoutingIndexManager manager, in Assignment solution) { Console.WriteLine($"Objective {solution.ObjectiveValue()}:"); // Inspect solution. // Display dropped nodes. string droppedNodes = "Dropped nodes:"; for (int index = 0; index < routing.Size(); ++index) { if (routing.IsStart(index) || routing.IsEnd(index)) { continue; } if (solution.Value(routing.NextVar(index)) == index) { droppedNodes += " " + manager.IndexToNode(index); } } Console.WriteLine("{0}", droppedNodes); // Inspect solution. long totalDistance = 0; long totalLoad = 0; for (int i = 0; i < data.VehicleNumber; ++i) { if (!routing.IsVehicleUsed(solution, i)) { continue; } Console.WriteLine("Route for Vehicle {0}:", i); long routeDistance = 0; long routeLoad = 0; var index = routing.Start(i); while (routing.IsEnd(index) == false) { long nodeIndex = manager.IndexToNode(index); routeLoad += data.Demands[nodeIndex]; Console.Write("{0} Load({1}) -> ", nodeIndex, routeLoad); var previousIndex = index; index = solution.Value(routing.NextVar(index)); routeDistance += routing.GetArcCostForVehicle(previousIndex, index, 0); } Console.WriteLine("{0}", manager.IndexToNode((int)index)); Console.WriteLine("Distance of the route: {0}m", routeDistance); totalDistance += routeDistance; totalLoad += routeLoad; } Console.WriteLine("Total Distance of all routes: {0}m", totalDistance); Console.WriteLine("Total Load of all routes: {0}m", totalLoad); } public static void Main(String[] args) { // Instantiate the data problem. DataModel data = new DataModel(); // Create Routing Index Manager RoutingIndexManager manager = new RoutingIndexManager(data.DistanceMatrix.GetLength(0), data.VehicleNumber, data.Depot); ``` -------------------------------- ### Navigate to the OR-Tools Examples Directory Source: https://developers.google.com/optimization/install/dotnet/pkg_windows Change your current directory to the root of the cloned OR-Tools .NET examples repository. ```bash cd dotnet_or-tools ``` -------------------------------- ### Complete Routing Model Setup (Python) Source: https://developers.google.com/optimization/routing/penalties Demonstrates the complete setup of a routing model in Python, including dimension registration, disjunctions, search parameters, and solving the problem. ```python from_node = manager.IndexToNode(from_index) return data["demands"][from_node] demand_callback_index = routing.RegisterUnaryTransitCallback(demand_callback) routing.AddDimensionWithVehicleCapacity( demand_callback_index, 0, # null capacity slack data["vehicle_capacities"], # vehicle maximum capacities True, # start cumul to zero "Capacity", ) # Allow to drop nodes. penalty = 1000 for node in range(1, len(data["distance_matrix"]): routing.AddDisjunction([manager.NodeToIndex(node)], penalty) # Setting first solution heuristic. search_parameters = pywrapcp.DefaultRoutingSearchParameters() search_parameters.first_solution_strategy = ( routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC ) search_parameters.local_search_metaheuristic = ( routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH ) search_parameters.time_limit.FromSeconds(1) # Solve the problem. assignment = routing.SolveWithParameters(search_parameters) # Print solution on console. if assignment: print_solution(data, manager, routing, assignment) if __name__ == "__main__": main() ``` -------------------------------- ### Validate C++ Installation on Windows Source: https://developers.google.com/optimization/install/cpp/binary_windows Run this command in the x64 Native Tools Command Prompt from the extracted OR-Tools directory to test your C++ installation. Successful execution of examples confirms readiness. ```bash make test ``` -------------------------------- ### VRP Drop Nodes Example in Java Source: https://developers.google.com/optimization/routing/penalties This Java code provides a complete example of setting up and solving a Vehicle Routing Problem where nodes can be dropped. It includes data model, routing setup, and solver parameters. ```java package com.google.ortools.constraintsolver.samples; 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; /** Minimal VRP.*/ public class VrpDropNodes { private static final Logger logger = Logger.getLogger(VrpDropNodes.class.getName()); 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}, }; public final int[] demands = {0, 1, 1, 2, 4, 1, 2, 4, 2, 8, 8, 1, 2, 1, 2, 4, 4}; public final int[] vehicleCapacities = {15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15}; public final int numVehicles = 1; public final int depot = 0; } public static void main(String[] args) { Loader.loadNativeLibrary(); // Instantiate the data problem. DataModel data = new DataModel(); // Create Routing Index Manager RoutingIndexManager manager = new RoutingIndexManager(data.distanceMatrix.length, data.numVehicles, data.depot); // Create Routing Model. RoutingModel routing = new RoutingModel(manager); // Create and register a transit callback. int transitCallbackIndex = routing.registerTransitCallback((long fromIndex, long toIndex) -> { // Convert from routing variable Index to distance matrix NodeIndex. int fromNode = manager.indexToNode(fromIndex); int toNode = manager.indexToNode(toIndex); return data.distanceMatrix[fromNode][toNode]; }); // Define cost of each arc. routing.setArcCostEvaluatorOfAllVehicles(transitCallbackIndex); // Add Capacity constraint. int demandCallbackIndex = routing.registerUnaryTransitCallback((long fromIndex) -> { // Convert from routing variable Index to demand 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); } // Setting first solution heuristic. RoutingSearchParameters searchParameters = routing.newSearchParameters().toBuilder().setFirstSolutionStrategy(FirstSolutionStrategy.PATH_CHEAPEST_ARC).setLocalSearchMetaheuristic(LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH).setTimeLimit(Duration.newBuilder().setSeconds(1)).build(); // Solve the problem. Assignment solution = routing.solveWithParameters(searchParameters); // Print solution on console. printSolution(data, manager, routing, solution); } static void printSolution(DataModel data, RoutingIndexManager manager, RoutingModel routing, Assignment solution) { long totalDistance = 0; long totalLoad = 0; logger.info("Objective: " + solution.objectiveValue()); for (int i = 0; i < data.numVehicles; ++i) { long index = routing.start(i); long routeDistance = 0; long routeLoad = 0; String route = "Route for vehicle " + i + ":\n"; while (!routing.isEnd(index)) { long previousIndex = index; index = solution.value(routing.nextVar(index)); routeDistance += routing.getArcCostForVehicle(previousIndex, index, i); routeLoad += data.demands[manager.indexToNode(index)]; } route += manager.indexToNode(index) + " Load(" + routeLoad + ")\n"; logger.info(route); logger.info("Distance of the route: " + routeDistance + "m\n"); logger.info("Load of the route: " + routeLoad + "\n"); totalDistance += routeDistance; totalLoad += routeLoad; } logger.info("Total distance of all routes: " + totalDistance + "m\n"); logger.info("Total load of all routes: " + totalLoad + "\n"); } } ``` -------------------------------- ### Build the OR-Tools .NET Example Project Source: https://developers.google.com/optimization/install/dotnet/pkg_windows Compile the OR-Tools .NET example project in Release mode using the .NET CLI. ```bash dotnet build -c Release ``` -------------------------------- ### Navigate to OR-Tools Examples Directory Source: https://developers.google.com/optimization/install/python/pkg_linux Changes the current directory to the cloned OR-Tools examples directory. ```bash cd python_or-tools ``` -------------------------------- ### Python Linear Programming Example Source: https://developers.google.com/optimization/lp/glop Solves a linear programming problem using the GLOP solver in Python. Ensure the ortools library is installed. ```python from ortools.linear_solver import pywraplp def LinearProgrammingExample(): """Linear programming sample.""" # Instantiate a Glop solver, naming it LinearExample. solver = pywraplp.Solver.CreateSolver("GLOP") if not solver: return # Create the two variables and let them take on any non-negative value. x = solver.NumVar(0, solver.infinity(), "x") y = solver.NumVar(0, solver.infinity(), "y") print("Number of variables =", solver.NumVariables()) # Constraint 0: x + 2y <= 14. solver.Add(x + 2 * y <= 14.0) # Constraint 1: 3x - y >= 0. solver.Add(3 * x - y >= 0.0) # Constraint 2: x - y <= 2. solver.Add(x - y <= 2.0) print("Number of constraints =", solver.NumConstraints()) # Objective function: 3x + 4y. solver.Maximize(3 * x + 4 * y) # Solve the system. print(f"Solving with {solver.SolverVersion()}") status = solver.Solve() if status == pywraplp.Solver.OPTIMAL: print("Solution:") print(f"Objective value = {solver.Objective().Value():0.1f}") print(f"x = {x.solution_value():0.1f}") print(f"y = {y.solution_value():0.1f}") else: print("The problem does not have an optimal solution.") print("\nAdvanced usage:") print(f"Problem solved in {solver.wall_time():d} milliseconds") print(f"Problem solved in {solver.iterations():d} iterations") LinearProgrammingExample() ``` -------------------------------- ### Build .Net OR-Tools Example Project Source: https://developers.google.com/optimization/install/dotnet/pkg_linux Compiles the OR-Tools .Net project in Release configuration. ```bash dotnet build -c Release ``` -------------------------------- ### Test the OR-Tools source code Source: https://developers.google.com/optimization/install/cpp/source_linux Run tests to verify that OR-Tools is compiled and running correctly. Successful execution of all examples indicates a proper installation. ```bash cmake --build build --config Release --target test -v ``` -------------------------------- ### Install .Net SDK on OpenSUSE Source: https://developers.google.com/optimization/install/dotnet/pkg_linux Installs the .Net 6 SDK on OpenSUSE after configuring the repository. ```bash sudo zypper install -y dotnet-sdk-6.0 ``` -------------------------------- ### TSP Solution with Guided Local Search Source: https://developers.google.com/optimization/routing/tsp This is an example of a TSP solution obtained after applying the GUIDED_LOCAL_SEARCH strategy. It shows the objective value and the sequence of visited nodes. ```text Objective: 2672 Route: 0 -> 3 -> 276 -> 4 -> 5 -> 6 -> 8 -> 7 -> 9 -> 10 -> 11 -> 14 -> 12 -> 13 -> 23 -> 22 -> 24 -> 21 -> 25 -> 26 -> 27 -> 28 -> 125 -> 126 -> 127 -> 20 -> 19 -> 130 -> 129 -> 128 -> 153 -> 154 -> 152 -> 155 -> 151 -> 150 -> 177 -> 176 -> 175 -> 180 -> 161 -> 160 -> 174 -> 159 -> 158 -> 157 -> 156 -> 118 -> 119 -> 120 -> 121 -> 122 -> 123 -> 124 -> 29 -> 30 -> 31 -> 32 -> 33 -> 34 -> 35 -> 36 -> 37 -> 38 -> 39 -> 40 -> 41 -> 42 -> 59 -> 60 -> 58 -> 43 -> 44 -> 45 -> 46 -> 47 -> 48 -> 49 -> 50 -> 51 -> 52 -> 53 -> 54 -> 55 -> 56 -> 57 -> 67 -> 68 -> 66 -> 69 -> 70 -> 71 -> 72 -> 73 -> 75 -> 74 -> 76 -> 77 -> 78 -> 80 -> 81 -> 88 -> 79 -> 92 -> 93 -> 94 -> 95 -> 96 -> 97 -> 98 -> 99 -> 100 -> 101 -> 102 -> 91 -> 90 -> 89 -> 108 -> 111 -> 87 -> 82 -> 83 -> 86 -> 112 -> 115 -> 85 -> 84 -> 64 -> 65 -> 63 -> 62 -> 61 -> 117 -> 116 -> 114 -> 113 -> 110 -> 109 -> 107 -> 103 -> 104 -> 105 -> 106 -> 173 -> 172 -> 171 -> 170 -> 169 -> 168 -> 167 -> 166 -> 165 -> 164 -> 163 -> 162 -> 187 -> 188 -> 189 -> 190 -> 191 -> 192 -> 185 -> 186 -> 184 -> 183 -> 182 -> 181 -> 179 -> 178 -> 149 -> 148 -> 138 -> 137 -> 136 -> 266 -> 267 -> 135 -> 134 -> 268 -> 269 -> 133 -> 132 -> 131 -> 18 -> 17 -> 16 -> 15 -> 270 -> 271 -> 272 -> 273 -> 274 -> 275 -> 259 -> 258 -> 260 -> 261 -> 262 -> 263 -> 264 -> 265 -> 139 -> 140 -> 147 -> 146 -> 141 -> 142 -> 145 -> 144 -> 198 -> 197 -> 196 -> 193 -> 194 -> 195 -> 200 -> 201 -> 199 -> 143 -> 202 -> 203 -> 204 -> 205 -> 206 -> 207 -> 252 -> 253 -> 256 -> 257 -> 255 -> 254 -> 251 -> 208 -> 209 -> 210 -> 211 -> 212 -> 213 -> 214 -> 215 -> 216 -> 217 -> 218 -> 219 -> 220 -> 221 -> 222 -> 223 -> 224 -> 225 -> 226 -> 227 -> 232 -> 233 -> 234 -> 235 -> 236 -> 237 -> 230 -> 231 -> 228 -> 229 -> 250 -> 245 -> 238 -> 239 -> 240 -> 241 -> 242 -> 243 -> 244 -> 246 -> 249 -> 248 -> 247 -> 277 -> 278 -> 2 -> 279 -> 1 -> 0 ``` -------------------------------- ### Read Initial Solution from Routes Source: https://developers.google.com/optimization/routing/routing_tasks Reads an initial solution from a predefined set of routes. This can be used to guide the solver or to provide a starting point for more complex search strategies. ```csharp // Get initial solution from routes. Assignment initialSolution = routing.ReadAssignmentFromRoutes(data.InitialRoutes, true); // Print initial solution on console. Console.WriteLine("Initial solution:"); PrintSolution(data, routing, manager, initialSolution); ``` -------------------------------- ### Clone the OR-Tools .NET Example Repository Source: https://developers.google.com/optimization/install/dotnet/pkg_windows Clone the OR-Tools .NET examples repository to your local machine. Use the specified branch and depth for efficiency. ```bash git clone -b v9.12 --depth 1 https://github.com/or-tools/dotnet_or-tools ``` -------------------------------- ### Configure .Net repository on OpenSUSE Source: https://developers.google.com/optimization/install/dotnet/pkg_linux Sets up the Microsoft package repository for .Net on OpenSUSE. ```bash sudo zypper install libicu sudo rpm --import https://packages.microsoft.com/keys/microsoft.asc wget https://packages.microsoft.com/config/opensuse/15/prod.repo sudo mv prod.repo /etc/zypp/repos.d/microsoft-prod.repo sudo chown root:root /etc/zypp/repos.d/microsoft-prod.repo ``` -------------------------------- ### C# TSP Solver Source: https://developers.google.com/optimization/routing/tsp A complete C# program for solving the Traveling Salesperson Problem. This example utilizes a predefined set of locations and demonstrates the setup of the OR-Tools routing model. ```csharp using System; using System.Collections.Generic; using Google.OrTools.ConstraintSolver; /// /// Minimal TSP. /// A description of the problem can be found here: /// http://en.wikipedia.org/wiki/Travelling_salesperson_problem. /// public class TspCircuitBoard { class DataModel { public 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 }, }; } public static void Main(string[] args) { DataModel data = new DataModel(); RoutingIndexManager manager = new RoutingIndexManager(data.Locations.Length, 1, 0); RoutingModel routing = new RoutingModel(manager); // Define cost of each arc. Func distanceCallback = ( long fromIndex, long toIndex) => { // Convert from routing variable Index to user NodeIndex. var fromNode = manager.IndexToNode(fromIndex); var toNode = manager.IndexToNode(toIndex); return (long)Math.Sqrt(Math.Pow(data.Locations[fromNode, 0] - data.Locations[toNode, 0], 2) + Math.Pow(data.Locations[fromNode, 1] - data.Locations[toNode, 1], 2)); }; // Add distance callback to the model. int distanceCallbackIndex = routing.RegisterTransitCallback(distanceCallback); routing.SetArcCostEvaluatorOfAllVehicles(distanceCallbackIndex); // Setting first solution heuristic. RoutingSearchParameters searchParameters = RoutingSearchParameters.Builder.NewBuilder() .SetFirstSolutionStrategy(FirstSolutionStrategy.Types.Value.PATH_CHEAPEST_ARC) .Build(); // Solve the problem. Assignment solution = routing.SolveWithParameters(searchParameters); // Print solution on console. // PrintSolution(routing, manager, solution); } } ``` -------------------------------- ### Python Requests POST Example Source: https://developers.google.com/optimization/service/scheduling/shift_generation_example Use this snippet to make a POST request to an API endpoint with custom headers and timeouts. Ensure the `requests` library is installed and the `api_key` and `end_point` variables are defined. ```python session = requests.Session() client_deadline_seconds = 60 server_deadline_seconds = 0.95 * client_deadline_seconds session.headers = { "Content-Type": "application/json", "Connection": "keep-alive", "Keep-Alive": f"timeout={client_deadline_seconds}, max=1", "X-Server-Timeout": f"{server_deadline_seconds}", "X-Goog-Api-Key": api_key, } response = session.post(end_point, json=json_request, timeout=client_deadline_seconds) ``` -------------------------------- ### Run the OR-Tools .NET Example Application Source: https://developers.google.com/optimization/install/dotnet/pkg_windows Execute the compiled OR-Tools .NET application in Release mode using the .NET CLI. ```bash dotnet run -c Release ``` -------------------------------- ### Python TSP Solver Setup Source: https://developers.google.com/optimization/routing/tsp Sets up the routing model, defines a distance callback, and configures the search parameters for solving a TSP in Python. This code is typically used as a starting point for TSP problems. ```python def main(): """Entry point of the program.""" # Instantiate the data problem. data = create_data_model() # Create the routing index manager. manager = pywrapcp.RoutingIndexManager( len(data["locations"]), data["num_vehicles"], data["depot"], ) # Create Routing Model. routing = pywrapcp.RoutingModel(manager) distance_matrix = compute_euclidean_distance_matrix(data["locations"]) def distance_callback(from_index, to_index): """Returns the distance between the two nodes.""" # Convert from routing variable Index to distance matrix NodeIndex. from_node = manager.IndexToNode(from_index) to_node = manager.IndexToNode(to_index) return distance_matrix[from_node][to_node] transit_callback_index = routing.RegisterTransitCallback(distance_callback) # Define cost of each arc. routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index) # Setting first solution heuristic. search_parameters = pywrapcp.DefaultRoutingSearchParameters() search_parameters.first_solution_strategy = ( routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC ) # Solve the problem. solution = routing.SolveWithParameters(search_parameters) # Print solution on console. if solution: print_solution(manager, routing, solution) if __name__ == "__main__": main() ``` -------------------------------- ### Run the OR-Tools Java Example Source: https://developers.google.com/optimization/install/java/pkg_windows Execute the OR-Tools Java example application using Maven. This command should be run from the root directory of the cloned repository after building. ```bash mvn exec:java ```