C++ Reference

C++ Reference: Graph

one_tree_lower_bound.h
Go to the documentation of this file.
1 // Copyright 2010-2022 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 // An implementation of the Held-Karp symmetric Traveling Salesman (TSP) lower
15 // bound algorithm, inspired by "Estimating the Held-Karp lower bound for the
16 // geometric TSP" by Christine L. Valenzuela and Antonia J. Jones, European
17 // Journal of Operational Research, Volume 102, Issue 1, 1 October 1997,
18 // Pages 157-175.
19 //
20 // The idea is to compute minimum 1-trees to evaluate a lower bound to the
21 // corresponding TSP. A minimum 1-tree is a minimum spanning tree on all nodes
22 // but one, to which are added the two shortest edges from the left-out node to
23 // the nodes of the spanning tree. The sum of the cost of the edges of the
24 // minimum 1-tree is a lower bound to the cost of the TSP.
25 // In order to improve (increase) this lower bound, the idea is to add weights
26 // to each nodes, weights which are added to the cost function used when
27 // computing the 1-tree. If weight[i] is the weight of node i, the cost function
28 // therefore becomes weighed_cost(i,j) = cost(i,j) + weight[i] + weight[j]. One
29 // can see that w = weighed_cost(minimum 1-tree) - Sum(2 * weight[i])
30 // = cost(minimum 1-tree) + Sum(weight[i] * (degree[i] - 2))
31 // is a valid lower bound to the TSP:
32 // 1) let T be the set of 1-trees on the nodes;
33 // 2) let U be the set of tours on the nodes; U is a subset of T (tours are
34 // 1-trees with all degrees equal to 2), therefore:
35 // min(t in T) Cost(t) <= min(t in U) Cost(t)
36 // and
37 // min(t in T) WeighedCost(t) <= min(t in U) WeighedCost(t)
38 // 3) weighed_cost(i,j) = cost(i,j) + weight[i] + weight[j], therefore:
39 // for all t in T, WeighedCost(t) = Cost(t) + Sum(weight[i] * degree[i])
40 // and
41 // for all i in U, WeighedCost(t) = Cost(t) + Sum(weight[i] * 2)
42 // 4) let t* in U s.t. WeighedCost(t*) = min(t in U) WeighedCost(t), therefore:
43 // min(t in T) (Cost(t) + Sum(weight[i] * degree[i]))
44 // <= Cost(t*) + Sum(weight[i] * 2)
45 // and
46 // min(t in T) (Cost(t) + Sum(weight[i] * (degree[i] - 2))) <= Cost(t*)
47 // and
48 // cost(minimum 1-tree) + Sum(weight[i] * (degree[i] - 2)) <= Cost(t*)
49 // and
50 // w <= Cost(t*)
51 // 5) because t* is also the tour minimizing Cost(t) with t in U (weights do not
52 // affect the optimality of a tour), Cost(t*) is the cost of the optimal
53 // solution to the TSP and w is a lower bound to this cost.
54 //
55 // The best lower bound is the one for which weights maximize w. Intuitively as
56 // degrees get closer to 2 the minimum 1-trees gets closer to a tour.
57 //
58 // At each iteration m, weights are therefore updated as follows:
59 // weight(m+1)[i] = weight(m)[i] + step(m) * (degree(m)[i] - 2)
60 // where degree(m)[i] is the degree of node i in the 1-tree at iteration i,
61 // step(m) is a subgradient optimization step.
62 //
63 // This implementation uses two variants of Held-Karp's initial subgradient
64 // optimization iterative estimation approach described in "The
65 // traveling-salesman problem and minimum spanning trees: Part I and II", by
66 // Michael Held and Richard M. Karp, Operations Research Vol. 18,
67 // No. 6 (Nov. - Dec., 1970), pp. 1138-1162 and Mathematical Programming (1971).
68 //
69 // The first variant comes from Volgenant, T., and Jonker, R. (1982), "A branch
70 // and bound algorithm for the symmetric traveling salesman problem based on the
71 // 1-tree relaxation", European Journal of Operational Research. 9:83-89.".
72 // It suggests using
73 // step(m) = (1.0 * (m - 1) * (2 * M - 5) / (2 * (M - 1))) * step1
74 // - (m - 2) * step1
75 // + (0.5 * (m - 1) * (m - 2) / ((M - 1) * (M - 2))) * step1
76 // where M is the maximum number of iterations and step1 is initially set to
77 // L / (2 * number of nodes), where L is the un-weighed cost of the 1-tree;
78 // step1 is updated each time a better w is found. The intuition is to have a
79 // positive decreasing step which is equal to 0 after M iterations; Volgenant
80 // and Jonker suggest that:
81 // step(m) - 2 * step(m-1) + t(m-2) = constant,
82 // step(M) = 0
83 // and
84 // step(1) - step(2) = 3 * (step(M-1) - step(M)).
85 // The step(m) formula above derives from this recursive formulation.
86 // This is the default algorithm used in this implementation.
87 //
88 // The second variant comes from Held, M., Wolfe, P., and Crowder, H. P. (1974),
89 // "Validation of subgradient optimization", Mathematical Programming 6:62-88.
90 // It derives from the original Held-Karp formulation:
91 // step(m) = lambda(m) * (wlb - w(m)) / Sum((degree[i] - 2)^2),
92 // where wlb is a lower bound to max(w(m)) and lambda(m) in [0, 2].
93 // Help-Karp prove that
94 // if w(m') > w(m) and 0 < step < 2 * (w(m') - w(m))/norm(degree(m) - 2)^2,
95 // then weight(m+1) is closer to w' than w from which they derive the above
96 // formula.
97 // Held-Wolfe-Crowder show that using an overestimate UB is as effective as
98 // using the underestimate wlb while UB is easier to compute. The resulting
99 // formula is:
100 // step(m) = lambda(m) * (UB - w(m)) / Sum((degree[i] - 2)^2),
101 // where UB is an upper bound to the TSP (here computed with the Christofides
102 // algorithm), and lambda(m) in [0, 2] initially set to 2. Held-Wolfe-Crowder
103 // suggest running the algorithm for M = 2 * number of nodes iterations, then
104 // dividing lambda and M by 2 until M is small enough (less than 2 in this
105 // implementation).
106 //
107 // To speed up the computation, minimum spanning trees are actually computed on
108 // a graph limited to the nearest neighbors of each node. Valenzuela-Jones 1997
109 // experiments have shown that this does not harm the lower bound computation
110 // significantly. At the end of the algorithm a last iteration is run on the
111 // complete graph to ensure the bound is correct (the cost of a minimum 1-tree
112 // on a partial graph is an upper bound to the one on a complete graph).
113 //
114 // Usage:
115 // std::function<int64_t(int,int)> cost_function =...;
116 // const double lower_bound =
117 // ComputeOneTreeLowerBound(number_of_nodes, cost_function);
118 // where number_of_nodes is the number of nodes in the TSP and cost_function
119 // is a function returning the cost between two nodes.
120 
121 #ifndef OR_TOOLS_GRAPH_ONE_TREE_LOWER_BOUND_H_
122 #define OR_TOOLS_GRAPH_ONE_TREE_LOWER_BOUND_H_
123 
124 #include <math.h>
125 
126 #include <cmath>
127 #include <cstdint>
128 #include <limits>
129 #include <set>
130 #include <utility>
131 #include <vector>
132 
133 #include "ortools/base/integral_types.h"
136 
137 namespace operations_research {
138 
139 // Implementation of algorithms computing Held-Karp bounds. They have to provide
140 // the following methods:
141 // - bool Next(): returns false when the algorithm must stop;
142 // - double GetStep(): returns the current step computed by the algorithm;
143 // - void OnOneTree(CostType one_tree_cost,
144 // double w,
145 // const std::vector<int>& degrees):
146 // called each time a new minimum 1-tree is computed;
147 // - one_tree_cost: the un-weighed cost of the 1-tree,
148 // - w the current value of w,
149 // - degrees: the degree of nodes in the 1-tree.
150 // - OnNewWMax(CostType one_tree_cost): called when a better value of w is
151 // found, one_tree_cost being the un-weighed cost of the corresponding
152 // minimum 1-tree.
153 
154 // Implementation of the Volgenant Jonker algorithm (see the comments at the
155 // head of the file for explanations).
156 template <typename CostType>
158  public:
159  VolgenantJonkerEvaluator(int number_of_nodes, int max_iterations)
160  : step1_initialized_(false),
161  step1_(0),
162  iteration_(0),
163  max_iterations_(max_iterations > 0 ? max_iterations
164  : MaxIterations(number_of_nodes)),
165  number_of_nodes_(number_of_nodes) {}
166 
167  bool Next() { return iteration_++ < max_iterations_; }
168 
169  double GetStep() const {
170  return (1.0 * (iteration_ - 1) * (2 * max_iterations_ - 5) /
171  (2 * (max_iterations_ - 1))) *
172  step1_ -
173  (iteration_ - 2) * step1_ +
174  (0.5 * (iteration_ - 1) * (iteration_ - 2) /
175  ((max_iterations_ - 1) * (max_iterations_ - 2))) *
176  step1_;
177  }
178 
179  void OnOneTree(CostType one_tree_cost, double w,
180  const std::vector<int>& degrees) {
181  if (!step1_initialized_) {
182  step1_initialized_ = true;
183  UpdateStep(one_tree_cost);
184  }
185  }
186 
187  void OnNewWMax(CostType one_tree_cost) { UpdateStep(one_tree_cost); }
188 
189  private:
190  // Automatic computation of the number of iterations based on empirical
191  // results given in Valenzuela-Jones 1997.
192  static int MaxIterations(int number_of_nodes) {
193  return static_cast<int>(28 * std::pow(number_of_nodes, 0.62));
194  }
195 
196  void UpdateStep(CostType one_tree_cost) {
197  step1_ = one_tree_cost / (2 * number_of_nodes_);
198  }
199 
200  bool step1_initialized_;
201  double step1_;
202  int iteration_;
203  const int max_iterations_;
204  const int number_of_nodes_;
205 };
206 
207 // Implementation of the Held-Wolfe-Crowder algorithm (see the comments at the
208 // head of the file for explanations).
209 template <typename CostType, typename CostFunction>
211  public:
212  HeldWolfeCrowderEvaluator(int number_of_nodes, const CostFunction& cost)
213  : iteration_(0),
214  number_of_iterations_(2 * number_of_nodes),
215  upper_bound_(0),
216  lambda_(2.0),
217  step_(0) {
218  // TODO(user): Improve upper bound with some local search; tighter upper
219  // bounds lead to faster convergence.
221  number_of_nodes, cost);
222  upper_bound_ = solver.TravelingSalesmanCost();
223  }
224 
225  bool Next() {
226  const int min_iterations = 2;
227  if (iteration_ >= number_of_iterations_) {
228  number_of_iterations_ /= 2;
229  if (number_of_iterations_ < min_iterations) return false;
230  iteration_ = 0;
231  lambda_ /= 2;
232  } else {
233  ++iteration_;
234  }
235  return true;
236  }
237 
238  double GetStep() const { return step_; }
239 
240  void OnOneTree(CostType one_tree_cost, double w,
241  const std::vector<int>& degrees) {
242  double norm = 0;
243  for (int degree : degrees) {
244  const double delta = degree - 2;
245  norm += delta * delta;
246  }
247  step_ = lambda_ * (upper_bound_ - w) / norm;
248  }
249 
250  void OnNewWMax(CostType one_tree_cost) {}
251 
252  private:
253  int iteration_;
254  int number_of_iterations_;
255  CostType upper_bound_;
256  double lambda_;
257  double step_;
258 };
259 
260 // Computes the nearest neighbors of each node for the given cost function.
261 // The ith element of the returned vector contains the indices of the nearest
262 // nodes to node i. Note that these indices contain the number_of_neighbors
263 // nearest neighbors as well as all the nodes for which i is a nearest
264 // neighbor.
265 template <typename CostFunction>
266 std::set<std::pair<int, int>> NearestNeighbors(int number_of_nodes,
267  int number_of_neighbors,
268  const CostFunction& cost) {
269  using CostType = decltype(cost(0, 0));
270  std::set<std::pair<int, int>> nearest;
271  for (int i = 0; i < number_of_nodes; ++i) {
272  std::vector<std::pair<CostType, int>> neighbors;
273  neighbors.reserve(number_of_nodes - 1);
274  for (int j = 0; j < number_of_nodes; ++j) {
275  if (i != j) {
276  neighbors.emplace_back(cost(i, j), j);
277  }
278  }
279  int size = neighbors.size();
280  if (number_of_neighbors < size) {
281  std::nth_element(neighbors.begin(),
282  neighbors.begin() + number_of_neighbors - 1,
283  neighbors.end());
284  size = number_of_neighbors;
285  }
286  for (int j = 0; j < size; ++j) {
287  nearest.insert({i, neighbors[j].second});
288  nearest.insert({neighbors[j].second, i});
289  }
290  }
291  return nearest;
292 }
293 
294 // Let G be the complete graph on nodes in [0, number_of_nodes - 1]. Adds arcs
295 // from the minimum spanning tree of G to the arcs set argument.
296 template <typename CostFunction>
297 void AddArcsFromMinimumSpanningTree(int number_of_nodes,
298  const CostFunction& cost,
299  std::set<std::pair<int, int>>* arcs) {
300  util::CompleteGraph<int, int> graph(number_of_nodes);
301  const std::vector<int> mst =
302  BuildPrimMinimumSpanningTree(graph, [&cost, &graph](int arc) {
303  return cost(graph.Tail(arc), graph.Head(arc));
304  });
305  for (int arc : mst) {
306  arcs->insert({graph.Tail(arc), graph.Head(arc)});
307  arcs->insert({graph.Head(arc), graph.Tail(arc)});
308  }
309 }
310 
311 // Returns the index of the node in graph which minimizes cost(node, source)
312 // with the constraint that accept(node) is true.
313 template <typename CostFunction, typename GraphType, typename AcceptFunction>
314 int GetNodeMinimizingEdgeCostToSource(const GraphType& graph, int source,
315  const CostFunction& cost,
316  AcceptFunction accept) {
317  int best_node = -1;
318  double best_edge_cost = 0;
319  for (const auto node : graph.AllNodes()) {
320  if (accept(node)) {
321  const double edge_cost = cost(node, source);
322  if (best_node == -1 || edge_cost < best_edge_cost) {
323  best_node = node;
324  best_edge_cost = edge_cost;
325  }
326  }
327  }
328  return best_node;
329 }
330 
331 // Computes a 1-tree for the given graph, cost function and node weights.
332 // Returns the degree of each node in the 1-tree and the un-weighed cost of the
333 // 1-tree.
334 template <typename CostFunction, typename GraphType, typename CostType>
335 std::vector<int> ComputeOneTree(const GraphType& graph,
336  const CostFunction& cost,
337  const std::vector<double>& weights,
338  const std::vector<int>& sorted_arcs,
339  CostType* one_tree_cost) {
340  const auto weighed_cost = [&cost, &weights](int from, int to) {
341  return cost(from, to) + weights[from] + weights[to];
342  };
343  // Compute MST on graph.
344  std::vector<int> mst;
345  if (!sorted_arcs.empty()) {
346  mst = BuildKruskalMinimumSpanningTreeFromSortedArcs<GraphType>(graph,
347  sorted_arcs);
348  } else {
349  mst = BuildPrimMinimumSpanningTree<GraphType>(
350  graph, [&weighed_cost, &graph](int arc) {
351  return weighed_cost(graph.Tail(arc), graph.Head(arc));
352  });
353  }
354  std::vector<int> degrees(graph.num_nodes() + 1, 0);
355  *one_tree_cost = 0;
356  for (int arc : mst) {
357  degrees[graph.Head(arc)]++;
358  degrees[graph.Tail(arc)]++;
359  *one_tree_cost += cost(graph.Tail(arc), graph.Head(arc));
360  }
361  // Add 2 cheapest edges from the nodes in the graph to the extra node not in
362  // the graph.
363  const int extra_node = graph.num_nodes();
364  const auto update_one_tree = [extra_node, one_tree_cost, &degrees,
365  &cost](int node) {
366  *one_tree_cost += cost(node, extra_node);
367  degrees.back()++;
368  degrees[node]++;
369  };
370  const int node = GetNodeMinimizingEdgeCostToSource(
371  graph, extra_node, weighed_cost,
372  [extra_node](int n) { return n != extra_node; });
373  update_one_tree(node);
374  update_one_tree(GetNodeMinimizingEdgeCostToSource(
375  graph, extra_node, weighed_cost,
376  [extra_node, node](int n) { return n != extra_node && n != node; }));
377  return degrees;
378 }
379 
380 // Computes the lower bound of a TSP using a given subgradient algorithm.
381 template <typename CostFunction, typename Algorithm>
382 double ComputeOneTreeLowerBoundWithAlgorithm(int number_of_nodes,
383  int nearest_neighbors,
384  const CostFunction& cost,
385  Algorithm* algorithm) {
386  if (number_of_nodes < 2) return 0;
387  if (number_of_nodes == 2) return cost(0, 1) + cost(1, 0);
388  using CostType = decltype(cost(0, 0));
389  auto nearest = NearestNeighbors(number_of_nodes - 1, nearest_neighbors, cost);
390  // Ensure nearest arcs result in a connected graph by adding arcs from the
391  // minimum spanning tree; this will add arcs which are likely to be "good"
392  // 1-tree arcs.
393  AddArcsFromMinimumSpanningTree(number_of_nodes - 1, cost, &nearest);
394  util::ListGraph<int, int> graph(number_of_nodes - 1, nearest.size());
395  for (const auto& arc : nearest) {
396  graph.AddArc(arc.first, arc.second);
397  }
398  std::vector<double> weights(number_of_nodes, 0);
399  std::vector<double> best_weights(number_of_nodes, 0);
400  double max_w = -std::numeric_limits<double>::infinity();
401  double w = 0;
402  // Iteratively compute lower bound using a partial graph.
403  while (algorithm->Next()) {
404  CostType one_tree_cost = 0;
405  const std::vector<int> degrees =
406  ComputeOneTree(graph, cost, weights, {}, &one_tree_cost);
407  algorithm->OnOneTree(one_tree_cost, w, degrees);
408  w = one_tree_cost;
409  for (int j = 0; j < number_of_nodes; ++j) {
410  w += weights[j] * (degrees[j] - 2);
411  }
412  if (w > max_w) {
413  max_w = w;
414  best_weights = weights;
415  algorithm->OnNewWMax(one_tree_cost);
416  }
417  const double step = algorithm->GetStep();
418  for (int j = 0; j < number_of_nodes; ++j) {
419  weights[j] += step * (degrees[j] - 2);
420  }
421  }
422  // Compute lower bound using the complete graph on the best weights. This is
423  // necessary as the MSTs computed on nearest neighbors is not guaranteed to
424  // lead to a lower bound.
425  util::CompleteGraph<int, int> complete_graph(number_of_nodes - 1);
426  CostType one_tree_cost = 0;
427  // TODO(user): We are not caching here since this would take O(n^2) memory;
428  // however the Kruskal algorithm will expand all arcs also consuming O(n^2)
429  // memory; investigate alternatives to expanding all arcs (Prim's algorithm).
430  const std::vector<int> degrees =
431  ComputeOneTree(complete_graph, cost, best_weights, {}, &one_tree_cost);
432  w = one_tree_cost;
433  for (int j = 0; j < number_of_nodes; ++j) {
434  w += best_weights[j] * (degrees[j] - 2);
435  }
436  return w;
437 }
438 
439 // Parameters to configure the computation of the TSP lower bound.
441  enum Algorithm {
444  };
445  // Subgradient algorithm to use to compute the TSP lower bound.
447  // Number of iterations to use in the Volgenant-Jonker algorithm. Overrides
448  // automatic iteration computation if positive.
450  // Number of nearest neighbors to consider in the miminum spanning trees.
452 };
453 
454 // Computes the lower bound of a TSP using given parameters.
455 template <typename CostFunction>
457  int number_of_nodes, const CostFunction& cost,
458  const TravelingSalesmanLowerBoundParameters& parameters) {
459  using CostType = decltype(cost(0, 0));
460  switch (parameters.algorithm) {
463  number_of_nodes, parameters.volgenant_jonker_iterations);
465  number_of_nodes, parameters.nearest_neighbors, cost, &algorithm);
466  break;
467  }
470  number_of_nodes, cost);
472  number_of_nodes, parameters.nearest_neighbors, cost, &algorithm);
473  }
474  default:
475  LOG(ERROR) << "Unsupported algorithm: " << parameters.algorithm;
476  return 0;
477  }
478 }
479 
480 // Computes the lower bound of a TSP using default parameters (Volgenant-Jonker
481 // algorithm, 200 iterations and 40 nearest neighbors) which have turned out to
482 // give good results on the TSPLIB.
483 template <typename CostFunction>
484 double ComputeOneTreeLowerBound(int number_of_nodes, const CostFunction& cost) {
486  return ComputeOneTreeLowerBoundWithParameters(number_of_nodes, cost,
487  parameters);
488 }
489 
490 } // namespace operations_research
491 
492 #endif // OR_TOOLS_GRAPH_ONE_TREE_LOWER_BOUND_H_
void OnOneTree(CostType one_tree_cost, double w, const std::vector< int > &degrees)
HeldWolfeCrowderEvaluator(int number_of_nodes, const CostFunction &cost)
VolgenantJonkerEvaluator(int number_of_nodes, int max_iterations)
void OnOneTree(CostType one_tree_cost, double w, const std::vector< int > &degrees)
NodeIndexType Tail(ArcIndexType arc) const
Definition: graph.h:2248
NodeIndexType Head(ArcIndexType arc) const
Definition: graph.h:2241
ArcIndexType AddArc(NodeIndexType tail, NodeIndexType head)
Definition: graph.h:1167
std::set< std::pair< int, int > > NearestNeighbors(int number_of_nodes, int number_of_neighbors, const CostFunction &cost)
std::vector< typename Graph::ArcIndex > BuildPrimMinimumSpanningTree(const Graph &graph, const ArcValue &arc_value)
double ComputeOneTreeLowerBoundWithAlgorithm(int number_of_nodes, int nearest_neighbors, const CostFunction &cost, Algorithm *algorithm)
double ComputeOneTreeLowerBoundWithParameters(int number_of_nodes, const CostFunction &cost, const TravelingSalesmanLowerBoundParameters &parameters)
std::vector< int > ComputeOneTree(const GraphType &graph, const CostFunction &cost, const std::vector< double > &weights, const std::vector< int > &sorted_arcs, CostType *one_tree_cost)
void AddArcsFromMinimumSpanningTree(int number_of_nodes, const CostFunction &cost, std::set< std::pair< int, int >> *arcs)
double ComputeOneTreeLowerBound(int number_of_nodes, const CostFunction &cost)
int GetNodeMinimizingEdgeCostToSource(const GraphType &graph, int source, const CostFunction &cost, AcceptFunction accept)