Fix clang-format in examples/

This commit is contained in:
Corentin Le Molgat
2022-02-16 16:19:26 +01:00
parent f4136a40d6
commit 985b6a9239
14 changed files with 170 additions and 171 deletions

View File

@@ -16,15 +16,15 @@ using System;
using Google.OrTools.ConstraintSolver;
/// <summary>
/// Vehicles Routing Problem (VRP) with Time Windows, with the difference that we'll add a fixed penalty for lateness, as opposed to a linear penalty based on how late it is.
/// Example is inspired by scheduling items which have contractual deadlines.
/// Code based on https://developers.google.com/optimization/routing/vrptw#program
/// Vehicles Routing Problem (VRP) with Time Windows, with the difference that we'll add a fixed penalty for lateness,
/// as opposed to a linear penalty based on how late it is. Example is inspired by scheduling items which have
/// contractual deadlines. Code based on https://developers.google.com/optimization/routing/vrptw#program
/// </summary>
public class VrpTimeWindowFixedPenalty
{
class DataModel
{
public long[,] TimeMatrix = {
class DataModel
{
public 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 },
@@ -43,7 +43,7 @@ public class VrpTimeWindowFixedPenalty
{ 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 long[,] TimeWindows = {
public long[,] TimeWindows = {
{ 0, 5 }, // depot
{ 7, 12 }, // 1
{ 10, 15 }, // 2
@@ -62,108 +62,109 @@ public class VrpTimeWindowFixedPenalty
{ 10, 15 }, // 15
{ 11, 15 }, // 16
};
public int VehicleNumber = 4;
public int Depot = 0;
};
public int VehicleNumber = 4;
public int Depot = 0;
};
/// <summary>
/// Print the solution.
/// </summary>
static void PrintSolution(in DataModel data, in RoutingModel routing, in RoutingIndexManager manager,
in Assignment solution)
{
RoutingDimension timeDimension = routing.GetMutableDimension("Time");
// Inspect solution.
long totalTime = 0;
for (int i = 0; i < data.VehicleNumber; ++i)
/// <summary>
/// Print the solution.
/// </summary>
static void PrintSolution(in DataModel data, in RoutingModel routing, in RoutingIndexManager manager,
in Assignment solution)
{
Console.WriteLine("Route for Vehicle {0}:", i);
var index = routing.Start(i);
while (routing.IsEnd(index) == false)
{
var timeVar = timeDimension.CumulVar(index);
Console.Write("{0} Time({1},{2}) -> ", manager.IndexToNode(index), solution.Min(timeVar),
solution.Max(timeVar));
index = solution.Value(routing.NextVar(index));
}
var endTimeVar = timeDimension.CumulVar(index);
Console.WriteLine("{0} Time({1},{2})", manager.IndexToNode(index), solution.Min(endTimeVar),
solution.Max(endTimeVar));
Console.WriteLine("Time of the route: {0}min", solution.Min(endTimeVar));
totalTime += solution.Min(endTimeVar);
}
Console.WriteLine("Total time of all routes: {0}min", totalTime);
}
public static void Main(String[] args)
{
// Instantiate the data problem.
DataModel data = new DataModel();
// Create Routing Index Manager
RoutingIndexManager manager =
new RoutingIndexManager(data.TimeMatrix.GetLength(0), data.VehicleNumber, 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.
var fromNode = manager.IndexToNode(fromIndex);
var toNode = manager.IndexToNode(toIndex);
return data.TimeMatrix[fromNode, toNode];
});
// Define cost of each arc.
routing.SetArcCostEvaluatorOfAllVehicles(transitCallbackIndex);
// Add Distance 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");
routing.AddConstantDimensionWithSlack(0, // transit var 0 for all
data.TimeMatrix.GetLength(0), // max value is every item being late
1, // slack is 0 or 1 based on lateness
true, // start cumul to zero
"Late");
RoutingDimension lateDimension = routing.GetMutableDimension("Late");
// Add time window constraints for each location except depot.
for (int i = 1; i < data.TimeWindows.GetLength(0); ++i)
{
long index = manager.NodeToIndex(i);
var isLate = timeDimension.CumulVar(index) > data.TimeWindows[i, 1];
// set the slack var to 1 if late
routing.solver().MakeEquality(isLate, lateDimension.SlackVar(index));
RoutingDimension timeDimension = routing.GetMutableDimension("Time");
// Inspect solution.
long totalTime = 0;
for (int i = 0; i < data.VehicleNumber; ++i)
{
Console.WriteLine("Route for Vehicle {0}:", i);
var index = routing.Start(i);
while (routing.IsEnd(index) == false)
{
var timeVar = timeDimension.CumulVar(index);
Console.Write("{0} Time({1},{2}) -> ", manager.IndexToNode(index), solution.Min(timeVar),
solution.Max(timeVar));
index = solution.Value(routing.NextVar(index));
}
var endTimeVar = timeDimension.CumulVar(index);
Console.WriteLine("{0} Time({1},{2})", manager.IndexToNode(index), solution.Min(endTimeVar),
solution.Max(endTimeVar));
Console.WriteLine("Time of the route: {0}min", solution.Min(endTimeVar));
totalTime += solution.Min(endTimeVar);
}
Console.WriteLine("Total time of all routes: {0}min", totalTime);
}
// Instantiate route start and end times to produce feasible times.
for (int i = 0; i < data.VehicleNumber; ++i)
public static void Main(String[] args)
{
// add a fixed penalty for each late item
long penalty = 1000;
lateDimension.SetCumulVarSoftUpperBound(routing.End(0), 0, penalty);
// Instantiate the data problem.
DataModel data = new DataModel();
routing.AddVariableMinimizedByFinalizer(lateDimension.CumulVar(routing.End(i)));
// Create Routing Index Manager
RoutingIndexManager manager =
new RoutingIndexManager(data.TimeMatrix.GetLength(0), data.VehicleNumber, 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.
var fromNode = manager.IndexToNode(fromIndex);
var toNode = manager.IndexToNode(toIndex);
return data.TimeMatrix[fromNode, toNode];
});
// Define cost of each arc.
routing.SetArcCostEvaluatorOfAllVehicles(transitCallbackIndex);
// Add Distance 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");
routing.AddConstantDimensionWithSlack(0, // transit var 0 for all
data.TimeMatrix.GetLength(0), // max value is every item being late
1, // slack is 0 or 1 based on lateness
true, // start cumul to zero
"Late");
RoutingDimension lateDimension = routing.GetMutableDimension("Late");
// Add time window constraints for each location except depot.
for (int i = 1; i < data.TimeWindows.GetLength(0); ++i)
{
long index = manager.NodeToIndex(i);
var isLate = timeDimension.CumulVar(index) > data.TimeWindows[i, 1];
// set the slack var to 1 if late
routing.solver().MakeEquality(isLate, lateDimension.SlackVar(index));
}
// Instantiate route start and end times to produce feasible times.
for (int i = 0; i < data.VehicleNumber; ++i)
{
// add a fixed penalty for each late item
long penalty = 1000;
lateDimension.SetCumulVarSoftUpperBound(routing.End(0), 0, penalty);
routing.AddVariableMinimizedByFinalizer(lateDimension.CumulVar(routing.End(i)));
}
// Setting first solution heuristic.
RoutingSearchParameters searchParameters =
operations_research_constraint_solver.DefaultRoutingSearchParameters();
searchParameters.FirstSolutionStrategy = FirstSolutionStrategy.Types.Value.PathCheapestArc;
// Solve the problem.
Assignment solution = routing.SolveWithParameters(searchParameters);
// Print solution on console.
PrintSolution(data, routing, manager, solution);
}
// Setting first solution heuristic.
RoutingSearchParameters searchParameters =
operations_research_constraint_solver.DefaultRoutingSearchParameters();
searchParameters.FirstSolutionStrategy = FirstSolutionStrategy.Types.Value.PathCheapestArc;
// Solve the problem.
Assignment solution = routing.SolveWithParameters(searchParameters);
// Print solution on console.
PrintSolution(data, routing, manager, solution);
}
}

View File

@@ -160,12 +160,13 @@ void LocationContainer::AddRandomLocation(int64_t x_max, int64_t y_max,
}
}
int64_t LocationContainer::ManhattanDistance(NodeIndex from, NodeIndex to) const {
int64_t LocationContainer::ManhattanDistance(NodeIndex from,
NodeIndex to) const {
return locations_[from].DistanceTo(locations_[to]);
}
int64_t LocationContainer::NegManhattanDistance(NodeIndex from,
NodeIndex to) const {
NodeIndex to) const {
return -ManhattanDistance(from, to);
}
@@ -179,7 +180,8 @@ bool LocationContainer::SameLocation(NodeIndex node1, NodeIndex node2) const {
}
return false;
}
int64_t LocationContainer::SameLocationFromIndex(int64_t node1, int64_t node2) const {
int64_t LocationContainer::SameLocationFromIndex(int64_t node1,
int64_t node2) const {
// The direct conversion from constraint model indices to routing model
// nodes is correct because the depot is node 0.
// TODO(user): Fetch proper indices from routing model.
@@ -190,7 +192,8 @@ LocationContainer::Location::Location() : x_(0), y_(0) {}
LocationContainer::Location::Location(int64_t x, int64_t y) : x_(x), y_(y) {}
int64_t LocationContainer::Location::DistanceTo(const Location& location) const {
int64_t LocationContainer::Location::DistanceTo(
const Location& location) const {
return Abs(x_ - location.x_) + Abs(y_ - location.y_);
}
@@ -220,8 +223,8 @@ void RandomDemand::Initialize() {
if (order == depot_) {
demand_[order] = 0;
} else {
demand_[order] =
kDemandMin + absl::Uniform(randomizer, 0, kDemandMax - kDemandMin + 1);
demand_[order] = kDemandMin + absl::Uniform(randomizer, 0,
kDemandMax - kDemandMin + 1);
}
}
}
@@ -249,7 +252,7 @@ StopServiceTimePlusTransition::StopServiceTimePlusTransition(
transition_time_(std::move(transition_time)) {}
int64_t StopServiceTimePlusTransition::Compute(NodeIndex from,
NodeIndex to) const {
NodeIndex to) const {
return location_container_.SameLocation(from, to)
? 0
: stop_time_ + transition_time_(from, to);

View File

@@ -68,7 +68,7 @@ int32_t GetSeed() {
// Sample function.
int64_t MyDistance(RoutingIndexManager::NodeIndex from,
RoutingIndexManager::NodeIndex to) {
RoutingIndexManager::NodeIndex to) {
// Put your distance code here.
return (from + to).value(); // for instance
}
@@ -84,7 +84,8 @@ class RandomMatrix {
for (RoutingIndexManager::NodeIndex from(0); from < size_; ++from) {
for (RoutingIndexManager::NodeIndex to(0); to < size_; ++to) {
if (to != from) {
matrix_[MatrixIndex(from, to)] = absl::Uniform(randomizer, 0, kDistanceMax);
matrix_[MatrixIndex(from, to)] =
absl::Uniform(randomizer, 0, kDistanceMax);
} else {
matrix_[MatrixIndex(from, to)] = 0LL;
}
@@ -92,13 +93,13 @@ class RandomMatrix {
}
}
int64_t Distance(RoutingIndexManager::NodeIndex from,
RoutingIndexManager::NodeIndex to) const {
RoutingIndexManager::NodeIndex to) const {
return matrix_[MatrixIndex(from, to)];
}
private:
int64_t MatrixIndex(RoutingIndexManager::NodeIndex from,
RoutingIndexManager::NodeIndex to) const {
RoutingIndexManager::NodeIndex to) const {
return (from * size_ + to).value();
}
std::unique_ptr<int64_t[]> matrix_;
@@ -144,9 +145,10 @@ void Tsp() {
int64_t forbidden_connections = 0;
while (forbidden_connections <
absl::GetFlag(FLAGS_tsp_random_forbidden_connections)) {
const int64_t from = absl::Uniform(randomizer, 0, absl::GetFlag(FLAGS_tsp_size) - 1);
const int64_t from =
absl::Uniform(randomizer, 0, absl::GetFlag(FLAGS_tsp_size) - 1);
const int64_t to =
absl::Uniform(randomizer, 0 , absl::GetFlag(FLAGS_tsp_size) - 1) + 1;
absl::Uniform(randomizer, 0, absl::GetFlag(FLAGS_tsp_size) - 1) + 1;
if (routing.NextVar(from)->Contains(to)) {
LOG(INFO) << "Forbidding connection " << from << " -> " << to;
routing.NextVar(from)->RemoveValue(to);

View File

@@ -143,7 +143,8 @@ static void UncapacitatedFacilityLocation(
// Set options and solve
if (optimization_problem_type != MPSolver::SCIP_MIXED_INTEGER_PROGRAMMING) {
if (!solver.SetNumThreads(8).ok()) {
LOG(INFO) << "Could not set parallelism for " << optimization_problem_type;
LOG(INFO) << "Could not set parallelism for "
<< optimization_problem_type;
}
}
solver.EnableOutput();

View File

@@ -87,7 +87,7 @@ int64_t RemainingCapacities::GetLoadCost(
++resource_id) {
const int load_cost_weight = resources_.at(resource_id).load_cost_weight;
const int64_t delta = safety_remaining_capacities.at(resource_id) -
remaining_capacities_.at(resource_id);
remaining_capacities_.at(resource_id);
load_cost += load_cost_weight * std::max(delta, int64_t{0});
}
return load_cost;
@@ -252,7 +252,7 @@ int64_t SolutionChecker::GetObjectiveCost() const {
const int64_t service_move_cost = GetServiceMoveCost();
const int64_t machine_move_cost = GetMachineMoveCost();
const int64_t total_cost = load_cost + balance_cost + process_move_cost +
service_move_cost + machine_move_cost;
service_move_cost + machine_move_cost;
return total_cost;
}

View File

@@ -211,7 +211,8 @@ public final class ConstraintSolverTest {
assertEquals(0, countApply.intValue());
assertEquals(0, countRefute.intValue());
final Decision decision = solver.makeDecision(
(Solver s) -> {
(Solver s)
-> {
assertEquals(s.model_name(), modelName);
countApply.addAndGet(1);
},
@@ -267,8 +268,7 @@ public final class ConstraintSolverTest {
assertEquals(0, countApply.intValue());
assertEquals(0, countRefute.intValue());
final DecisionBuilder db = new ActionDecisionBuilder(
(Solver s) -> countApply.addAndGet(1),
(Solver s) -> countRefute.addAndGet(1));
(Solver s) -> countApply.addAndGet(1), (Solver s) -> countRefute.addAndGet(1));
solver.newSearch(db);
assertTrue(solver.nextSolution());
assertEquals(1, countApply.intValue());

View File

@@ -31,10 +31,8 @@ public final class FlowTest {
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[][] 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);

View File

@@ -40,15 +40,15 @@ public final class InitTest {
@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);
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
@@ -58,7 +58,7 @@ public final class InitTest {
final int major = v.getMajorNumber();
final int minor = v.getMinorNumber();
final int patch = v.getPatchNumber();
final String version = v.getVersionString();
final String version = v.getVersionString();
final String check = major + "." + minor + "." + patch;
assertEquals(check, version);
}

View File

@@ -33,18 +33,12 @@ public final class KnapsackSolverTest {
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[] 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);

View File

@@ -479,10 +479,11 @@ public final class LinearSolverTest {
.setObjectiveCoefficient(1.0)
.build();
modelBuilder.addVariable(variable);
final MPModelRequest request = MPModelRequest.newBuilder()
.setModel(modelBuilder.build())
.setSolverType(MPModelRequest.SolverType.GLOP_LINEAR_PROGRAMMING)
.build();
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);

View File

@@ -236,12 +236,11 @@ public final class RoutingSolverTest {
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);
});
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);
@@ -290,11 +289,10 @@ public final class RoutingSolverTest {
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);
});
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);

View File

@@ -11,9 +11,10 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#include "absl/strings/str_cat.h"
#include "ortools/init/init.h"
#include "absl/strings/str_cat.h"
namespace operations_research {
void TestLogging() {
LOG(INFO) << "Test Logging";

View File

@@ -19,8 +19,7 @@
namespace operations_research {
void SolveAndPrint(MPSolver& solver, std::vector<MPVariable*> variables,
std::vector<MPConstraint*> constraints,
bool is_continuous) {
std::vector<MPConstraint*> constraints, bool is_continuous) {
LOG(INFO) << "Number of variables = " << solver.NumVariables();
LOG(INFO) << "Number of constraints = " << solver.NumConstraints();
@@ -47,7 +46,7 @@ void SolveAndPrint(MPSolver& solver, std::vector<MPVariable*> variables,
const std::vector<double> activities = solver.ComputeConstraintActivities();
for (const auto& i : constraints) {
LOG(INFO) << i->name() << ": dual value = " << i->dual_value()
<< " activity = " << activities[i->index()];
<< " activity = " << activities[i->index()];
}
}
}

View File

@@ -85,13 +85,13 @@ class RandomMatrix {
}
}
int64_t Distance(RoutingModel::NodeIndex from,
RoutingModel::NodeIndex to) const {
RoutingModel::NodeIndex to) const {
return matrix_[MatrixIndex(from, to)];
}
private:
int64_t MatrixIndex(RoutingModel::NodeIndex from,
RoutingModel::NodeIndex to) const {
RoutingModel::NodeIndex to) const {
return (from * size_ + to).value();
}
std::unique_ptr<int64_t[]> matrix_;
@@ -129,7 +129,8 @@ int main(int argc, char** argv) {
int64_t forbidden_connections = 0;
while (forbidden_connections <
absl::GetFlag(FLAGS_tsp_random_forbidden_connections)) {
const int64_t from = randomizer.Uniform(absl::GetFlag(FLAGS_tsp_size) - 1);
const int64_t from =
randomizer.Uniform(absl::GetFlag(FLAGS_tsp_size) - 1);
const int64_t to =
randomizer.Uniform(absl::GetFlag(FLAGS_tsp_size) - 1) + 1;
if (routing.NextVar(from)->Contains(to)) {