Welcome to mirror list, hosted at ThFree Co, Russian Federation.

tsp_test.cc « test « lemon-1.3.1 « 3rd « quadriflow « extern - git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 398a812e0905c50733228c6727e1165b1b6ee5a2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
/* -*- mode: C++; indent-tabs-mode: nil; -*-
 *
 * This file is a part of LEMON, a generic C++ optimization library.
 *
 * Copyright (C) 2003-2013
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
 *
 * Permission to use, modify and distribute this software is granted
 * provided that this copyright notice appears in all copies. For
 * precise terms see the accompanying LICENSE file.
 *
 * This software is provided "AS IS" with no warranty of any kind,
 * express or implied, and with no claim as to its suitability for any
 * purpose.
 *
 */

#include <iostream>

#include <lemon/full_graph.h>
#include <lemon/math.h>
#include <lemon/maps.h>
#include <lemon/random.h>
#include <lemon/dim2.h>

#include <lemon/nearest_neighbor_tsp.h>
#include <lemon/greedy_tsp.h>
#include <lemon/insertion_tsp.h>
#include <lemon/christofides_tsp.h>
#include <lemon/opt2_tsp.h>

#include "test_tools.h"

using namespace lemon;

// // Tests checkMetricCost() function
// void metricCostTest() {
//   GRAPH_TYPEDEFS(FullGraph);
//   FullGraph g(10);
//   check(checkMetricCost(g, constMap<Edge>(0)), "Wrong checkMetricCost()");
//   check(checkMetricCost(g, constMap<Edge>(1)), "Wrong checkMetricCost()");
//   check(!checkMetricCost(g, constMap<Edge>(-1)), "Wrong checkMetricCost()");
//
//   FullGraph::EdgeMap<float> cost(g);
//   for (NodeIt u(g); u != INVALID; ++u) {
//     for (NodeIt v(g); v != INVALID; ++v) {
//       if (u == v) continue;
//       float x1 = g.id(u), x2 = g.id(v);
//       float y1 = x1 * x1, y2 = x2 * x2;
//       cost[g.edge(u, v)] = std::sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));
//     }
//   }
//   check(checkMetricCost(g, cost), "Wrong checkMetricCost()");
//   float eps = Tolerance<float>::defaultEpsilon();
//   cost[g.edge(g(0), g(9))] =
//     cost[g.edge(g(0), g(8))] + cost[g.edge(g(8), g(9))] + eps * 2;
//   check(!checkMetricCost(g, cost), "Wrong checkMetricCost()");
//   check(checkMetricCost(g, cost, Tolerance<float>(eps * 4)),
//     "Wrong checkMetricCost()");
// }

// Checks tour validity
template <typename Container>
bool checkTour(const FullGraph &gr, const Container &p) {
  FullGraph::NodeMap<bool> used(gr, false);

  int node_cnt = 0;
  for (typename Container::const_iterator it = p.begin(); it != p.end(); ++it)
    {
      FullGraph::Node node = *it;
      if (used[node]) return false;
      used[node] = true;
      ++node_cnt;
    }

  return (node_cnt == gr.nodeNum());
}

// Checks tour validity
bool checkTourPath(const FullGraph &gr, const Path<FullGraph> &p) {
  FullGraph::NodeMap<bool> used(gr, false);

  if (!checkPath(gr, p)) return false;
  if (gr.nodeNum() <= 1 && p.length() != 0) return false;
  if (gr.nodeNum() > 1 && p.length() != gr.nodeNum()) return false;

  for (int i = 0; i < p.length(); ++i) {
    if (used[gr.target(p.nth(i))]) return false;
    used[gr.target(p.nth(i))] = true;
  }
  return true;
}

// Checks tour cost
template <typename CostMap>
bool checkCost(const FullGraph &gr, const std::vector<FullGraph::Node> &p,
               const CostMap &cost, typename CostMap::Value total)
{
  typedef typename CostMap::Value Cost;

  Cost s = 0;
  for (int i = 0; i < int(p.size()) - 1; ++i)
    s += cost[gr.edge(p[i], p[i+1])];
  if (int(p.size()) >= 2)
    s += cost[gr.edge(p.back(), p.front())];

  return !Tolerance<Cost>().different(s, total);
}

// Checks tour cost
template <typename CostMap>
bool checkCost(const FullGraph &, const Path<FullGraph> &p,
               const CostMap &cost, typename CostMap::Value total)
{
  typedef typename CostMap::Value Cost;

  Cost s = 0;
  for (int i = 0; i < p.length(); ++i)
    s += cost[p.nth(i)];

  return !Tolerance<Cost>().different(s, total);
}

// Tests a TSP algorithm on small graphs
template <typename TSP>
void tspTestSmall(const std::string &alg_name) {
  GRAPH_TYPEDEFS(FullGraph);

  for (int n = 0; n <= 5; ++n) {
    FullGraph g(n);
    unsigned nsize = n;
    int esize = n <= 1 ? 0 : n;

    ConstMap<Edge, int> cost_map(1);
    TSP alg(g, cost_map);

    check(alg.run() == esize, alg_name + ": Wrong total cost");
    check(alg.tourCost() == esize, alg_name + ": Wrong total cost");

    std::list<Node> list1(nsize), list2;
    std::vector<Node> vec1(nsize), vec2;
    alg.tourNodes(list1.begin());
    alg.tourNodes(vec1.begin());
    alg.tourNodes(std::front_inserter(list2));
    alg.tourNodes(std::back_inserter(vec2));
    check(checkTour(g, alg.tourNodes()), alg_name + ": Wrong node sequence");
    check(checkTour(g, list1), alg_name + ": Wrong node sequence");
    check(checkTour(g, vec1), alg_name + ": Wrong node sequence");
    check(checkTour(g, list2), alg_name + ": Wrong node sequence");
    check(checkTour(g, vec2), alg_name + ": Wrong node sequence");
    check(checkCost(g, vec1, constMap<Edge, int>(1), esize),
      alg_name + ": Wrong tour cost");

    SimplePath<FullGraph> path;
    alg.tour(path);
    check(path.length() == esize, alg_name + ": Wrong tour");
    check(checkTourPath(g, path), alg_name + ": Wrong tour");
    check(checkCost(g, path, constMap<Edge, int>(1), esize),
      alg_name + ": Wrong tour cost");
  }
}

// Tests a TSP algorithm on random graphs
template <typename TSP>
void tspTestRandom(const std::string &alg_name) {
  GRAPH_TYPEDEFS(FullGraph);

  FullGraph g(20);
  FullGraph::NodeMap<dim2::Point<double> > pos(g);
  DoubleEdgeMap cost(g);

  TSP alg(g, cost);
  Opt2Tsp<DoubleEdgeMap > opt2(g, cost);

  for (int i = 1; i <= 3; i++) {
    for (NodeIt u(g); u != INVALID; ++u) {
      pos[u] = dim2::Point<double>(rnd(), rnd());
    }
    for (NodeIt u(g); u != INVALID; ++u) {
      for (NodeIt v(g); v != INVALID; ++v) {
        if (u == v) continue;
        cost[g.edge(u, v)] = (pos[u] - pos[v]).normSquare();
      }
    }

    check(alg.run() > 0, alg_name + ": Wrong total cost");

    std::vector<Node> vec;
    alg.tourNodes(std::back_inserter(vec));
    check(checkTour(g, vec), alg_name + ": Wrong node sequence");
    check(checkCost(g, vec, cost, alg.tourCost()),
      alg_name + ": Wrong tour cost");

    SimplePath<FullGraph> path;
    alg.tour(path);
    check(checkTourPath(g, path), alg_name + ": Wrong tour");
    check(checkCost(g, path, cost, alg.tourCost()),
      alg_name + ": Wrong tour cost");

    check(!Tolerance<double>().less(alg.tourCost(), opt2.run(alg.tourNodes())),
      "2-opt improvement: Wrong total cost");
    check(checkTour(g, opt2.tourNodes()),
      "2-opt improvement: Wrong node sequence");
    check(checkCost(g, opt2.tourNodes(), cost, opt2.tourCost()),
      "2-opt improvement: Wrong tour cost");

    check(!Tolerance<double>().less(alg.tourCost(), opt2.run(path)),
      "2-opt improvement: Wrong total cost");
    check(checkTour(g, opt2.tourNodes()),
      "2-opt improvement: Wrong node sequence");
    check(checkCost(g, opt2.tourNodes(), cost, opt2.tourCost()),
      "2-opt improvement: Wrong tour cost");
  }
}

// Algorithm class for Nearest Insertion
template <typename CM>
class NearestInsertionTsp : public InsertionTsp<CM> {
public:
  NearestInsertionTsp(const FullGraph &gr, const CM &cost)
    : InsertionTsp<CM>(gr, cost) {}
  typename CM::Value run() {
    return InsertionTsp<CM>::run(InsertionTsp<CM>::NEAREST);
  }
};

// Algorithm class for Farthest Insertion
template <typename CM>
class FarthestInsertionTsp : public InsertionTsp<CM> {
public:
  FarthestInsertionTsp(const FullGraph &gr, const CM &cost)
    : InsertionTsp<CM>(gr, cost) {}
  typename CM::Value run() {
    return InsertionTsp<CM>::run(InsertionTsp<CM>::FARTHEST);
  }
};

// Algorithm class for Cheapest Insertion
template <typename CM>
class CheapestInsertionTsp : public InsertionTsp<CM> {
public:
  CheapestInsertionTsp(const FullGraph &gr, const CM &cost)
    : InsertionTsp<CM>(gr, cost) {}
  typename CM::Value run() {
    return InsertionTsp<CM>::run(InsertionTsp<CM>::CHEAPEST);
  }
};

// Algorithm class for Random Insertion
template <typename CM>
class RandomInsertionTsp : public InsertionTsp<CM> {
public:
  RandomInsertionTsp(const FullGraph &gr, const CM &cost)
    : InsertionTsp<CM>(gr, cost) {}
  typename CM::Value run() {
    return InsertionTsp<CM>::run(InsertionTsp<CM>::RANDOM);
  }
};

int main() {
  GRAPH_TYPEDEFS(FullGraph);

  // metricCostTest();

  tspTestSmall<NearestNeighborTsp<ConstMap<Edge, int> > >("Nearest Neighbor");
  tspTestSmall<GreedyTsp<ConstMap<Edge, int> > >("Greedy");
  tspTestSmall<NearestInsertionTsp<ConstMap<Edge, int> > >("Nearest Insertion");
  tspTestSmall<FarthestInsertionTsp<ConstMap<Edge, int> > >
    ("Farthest Insertion");
  tspTestSmall<CheapestInsertionTsp<ConstMap<Edge, int> > >
    ("Cheapest Insertion");
  tspTestSmall<RandomInsertionTsp<ConstMap<Edge, int> > >("Random Insertion");
  tspTestSmall<ChristofidesTsp<ConstMap<Edge, int> > >("Christofides");
  tspTestSmall<Opt2Tsp<ConstMap<Edge, int> > >("2-opt");

  tspTestRandom<NearestNeighborTsp<DoubleEdgeMap > >("Nearest Neighbor");
  tspTestRandom<GreedyTsp<DoubleEdgeMap > >("Greedy");
  tspTestRandom<NearestInsertionTsp<DoubleEdgeMap > >("Nearest Insertion");
  tspTestRandom<FarthestInsertionTsp<DoubleEdgeMap > >("Farthest Insertion");
  tspTestRandom<CheapestInsertionTsp<DoubleEdgeMap > >("Cheapest Insertion");
  tspTestRandom<RandomInsertionTsp<DoubleEdgeMap > >("Random Insertion");
  tspTestRandom<ChristofidesTsp<DoubleEdgeMap > >("Christofides");
  tspTestRandom<Opt2Tsp<DoubleEdgeMap > >("2-opt");

  return 0;
}