C++ Reference

C++ Reference: Graph

one_tree_lower_bound.h
Go to the documentation of this file.
1 // Copyright 2010-2018 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(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 <limits>
127 #include <set>
128 
129 #include "ortools/base/integral_types.h"
132 
133 namespace operations_research {
134 
135 // Implementation of algorithms computing Held-Karp bounds. They have to provide
136 // the following methods:
137 // - bool Next(): returns false when the algorithm must stop;
138 // - double GetStep(): returns the current step computed by the algorithm;
139 // - void OnOneTree(CostType one_tree_cost,
140 // double w,
141 // const std::vector<int>& degrees):
142 // called each time a new minimum 1-tree is computed;
143 // - one_tree_cost: the un-weighed cost of the 1-tree,
144 // - w the current value of w,
145 // - degrees: the degree of nodes in the 1-tree.
146 // - OnNewWMax(CostType one_tree_cost): called when a better value of w is
147 // found, one_tree_cost being the un-weighed cost of the corresponding
148 // minimum 1-tree.
149 
150 // Implementation of the Volgenant Jonker algorithm (see the comments at the
151 // head of the file for explanations).
152 template <typename CostType>
154  public:
155  VolgenantJonkerEvaluator(int number_of_nodes, int max_iterations)
156  : step1_initialized_(false),
157  step1_(0),
158  iteration_(0),
159  max_iterations_(max_iterations > 0 ? max_iterations
160  : MaxIterations(number_of_nodes)),
161  number_of_nodes_(number_of_nodes) {}
162 
163  bool Next() { return iteration_++ < max_iterations_; }
164 
165  double GetStep() const {
166  return (1.0 * (iteration_ - 1) * (2 * max_iterations_ - 5) /
167  (2 * (max_iterations_ - 1))) *
168  step1_ -
169  (iteration_ - 2) * step1_ +
170  (0.5 * (iteration_ - 1) * (iteration_ - 2) /
171  ((max_iterations_ - 1) * (max_iterations_ - 2))) *
172  step1_;
173  }
174 
175  void OnOneTree(CostType one_tree_cost, double w,
176  const std::vector<int>& degrees) {
177  if (!step1_initialized_) {
178  step1_initialized_ = true;
179  UpdateStep(one_tree_cost);
180  }
181  }
182 
183  void OnNewWMax(CostType one_tree_cost) { UpdateStep(one_tree_cost); }
184 
185  private:
186  // Automatic computation of the number of iterations based on empirical
187  // results given in Valenzuela-Jones 1997.
188  static int MaxIterations(int number_of_nodes) {
189  return static_cast<int>(28 * std::pow(number_of_nodes, 0.62));
190  }
191 
192  void UpdateStep(CostType one_tree_cost) {
193  step1_ = one_tree_cost / (2 * number_of_nodes_);
194  }
195 
196  bool step1_initialized_;
197  double step1_;
198  int iteration_;
199  const int max_iterations_;
200  const int number_of_nodes_;
201 };
202 
203 // Implementation of the Held-Wolfe-Crowder algorithm (see the comments at the
204 // head of the file for explanations).
205 template <typename CostType, typename CostFunction>
207  public:
208  HeldWolfeCrowderEvaluator(int number_of_nodes, const CostFunction& cost)
209  : iteration_(0),
210  number_of_iterations_(2 * number_of_nodes),
211  upper_bound_(0),
212  lambda_(2.0),
213  step_(0) {
214  // TODO(user): Improve upper bound with some local search; tighter upper
215  // bounds lead to faster convergence.
217  number_of_nodes, cost);
218  upper_bound_ = solver.TravelingSalesmanCost();
219  }
220 
221  bool Next() {
222  const int min_iterations = 2;
223  if (iteration_ >= number_of_iterations_) {
224  number_of_iterations_ /= 2;
225  if (number_of_iterations_ < min_iterations) return false;
226  iteration_ = 0;
227  lambda_ /= 2;
228  } else {
229  ++iteration_;
230  }
231  return true;
232  }
233 
234  double GetStep() const { return step_; }
235 
236  void OnOneTree(CostType one_tree_cost, double w,
237  const std::vector<int>& degrees) {
238  double norm = 0;
239  for (int degree : degrees) {
240  const double delta = degree - 2;
241  norm += delta * delta;
242  }
243  step_ = lambda_ * (upper_bound_ - w) / norm;
244  }
245 
246  void OnNewWMax(CostType one_tree_cost) {}
247 
248  private:
249  int iteration_;
250  int number_of_iterations_;
251  CostType upper_bound_;
252  double lambda_;
253  double step_;
254 };
255 
256 // Computes the nearest neighbors of each node for the given cost function.
257 // The ith element of the returned vector contains the indices of the nearest
258 // nodes to node i. Note that these indices contain the number_of_neighbors
259 // nearest neighbors as well as all the nodes for which i is a nearest
260 // neighbor.
261 template <typename CostFunction>
262 std::set<std::pair<int, int>> NearestNeighbors(int number_of_nodes,
263  int number_of_neighbors,
264  const CostFunction& cost) {
265  using CostType = decltype(cost(0, 0));
266  std::set<std::pair<int, int>> nearest;
267  for (int i = 0; i < number_of_nodes; ++i) {
268  std::vector<std::pair<CostType, int>> neighbors;
269  neighbors.reserve(number_of_nodes - 1);
270  for (int j = 0; j < number_of_nodes; ++j) {
271  if (i != j) {
272  neighbors.emplace_back(cost(i, j), j);
273  }
274  }
275  int size = neighbors.size();
276  if (number_of_neighbors < size) {
277  std::nth_element(neighbors.begin(),
278  neighbors.begin() + number_of_neighbors - 1,
279  neighbors.end());
280  size = number_of_neighbors;
281  }
282  for (int j = 0; j < size; ++j) {
283  nearest.insert({i, neighbors[j].second});
284  nearest.insert({neighbors[j].second, i});
285  }
286  }
287  return nearest;
288 }
289 
290 // Let G be the complete graph on nodes in [0, number_of_nodes - 1]. Adds arcs
291 // from the minimum spanning tree of G to the arcs set argument.
292 template <typename CostFunction>
293 void AddArcsFromMinimumSpanningTree(int number_of_nodes,
294  const CostFunction& cost,
295  std::set<std::pair<int, int>>* arcs) {
296  util::CompleteGraph<int, int> graph(number_of_nodes);
297  const std::vector<int> mst =
298  BuildPrimMinimumSpanningTree(graph, [&cost, &graph](int arc) {
299  return cost(graph.Tail(arc), graph.Head(arc));
300  });
301  for (int arc : mst) {
302  arcs->insert({graph.Tail(arc), graph.Head(arc)});
303  arcs->insert({graph.Head(arc), graph.Tail(arc)});
304  }
305 }
306 
307 // Returns the index of the node in graph which minimizes cost(node, source)
308 // with the constraint that accept(node) is true.
309 template <typename CostFunction, typename GraphType, typename AcceptFunction>
310 int GetNodeMinimizingEdgeCostToSource(const GraphType& graph, int source,
311  const CostFunction& cost,
312  AcceptFunction accept) {
313  int best_node = -1;
314  double best_edge_cost = 0;
315  for (const auto node : graph.AllNodes()) {
316  if (accept(node)) {
317  const double edge_cost = cost(node, source);
318  if (best_node == -1 || edge_cost < best_edge_cost) {
319  best_node = node;
320  best_edge_cost = edge_cost;
321  }
322  }
323  }
324  return best_node;
325 }
326 
327 // Computes a 1-tree for the given graph, cost function and node weights.
328 // Returns the degree of each node in the 1-tree and the un-weighed cost of the
329 // 1-tree.
330 template <typename CostFunction, typename GraphType, typename CostType>
331 std::vector<int> ComputeOneTree(const GraphType& graph,
332  const CostFunction& cost,
333  const std::vector<double>& weights,
334  const std::vector<int>& sorted_arcs,
335  CostType* one_tree_cost) {
336  const auto weighed_cost = [&cost, &weights](int from, int to) {
337  return cost(from, to) + weights[from] + weights[to];
338  };
339  // Compute MST on graph.
340  std::vector<int> mst;
341  if (!sorted_arcs.empty()) {
342  mst = BuildKruskalMinimumSpanningTreeFromSortedArcs<GraphType>(graph,
343  sorted_arcs);
344  } else {
345  mst = BuildPrimMinimumSpanningTree<GraphType>(
346  graph, [&weighed_cost, &graph](int arc) {
347  return weighed_cost(graph.Tail(arc), graph.Head(arc));
348  });
349  }
350  std::vector<int> degrees(graph.num_nodes() + 1, 0);
351  *one_tree_cost = 0;
352  for (int arc : mst) {
353  degrees[graph.Head(arc)]++;
354  degrees[graph.Tail(arc)]++;
355  *one_tree_cost += cost(graph.Tail(arc), graph.Head(arc));
356  }
357  // Add 2 cheapest edges from the nodes in the graph to the extra node not in
358  // the graph.
359  const int extra_node = graph.num_nodes();
360  const auto update_one_tree = [extra_node, one_tree_cost, &degrees,
361  &cost](int node) {
362  *one_tree_cost += cost(node, extra_node);
363  degrees.back()++;
364  degrees[node]++;
365  };
366  const int node = GetNodeMinimizingEdgeCostToSource(
367  graph, extra_node, weighed_cost,
368  [extra_node](int n) { return n != extra_node; });
369  update_one_tree(node);
370  update_one_tree(GetNodeMinimizingEdgeCostToSource(
371  graph, extra_node, weighed_cost,
372  [extra_node, node](int n) { return n != extra_node && n != node; }));
373  return degrees;
374 }
375 
376 // Computes the lower bound of a TSP using a given subgradient algorithm.
377 template <typename CostFunction, typename Algorithm>
378 double ComputeOneTreeLowerBoundWithAlgorithm(int number_of_nodes,
379  int nearest_neighbors,
380  const CostFunction& cost,
381  Algorithm* algorithm) {
382  if (number_of_nodes < 2) return 0;
383  if (number_of_nodes == 2) return cost(0, 1) + cost(1, 0);
384  using CostType = decltype(cost(0, 0));
385  auto nearest = NearestNeighbors(number_of_nodes - 1, nearest_neighbors, cost);
386  // Ensure nearest arcs result in a connected graph by adding arcs from the
387  // minimum spanning tree; this will add arcs which are likely to be "good"
388  // 1-tree arcs.
389  AddArcsFromMinimumSpanningTree(number_of_nodes - 1, cost, &nearest);
390  util::ListGraph<int, int> graph(number_of_nodes - 1, nearest.size());
391  for (const auto& arc : nearest) {
392  graph.AddArc(arc.first, arc.second);
393  }
394  std::vector<double> weights(number_of_nodes, 0);
395  std::vector<double> best_weights(number_of_nodes, 0);
396  double max_w = -std::numeric_limits<double>::infinity();
397  double w = 0;
398  // Iteratively compute lower bound using a partial graph.
399  while (algorithm->Next()) {
400  CostType one_tree_cost = 0;
401  const std::vector<int> degrees =
402  ComputeOneTree(graph, cost, weights, {}, &one_tree_cost);
403  algorithm->OnOneTree(one_tree_cost, w, degrees);
404  w = one_tree_cost;
405  for (int j = 0; j < number_of_nodes; ++j) {
406  w += weights[j] * (degrees[j] - 2);
407  }
408  if (w > max_w) {
409  max_w = w;
410  best_weights = weights;
411  algorithm->OnNewWMax(one_tree_cost);
412  }
413  const double step = algorithm->GetStep();
414  for (int j = 0; j < number_of_nodes; ++j) {
415  weights[j] += step * (degrees[j] - 2);
416  }
417  }
418  // Compute lower bound using the complete graph on the best weights. This is
419  // necessary as the MSTs computed on nearest neighbors is not guaranteed to
420  // lead to a lower bound.
421  util::CompleteGraph<int, int> complete_graph(number_of_nodes - 1);
422  CostType one_tree_cost = 0;
423  // TODO(user): We are not caching here since this would take O(n^2) memory;
424  // however the Kruskal algorithm will expand all arcs also consuming O(n^2)
425  // memory; investigate alternatives to expanding all arcs (Prim's algorithm).
426  const std::vector<int> degrees =
427  ComputeOneTree(complete_graph, cost, best_weights, {}, &one_tree_cost);
428  w = one_tree_cost;
429  for (int j = 0; j < number_of_nodes; ++j) {
430  w += best_weights[j] * (degrees[j] - 2);
431  }
432  return w;
433 }
434 
435 // Parameters to configure the computation of the TSP lower bound.
437  enum Algorithm {
440  };
441  // Subgradient algorithm to use to compute the TSP lower bound.
443  // Number of iterations to use in the Volgenant-Jonker algorithm. Overrides
444  // automatic iteration computation if positive.
446  // Number of nearest neighbors to consider in the miminum spanning trees.
448 };
449 
450 // Computes the lower bound of a TSP using given parameters.
451 template <typename CostFunction>
453  int number_of_nodes, const CostFunction& cost,
454  const TravelingSalesmanLowerBoundParameters& parameters) {
455  using CostType = decltype(cost(0, 0));
456  switch (parameters.algorithm) {
459  number_of_nodes, parameters.volgenant_jonker_iterations);
461  number_of_nodes, parameters.nearest_neighbors, cost, &algorithm);
462  break;
463  }
466  number_of_nodes, cost);
468  number_of_nodes, parameters.nearest_neighbors, cost, &algorithm);
469  }
470  default:
471  LOG(ERROR) << "Unsupported algorithm: " << parameters.algorithm;
472  return 0;
473  }
474 }
475 
476 // Computes the lower bound of a TSP using default parameters (Volgenant-Jonker
477 // algorithm, 200 iterations and 40 nearest neighbors) which have turned out to
478 // give good results on the TSPLIB.
479 template <typename CostFunction>
480 double ComputeOneTreeLowerBound(int number_of_nodes, const CostFunction& cost) {
482  return ComputeOneTreeLowerBoundWithParameters(number_of_nodes, cost,
483  parameters);
484 }
485 
486 } // namespace operations_research
487 
488 #endif // OR_TOOLS_GRAPH_ONE_TREE_LOWER_BOUND_H_
@ HeldWolfeCrowder
HeldWolfeCrowderEvaluator(int number_of_nodes, const CostFunction &cost)
NodeIndexType Tail(ArcIndexType arc) const
Definition: graph.h:2204
Algorithm algorithm
VolgenantJonkerEvaluator(int number_of_nodes, int max_iterations)
int GetNodeMinimizingEdgeCostToSource(const GraphType &graph, int source, const CostFunction &cost, AcceptFunction accept)
Definition: graph.h:2170
double ComputeOneTreeLowerBoundWithParameters(int number_of_nodes, const CostFunction &cost, const TravelingSalesmanLowerBoundParameters &parameters)
Definition: christofides.h:33
double GetStep() const
std::set< std::pair< int, int > > NearestNeighbors(int number_of_nodes, int number_of_neighbors, const CostFunction &cost)
Definition: christofides.h:40
bool Next()
double GetStep() const
std::vector< typename Graph::ArcIndex > BuildPrimMinimumSpanningTree(const Graph &graph, const ArcValue &arc_value)
int volgenant_jonker_iterations
NodeIndexType Head(ArcIndexType arc) const
Definition: graph.h:2197
double ComputeOneTreeLowerBound(int number_of_nodes, const CostFunction &cost)
void OnNewWMax(CostType one_tree_cost)
void OnNewWMax(CostType one_tree_cost)
void OnOneTree(CostType one_tree_cost, double w, const std::vector< int > &degrees)
double ComputeOneTreeLowerBoundWithAlgorithm(int number_of_nodes, int nearest_neighbors, const CostFunction &cost, Algorithm *algorithm)
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)
CostType TravelingSalesmanCost()
Definition: christofides.h:223
Definition: graph.h:297
bool Next()
@ VolgenantJonker
void OnOneTree(CostType one_tree_cost, double w, const std::vector< int > &degrees)
ArcIndexType AddArc(NodeIndexType tail, NodeIndexType head)
Definition: graph.h:1134
Algorithm
int nearest_neighbors
void AddArcsFromMinimumSpanningTree(int number_of_nodes, const CostFunction &cost, std::set< std::pair< int, int >> *arcs)