From b948cc5c1e8fee9f44e4019c4c76ee5db7b9a59c Mon Sep 17 00:00:00 2001 From: Andrew Teirney Date: Mon, 20 Jan 2020 21:08:03 +1300 Subject: [PATCH 1/2] feat: add support for adding extra cost variables to the cost function --- ortools/constraint_solver/routing.cc | 3 +++ ortools/constraint_solver/routing.h | 10 ++++++++++ 2 files changed, 13 insertions(+) diff --git a/ortools/constraint_solver/routing.cc b/ortools/constraint_solver/routing.cc index 6a71e578a32..2a3eab0232a 100644 --- a/ortools/constraint_solver/routing.cc +++ b/ortools/constraint_solver/routing.cc @@ -2147,6 +2147,9 @@ void RoutingModel::CloseModelWithParameters( for (int i = 0; i < same_vehicle_costs_.size(); ++i) { cost_elements.push_back(CreateSameVehicleCost(i)); } + // Add in any extra cost elements + cost_elements.insert(cost_elements.end(), extra_costs_.begin(), extra_costs_.end()); + cost_ = solver_->MakeSum(cost_elements)->Var(); cost_->set_name("Cost"); diff --git a/ortools/constraint_solver/routing.h b/ortools/constraint_solver/routing.h index bfa8e9c71ab..21857acee48 100644 --- a/ortools/constraint_solver/routing.h +++ b/ortools/constraint_solver/routing.h @@ -1072,6 +1072,15 @@ class RoutingModel { } extra_filters_.push_back(filter); } + // Adds a custom extra cost to the list of cost elements that make up the + // objective value + void AddExtraCost(IntVar* intVar) { + CHECK(intVar != nullptr); + if (closed_) { + LOG(WARNING) << "Model is closed, cost addition will be ignored."; + } + extra_costs_.push_back(intVar); + } /// Model inspection. /// Returns the variable index of the starting node of a vehicle route. @@ -1679,6 +1688,7 @@ class RoutingModel { std::vector filters_; std::vector feasibility_filters_; std::vector extra_filters_; + std::vector extra_costs_; #ifndef SWIG std::vector> finalizer_variable_cost_pairs_; std::vector> finalizer_variable_target_pairs_; From c8b6d5f3f94d4d620b5df045fab35837ce73e746 Mon Sep 17 00:00:00 2001 From: Andrew Teirney Date: Mon, 20 Jan 2020 21:12:45 +1300 Subject: [PATCH 2/2] feat: rename the AddExtraCost method in the Java SWIG bindings to be lowerCamelCase --- ortools/constraint_solver/java/routing.i | 1 + 1 file changed, 1 insertion(+) diff --git a/ortools/constraint_solver/java/routing.i b/ortools/constraint_solver/java/routing.i index 76d7c9ceaa2..3b8b6254d0a 100644 --- a/ortools/constraint_solver/java/routing.i +++ b/ortools/constraint_solver/java/routing.i @@ -145,6 +145,7 @@ import java.util.function.LongUnaryOperator; %rename (compactAssignment) RoutingModel::CompactAssignment; %rename (computeLowerBound) RoutingModel::ComputeLowerBound; %rename (costVar) RoutingModel::CostVar; +%rename (addExtraCost) RoutingModel::AddExtraCost; %rename (costsAreHomogeneousAcrossVehicles) RoutingModel::CostsAreHomogeneousAcrossVehicles; %rename (debugOutputAssignment) RoutingModel::DebugOutputAssignment; %rename (end) RoutingModel::End;