Google OR-Tools v9.11
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
christofides.h
Go to the documentation of this file.
1// Copyright 2010-2024 Google LLC
2// Licensed under the Apache License, Version 2.0 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//
6// http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14// ChristofidesPathSolver computes an approximate solution to the Traveling
15// Salesman Problen using the Christofides algorithm (c.f.
16// https://en.wikipedia.org/wiki/Christofides_algorithm).
17// Note that the algorithm guarantees finding a solution within 3/2 of the
18// optimum when using minimum weight perfect matching in the matching phase.
19// The complexity of the algorithm is dominated by the complexity of the
20// matching algorithm: O(n^2 * log(n)) if minimal matching is used, or at least
21// O(n^3) or O(nmlog(n)) otherwise, depending on the implementation of the
22// perfect matching algorithm used, where n is the number of nodes and m is the
23// number of edges of the subgraph induced by odd-degree nodes of the minimum
24// spanning tree.
25
26#ifndef OR_TOOLS_GRAPH_CHRISTOFIDES_H_
27#define OR_TOOLS_GRAPH_CHRISTOFIDES_H_
28
29#include <cstdint>
30#include <functional>
31#include <string>
32#include <utility>
33#include <vector>
34
35#include "absl/status/status.h"
36#include "absl/status/statusor.h"
39#include "ortools/graph/graph.h"
43#include "ortools/linear_solver/linear_solver.pb.h"
45
46namespace operations_research {
47
48using ::util::CompleteGraph;
49
50template <typename CostType, typename ArcIndex = int64_t,
51 typename NodeIndex = int32_t,
52 typename CostFunction = std::function<CostType(NodeIndex, NodeIndex)>>
54 public:
55 enum class MatchingAlgorithm {
57#if defined(USE_CBC) || defined(USE_SCIP)
59#endif // defined(USE_CBC) || defined(USE_SCIP)
61 };
62 ChristofidesPathSolver(NodeIndex num_nodes, CostFunction costs);
63
64 // Sets the matching algorithm to use. A minimum weight perfect matching
65 // (MINIMUM_WEIGHT_MATCHING) guarantees the 3/2 upper bound to the optimal
66 // solution. A minimal weight perfect matching (MINIMAL_WEIGHT_MATCHING)
67 // finds a locally minimal weight matching which does not offer any bound
68 // guarantee but, as of 1/2017, is orders of magnitude faster than the
69 // minimum matching.
70 // By default, MINIMAL_WEIGHT_MATCHING is selected.
71 // TODO(user): Change the default when minimum matching gets faster.
73 matching_ = matching;
74 }
75
76 // Returns the cost of the approximate TSP tour.
77 CostType TravelingSalesmanCost();
78
79 // Returns the approximate TSP tour.
80 std::vector<NodeIndex> TravelingSalesmanPath();
81
82 // Runs the Christofides algorithm. Returns true if a solution was found,
83 // false otherwise.
84 bool Solve();
85
86 private:
87 int64_t SafeAdd(int64_t a, int64_t b) { return CapAdd(a, b); }
88
89 // Matching algorithm to use.
90 MatchingAlgorithm matching_;
91
92 // The complete graph on the nodes of the problem.
93 CompleteGraph<NodeIndex, ArcIndex> graph_;
94
95 // Function returning the cost between nodes of the problem.
96 const CostFunction costs_;
97
98 // The cost of the computed TSP path.
99 CostType tsp_cost_;
100
101 // The path of the computed TSP,
102 std::vector<NodeIndex> tsp_path_;
103
104 // True if the TSP has been solved, false otherwise.
105 bool solved_;
106};
107
108// Computes a minimum weight perfect matching on an undirected graph.
109template <typename WeightFunctionType, typename GraphType>
110absl::StatusOr<std::vector<
111 std::pair<typename GraphType::NodeIndex, typename GraphType::NodeIndex>>>
113 const WeightFunctionType& weight) {
114 using ArcIndex = typename GraphType::ArcIndex;
115 using NodeIndex = typename GraphType::NodeIndex;
116 MinCostPerfectMatching matching(graph.num_nodes());
117 for (NodeIndex tail : graph.AllNodes()) {
118 for (const ArcIndex arc : graph.OutgoingArcs(tail)) {
119 const NodeIndex head = graph.Head(arc);
120 // Adding both arcs is redundant for MinCostPerfectMatching.
121 if (tail < head) {
122 matching.AddEdgeWithCost(tail, head, weight(arc));
123 }
124 }
125 }
128 return absl::InvalidArgumentError("Perfect matching failed");
129 }
130 std::vector<std::pair<NodeIndex, NodeIndex>> match;
131 for (NodeIndex tail : graph.AllNodes()) {
132 const NodeIndex head = matching.Match(tail);
133 if (tail < head) { // Both arcs are matched for a given edge, we keep one.
134 match.emplace_back(tail, head);
135 }
136 }
137 return match;
138}
139
140#if defined(USE_CBC) || defined(USE_SCIP)
141// Computes a minimum weight perfect matching on an undirected graph using a
142// Mixed Integer Programming model.
143// TODO(user): Handle infeasible cases if this algorithm is used outside of
144// Christofides.
145template <typename WeightFunctionType, typename GraphType>
146absl::StatusOr<std::vector<
147 std::pair<typename GraphType::NodeIndex, typename GraphType::NodeIndex>>>
149 const WeightFunctionType& weight) {
150 using ArcIndex = typename GraphType::ArcIndex;
151 using NodeIndex = typename GraphType::NodeIndex;
152 MPModelProto model;
153 model.set_maximize(false);
154 // The model is composed of Boolean decision variables to select matching arcs
155 // and constraints ensuring that each node appears in exactly one selected
156 // arc. The objective is to minimize the sum of the weights of selected arcs.
157 // It is assumed the graph is symmetrical.
158 std::vector<int> variable_indices(graph.num_arcs(), -1);
159 for (NodeIndex node : graph.AllNodes()) {
160 // Creating arc-selection Boolean variable.
161 for (const ArcIndex arc : graph.OutgoingArcs(node)) {
162 const NodeIndex head = graph.Head(arc);
163 if (node < head) {
164 variable_indices[arc] = model.variable_size();
165 MPVariableProto* const arc_var = model.add_variable();
166 arc_var->set_lower_bound(0);
167 arc_var->set_upper_bound(1);
168 arc_var->set_is_integer(true);
169 arc_var->set_objective_coefficient(weight(arc));
170 }
171 }
172 // Creating matching constraint:
173 // for all node i, sum(j) arc(i,j) + sum(j) arc(j,i) = 1
174 MPConstraintProto* const one_of_ct = model.add_constraint();
175 one_of_ct->set_lower_bound(1);
176 one_of_ct->set_upper_bound(1);
177 }
178 for (NodeIndex node : graph.AllNodes()) {
179 for (const ArcIndex arc : graph.OutgoingArcs(node)) {
180 const NodeIndex head = graph.Head(arc);
181 if (node < head) {
182 const int arc_var = variable_indices[arc];
183 DCHECK_GE(arc_var, 0);
184 MPConstraintProto* one_of_ct = model.mutable_constraint(node);
185 one_of_ct->add_var_index(arc_var);
186 one_of_ct->add_coefficient(1);
187 one_of_ct = model.mutable_constraint(head);
188 one_of_ct->add_var_index(arc_var);
189 one_of_ct->add_coefficient(1);
190 }
191 }
192 }
193#if defined(USE_SCIP)
194 MPSolver mp_solver("MatchingWithSCIP",
196#elif defined(USE_CBC)
197 MPSolver mp_solver("MatchingWithCBC",
199#endif
200 std::string error;
201 mp_solver.LoadModelFromProto(model, &error);
202 MPSolver::ResultStatus status = mp_solver.Solve();
203 if (status != MPSolver::OPTIMAL) {
204 return absl::InvalidArgumentError("MIP-based matching failed");
205 }
206 MPSolutionResponse response;
207 mp_solver.FillSolutionResponseProto(&response);
208 std::vector<std::pair<NodeIndex, NodeIndex>> matching;
209 for (ArcIndex arc = 0; arc < variable_indices.size(); ++arc) {
210 const int arc_var = variable_indices[arc];
211 if (arc_var >= 0 && response.variable_value(arc_var) > .9) {
212 DCHECK_GE(response.variable_value(arc_var), 1.0 - 1e-4);
213 matching.emplace_back(graph.Tail(arc), graph.Head(arc));
214 }
215 }
216 return matching;
217}
218#endif // defined(USE_CBC) || defined(USE_SCIP)
219
220template <typename CostType, typename ArcIndex, typename NodeIndex,
221 typename CostFunction>
223 ChristofidesPathSolver(NodeIndex num_nodes, CostFunction costs)
224 : matching_(MatchingAlgorithm::MINIMAL_WEIGHT_MATCHING),
225 graph_(num_nodes),
226 costs_(std::move(costs)),
227 tsp_cost_(0),
228 solved_(false) {}
229
230template <typename CostType, typename ArcIndex, typename NodeIndex,
231 typename CostFunction>
232CostType ChristofidesPathSolver<CostType, ArcIndex, NodeIndex,
233 CostFunction>::TravelingSalesmanCost() {
234 if (!solved_) {
235 bool const ok = Solve();
236 DCHECK(ok);
237 }
238 return tsp_cost_;
239}
240
241template <typename CostType, typename ArcIndex, typename NodeIndex,
242 typename CostFunction>
243std::vector<NodeIndex> ChristofidesPathSolver<
244 CostType, ArcIndex, NodeIndex, CostFunction>::TravelingSalesmanPath() {
245 if (!solved_) {
246 const bool ok = Solve();
247 DCHECK(ok);
248 }
249 return tsp_path_;
250}
251
252template <typename CostType, typename ArcIndex, typename NodeIndex,
253 typename CostFunction>
255 CostFunction>::Solve() {
256 const NodeIndex num_nodes = graph_.num_nodes();
257 tsp_path_.clear();
258 tsp_cost_ = 0;
259 if (num_nodes == 1) {
260 tsp_path_ = {0, 0};
261 }
262 if (num_nodes <= 1) {
263 return true;
264 }
265 // Compute Minimum Spanning Tree.
266 const std::vector<ArcIndex> mst =
268 return costs_(graph_.Tail(arc), graph_.Head(arc));
269 });
270 // Detect odd degree nodes.
271 std::vector<NodeIndex> degrees(num_nodes, 0);
272 for (ArcIndex arc : mst) {
273 degrees[graph_.Tail(arc)]++;
274 degrees[graph_.Head(arc)]++;
275 }
276 std::vector<NodeIndex> odd_degree_nodes;
277 for (int i = 0; i < degrees.size(); ++i) {
278 if (degrees[i] % 2 != 0) {
279 odd_degree_nodes.push_back(i);
280 }
281 }
282 // Find minimum-weight perfect matching on odd-degree-node complete graph.
283 // TODO(user): Make this code available as an independent algorithm.
284 const NodeIndex reduced_size = odd_degree_nodes.size();
285 DCHECK_NE(0, reduced_size);
286 CompleteGraph<NodeIndex, ArcIndex> reduced_graph(reduced_size);
287 std::vector<std::pair<NodeIndex, NodeIndex>> closure_arcs;
288 switch (matching_) {
289 case MatchingAlgorithm::MINIMUM_WEIGHT_MATCHING: {
290 auto result = ComputeMinimumWeightMatching(
291 reduced_graph, [this, &reduced_graph,
292 &odd_degree_nodes](CompleteGraph<>::ArcIndex arc) {
293 return costs_(odd_degree_nodes[reduced_graph.Tail(arc)],
294 odd_degree_nodes[reduced_graph.Head(arc)]);
295 });
296 if (!result.ok()) {
297 return false;
298 }
299 result->swap(closure_arcs);
300 break;
301 }
302#if defined(USE_CBC) || defined(USE_SCIP)
303 case MatchingAlgorithm::MINIMUM_WEIGHT_MATCHING_WITH_MIP: {
305 reduced_graph, [this, &reduced_graph,
306 &odd_degree_nodes](CompleteGraph<>::ArcIndex arc) {
307 return costs_(odd_degree_nodes[reduced_graph.Tail(arc)],
308 odd_degree_nodes[reduced_graph.Head(arc)]);
309 });
310 if (!result.ok()) {
311 return false;
312 }
313 result->swap(closure_arcs);
314 break;
315 }
316#endif // defined(USE_CBC) || defined(USE_SCIP)
317 case MatchingAlgorithm::MINIMAL_WEIGHT_MATCHING: {
318 // TODO(user): Cost caching was added and can gain up to 20% but
319 // increases memory usage; see if we can avoid caching.
320 std::vector<ArcIndex> ordered_arcs(reduced_graph.num_arcs());
321 std::vector<CostType> ordered_arc_costs(reduced_graph.num_arcs(), 0);
322 for (const ArcIndex arc : reduced_graph.AllForwardArcs()) {
323 ordered_arcs[arc] = arc;
324 ordered_arc_costs[arc] =
325 costs_(odd_degree_nodes[reduced_graph.Tail(arc)],
326 odd_degree_nodes[reduced_graph.Head(arc)]);
327 }
328 std::sort(ordered_arcs.begin(), ordered_arcs.end(),
329 [&ordered_arc_costs](ArcIndex arc_a, ArcIndex arc_b) {
330 return ordered_arc_costs[arc_a] < ordered_arc_costs[arc_b];
331 });
332 std::vector<bool> touched_nodes(reduced_size, false);
333 for (ArcIndex arc_index = 0; closure_arcs.size() * 2 < reduced_size;
334 ++arc_index) {
335 const ArcIndex arc = ordered_arcs[arc_index];
336 const NodeIndex tail = reduced_graph.Tail(arc);
337 const NodeIndex head = reduced_graph.Head(arc);
338 if (head != tail && !touched_nodes[tail] && !touched_nodes[head]) {
339 touched_nodes[tail] = true;
340 touched_nodes[head] = true;
341 closure_arcs.emplace_back(tail, head);
342 }
343 }
344 break;
345 }
346 }
347 // Build Eulerian path on minimum spanning tree + closing edges from matching
348 // and extract a solution to the Traveling Salesman from the path by skipping
349 // duplicate nodes.
351 num_nodes, closure_arcs.size() + mst.size());
352 for (ArcIndex arc : mst) {
353 egraph.AddArc(graph_.Tail(arc), graph_.Head(arc));
354 }
355 for (const auto arc : closure_arcs) {
356 egraph.AddArc(odd_degree_nodes[arc.first], odd_degree_nodes[arc.second]);
357 }
358 std::vector<bool> touched(num_nodes, false);
359 DCHECK(IsEulerianGraph(egraph));
360 for (const NodeIndex node : BuildEulerianTourFromNode(egraph, 0)) {
361 if (touched[node]) continue;
362 touched[node] = true;
363 tsp_cost_ = SafeAdd(tsp_cost_,
364 tsp_path_.empty() ? 0 : costs_(tsp_path_.back(), node));
365 tsp_path_.push_back(node);
366 }
367 tsp_cost_ =
368 SafeAdd(tsp_cost_, tsp_path_.empty() ? 0 : costs_(tsp_path_.back(), 0));
369 tsp_path_.push_back(0);
370 solved_ = true;
371 return true;
372}
373} // namespace operations_research
374
375#endif // OR_TOOLS_GRAPH_CHRISTOFIDES_H_
ChristofidesPathSolver(NodeIndex num_nodes, CostFunction costs)
void SetMatchingAlgorithm(MatchingAlgorithm matching)
std::vector< NodeIndex > TravelingSalesmanPath()
Returns the approximate TSP tour.
CostType TravelingSalesmanCost()
Returns the cost of the approximate TSP tour.
ResultStatus Solve()
Solves the problem using the default parameter values.
MPSolverResponseStatus LoadModelFromProto(const MPModelProto &input_model, std::string *error_message, bool clear_names=true)
--— Methods using protocol buffers --—
@ SCIP_MIXED_INTEGER_PROGRAMMING
Recommended default value for MIP problems.
void FillSolutionResponseProto(MPSolutionResponse *response) const
Encodes the current solution in a solution response protocol buffer.
void AddEdgeWithCost(int tail, int head, int64_t cost)
@ OPTIMAL
A perfect matching with min-cost has been found.
ArcIndexType AddArc(NodeIndexType tail, NodeIndexType head)
Definition graph.h:1553
int64_t b
Definition table.cc:45
int64_t a
Definition table.cc:44
GraphType graph
absl::Status status
Definition g_gurobi.cc:44
GRBmodel * model
int arc
In SWIG mode, we don't want anything besides these top-level includes.
bool IsEulerianGraph(const Graph &graph, bool assume_connectivity=true)
Returns true if a graph is Eulerian, aka all its nodes are of even degree.
int64_t CapAdd(int64_t x, int64_t y)
absl::StatusOr< std::vector< std::pair< typename GraphType::NodeIndex, typename GraphType::NodeIndex > > > ComputeMinimumWeightMatchingWithMIP(const GraphType &graph, const WeightFunctionType &weight)
std::vector< NodeIndex > BuildEulerianTourFromNode(const Graph &graph, NodeIndex root, bool assume_connectivity=true)
std::vector< typename Graph::ArcIndex > BuildPrimMinimumSpanningTree(const Graph &graph, const ArcValue &arc_value)
absl::StatusOr< std::vector< std::pair< typename GraphType::NodeIndex, typename GraphType::NodeIndex > > > ComputeMinimumWeightMatching(const GraphType &graph, const WeightFunctionType &weight)
Computes a minimum weight perfect matching on an undirected graph.
STL namespace.
trees with all degrees equal w the current value of degrees
int64_t weight
Definition pack.cc:510
int head
int tail