test/tsp_test.cc
changeset 1206 a2d142bb5d3c
parent 1203 07682e24c4e8
child 1270 dceba191c00d
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/test/tsp_test.cc	Fri Mar 01 17:59:08 2013 +0100
     1.3 @@ -0,0 +1,283 @@
     1.4 +/* -*- mode: C++; indent-tabs-mode: nil; -*-
     1.5 + *
     1.6 + * This file is a part of LEMON, a generic C++ optimization library.
     1.7 + *
     1.8 + * Copyright (C) 2003-2010
     1.9 + * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
    1.10 + * (Egervary Research Group on Combinatorial Optimization, EGRES).
    1.11 + *
    1.12 + * Permission to use, modify and distribute this software is granted
    1.13 + * provided that this copyright notice appears in all copies. For
    1.14 + * precise terms see the accompanying LICENSE file.
    1.15 + *
    1.16 + * This software is provided "AS IS" with no warranty of any kind,
    1.17 + * express or implied, and with no claim as to its suitability for any
    1.18 + * purpose.
    1.19 + *
    1.20 + */
    1.21 +
    1.22 +#include <iostream>
    1.23 +
    1.24 +#include <lemon/full_graph.h>
    1.25 +#include <lemon/math.h>
    1.26 +#include <lemon/maps.h>
    1.27 +#include <lemon/random.h>
    1.28 +#include <lemon/dim2.h>
    1.29 +
    1.30 +#include <lemon/nearest_neighbor_tsp.h>
    1.31 +#include <lemon/greedy_tsp.h>
    1.32 +#include <lemon/insertion_tsp.h>
    1.33 +#include <lemon/christofides_tsp.h>
    1.34 +#include <lemon/opt2_tsp.h>
    1.35 +
    1.36 +#include "test_tools.h"
    1.37 +
    1.38 +using namespace lemon;
    1.39 +
    1.40 +// // Tests checkMetricCost() function
    1.41 +// void metricCostTest() {
    1.42 +//   GRAPH_TYPEDEFS(FullGraph);
    1.43 +//   FullGraph g(10);
    1.44 +//   check(checkMetricCost(g, constMap<Edge>(0)), "Wrong checkMetricCost()");
    1.45 +//   check(checkMetricCost(g, constMap<Edge>(1)), "Wrong checkMetricCost()");
    1.46 +//   check(!checkMetricCost(g, constMap<Edge>(-1)), "Wrong checkMetricCost()");
    1.47 +//   
    1.48 +//   FullGraph::EdgeMap<float> cost(g);
    1.49 +//   for (NodeIt u(g); u != INVALID; ++u) {
    1.50 +//     for (NodeIt v(g); v != INVALID; ++v) {
    1.51 +//       if (u == v) continue;
    1.52 +//       float x1 = g.id(u), x2 = g.id(v);
    1.53 +//       float y1 = x1 * x1, y2 = x2 * x2;
    1.54 +//       cost[g.edge(u, v)] = std::sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));
    1.55 +//     }
    1.56 +//   }
    1.57 +//   check(checkMetricCost(g, cost), "Wrong checkMetricCost()");
    1.58 +//   float eps = Tolerance<float>::defaultEpsilon();
    1.59 +//   cost[g.edge(g(0), g(9))] =
    1.60 +//     cost[g.edge(g(0), g(8))] + cost[g.edge(g(8), g(9))] + eps * 2;
    1.61 +//   check(!checkMetricCost(g, cost), "Wrong checkMetricCost()");
    1.62 +//   check(checkMetricCost(g, cost, Tolerance<float>(eps * 4)),
    1.63 +//     "Wrong checkMetricCost()");
    1.64 +// }
    1.65 +
    1.66 +// Checks tour validity
    1.67 +template <typename Container>
    1.68 +bool checkTour(const FullGraph &gr, const Container &p) {
    1.69 +  FullGraph::NodeMap<bool> used(gr, false);
    1.70 +  
    1.71 +  int node_cnt = 0;
    1.72 +  for (typename Container::const_iterator it = p.begin(); it != p.end(); ++it) {
    1.73 +    FullGraph::Node node = *it;
    1.74 +    if (used[node]) return false;
    1.75 +    used[node] = true;
    1.76 +    ++node_cnt;
    1.77 +  }
    1.78 +  
    1.79 +  return (node_cnt == gr.nodeNum());
    1.80 +}
    1.81 +
    1.82 +// Checks tour validity
    1.83 +bool checkTourPath(const FullGraph &gr, const Path<FullGraph> &p) {
    1.84 +  FullGraph::NodeMap<bool> used(gr, false);
    1.85 +  
    1.86 +  if (!checkPath(gr, p)) return false;
    1.87 +  if (gr.nodeNum() <= 1 && p.length() != 0) return false;
    1.88 +  if (gr.nodeNum() > 1 && p.length() != gr.nodeNum()) return false;
    1.89 +
    1.90 +  for (int i = 0; i < p.length(); ++i) {
    1.91 +    if (used[gr.target(p.nth(i))]) return false;
    1.92 +    used[gr.target(p.nth(i))] = true;
    1.93 +  }
    1.94 +  return true;
    1.95 +}
    1.96 +
    1.97 +// Checks tour cost
    1.98 +template <typename CostMap>
    1.99 +bool checkCost(const FullGraph &gr, const std::vector<FullGraph::Node> &p,
   1.100 +               const CostMap &cost, typename CostMap::Value total)
   1.101 +{
   1.102 +  typedef typename CostMap::Value Cost;
   1.103 +
   1.104 +  Cost s = 0;
   1.105 +  for (int i = 0; i < int(p.size()) - 1; ++i)
   1.106 +    s += cost[gr.edge(p[i], p[i+1])];
   1.107 +  if (int(p.size()) >= 2)
   1.108 +    s += cost[gr.edge(p.back(), p.front())];
   1.109 +
   1.110 +  return !Tolerance<Cost>().different(s, total);
   1.111 +}
   1.112 +
   1.113 +// Checks tour cost
   1.114 +template <typename CostMap>
   1.115 +bool checkCost(const FullGraph &, const Path<FullGraph> &p,
   1.116 +               const CostMap &cost, typename CostMap::Value total)
   1.117 +{
   1.118 +  typedef typename CostMap::Value Cost;
   1.119 +
   1.120 +  Cost s = 0;
   1.121 +  for (int i = 0; i < p.length(); ++i)
   1.122 +    s += cost[p.nth(i)];
   1.123 +
   1.124 +  return !Tolerance<Cost>().different(s, total);
   1.125 +}
   1.126 +
   1.127 +// Tests a TSP algorithm on small graphs
   1.128 +template <typename TSP>
   1.129 +void tspTestSmall(const std::string &alg_name) {
   1.130 +  GRAPH_TYPEDEFS(FullGraph);
   1.131 +
   1.132 +  for (int n = 0; n <= 5; ++n) {
   1.133 +    FullGraph g(n);
   1.134 +    unsigned nsize = n;
   1.135 +    int esize = n <= 1 ? 0 : n;
   1.136 +
   1.137 +    TSP alg(g, constMap<Edge, int>(1));
   1.138 +
   1.139 +    check(alg.run() == esize, alg_name + ": Wrong total cost");
   1.140 +    check(alg.tourCost() == esize, alg_name + ": Wrong total cost");
   1.141 +
   1.142 +    std::list<Node> list1(nsize), list2;
   1.143 +    std::vector<Node> vec1(nsize), vec2;
   1.144 +    alg.tourNodes(list1.begin());
   1.145 +    alg.tourNodes(vec1.begin());
   1.146 +    alg.tourNodes(std::front_inserter(list2));
   1.147 +    alg.tourNodes(std::back_inserter(vec2));
   1.148 +    check(checkTour(g, alg.tourNodes()), alg_name + ": Wrong node sequence");
   1.149 +    check(checkTour(g, list1), alg_name + ": Wrong node sequence");
   1.150 +    check(checkTour(g, vec1), alg_name + ": Wrong node sequence");
   1.151 +    check(checkTour(g, list2), alg_name + ": Wrong node sequence");
   1.152 +    check(checkTour(g, vec2), alg_name + ": Wrong node sequence");
   1.153 +    check(checkCost(g, vec1, constMap<Edge, int>(1), esize),
   1.154 +      alg_name + ": Wrong tour cost");
   1.155 +
   1.156 +    SimplePath<FullGraph> path;
   1.157 +    alg.tour(path);
   1.158 +    check(path.length() == esize, alg_name + ": Wrong tour");
   1.159 +    check(checkTourPath(g, path), alg_name + ": Wrong tour");
   1.160 +    check(checkCost(g, path, constMap<Edge, int>(1), esize),
   1.161 +      alg_name + ": Wrong tour cost");
   1.162 +  }
   1.163 +}
   1.164 +
   1.165 +// Tests a TSP algorithm on random graphs
   1.166 +template <typename TSP>
   1.167 +void tspTestRandom(const std::string &alg_name) {
   1.168 +  GRAPH_TYPEDEFS(FullGraph);
   1.169 +
   1.170 +  FullGraph g(20);
   1.171 +  FullGraph::NodeMap<dim2::Point<double> > pos(g);
   1.172 +  DoubleEdgeMap cost(g);
   1.173 +
   1.174 +  TSP alg(g, cost);
   1.175 +  Opt2Tsp<DoubleEdgeMap > opt2(g, cost);
   1.176 +
   1.177 +  for (int i = 1; i <= 3; i++) {
   1.178 +    for (NodeIt u(g); u != INVALID; ++u) {
   1.179 +      pos[u] = dim2::Point<double>(rnd(), rnd());
   1.180 +    }
   1.181 +    for (NodeIt u(g); u != INVALID; ++u) {
   1.182 +      for (NodeIt v(g); v != INVALID; ++v) {
   1.183 +        if (u == v) continue;
   1.184 +        cost[g.edge(u, v)] = (pos[u] - pos[v]).normSquare();
   1.185 +      }
   1.186 +    }
   1.187 +    
   1.188 +    check(alg.run() > 0, alg_name + ": Wrong total cost");
   1.189 +
   1.190 +    std::vector<Node> vec;
   1.191 +    alg.tourNodes(std::back_inserter(vec));
   1.192 +    check(checkTour(g, vec), alg_name + ": Wrong node sequence");
   1.193 +    check(checkCost(g, vec, cost, alg.tourCost()),
   1.194 +      alg_name + ": Wrong tour cost");
   1.195 +
   1.196 +    SimplePath<FullGraph> path;
   1.197 +    alg.tour(path);
   1.198 +    check(checkTourPath(g, path), alg_name + ": Wrong tour");
   1.199 +    check(checkCost(g, path, cost, alg.tourCost()),
   1.200 +      alg_name + ": Wrong tour cost");
   1.201 +    
   1.202 +    check(!Tolerance<double>().less(alg.tourCost(), opt2.run(alg.tourNodes())),
   1.203 +      "2-opt improvement: Wrong total cost");
   1.204 +    check(checkTour(g, opt2.tourNodes()),
   1.205 +      "2-opt improvement: Wrong node sequence");
   1.206 +    check(checkCost(g, opt2.tourNodes(), cost, opt2.tourCost()),
   1.207 +      "2-opt improvement: Wrong tour cost");
   1.208 +    
   1.209 +    check(!Tolerance<double>().less(alg.tourCost(), opt2.run(path)),
   1.210 +      "2-opt improvement: Wrong total cost");
   1.211 +    check(checkTour(g, opt2.tourNodes()),
   1.212 +      "2-opt improvement: Wrong node sequence");
   1.213 +    check(checkCost(g, opt2.tourNodes(), cost, opt2.tourCost()),
   1.214 +      "2-opt improvement: Wrong tour cost");
   1.215 +  }
   1.216 +}
   1.217 +
   1.218 +// Algorithm class for Nearest Insertion 
   1.219 +template <typename CM>
   1.220 +class NearestInsertionTsp : public InsertionTsp<CM> {
   1.221 +public:
   1.222 +  NearestInsertionTsp(const FullGraph &gr, const CM &cost)
   1.223 +    : InsertionTsp<CM>(gr, cost) {}
   1.224 +  typename CM::Value run() {
   1.225 +    return InsertionTsp<CM>::run(InsertionTsp<CM>::NEAREST);
   1.226 +  }
   1.227 +};
   1.228 +
   1.229 +// Algorithm class for Farthest Insertion 
   1.230 +template <typename CM>
   1.231 +class FarthestInsertionTsp : public InsertionTsp<CM> {
   1.232 +public:
   1.233 +  FarthestInsertionTsp(const FullGraph &gr, const CM &cost)
   1.234 +    : InsertionTsp<CM>(gr, cost) {}
   1.235 +  typename CM::Value run() {
   1.236 +    return InsertionTsp<CM>::run(InsertionTsp<CM>::FARTHEST);
   1.237 +  }
   1.238 +};
   1.239 +
   1.240 +// Algorithm class for Cheapest Insertion 
   1.241 +template <typename CM>
   1.242 +class CheapestInsertionTsp : public InsertionTsp<CM> {
   1.243 +public:
   1.244 +  CheapestInsertionTsp(const FullGraph &gr, const CM &cost)
   1.245 +    : InsertionTsp<CM>(gr, cost) {}
   1.246 +  typename CM::Value run() {
   1.247 +    return InsertionTsp<CM>::run(InsertionTsp<CM>::CHEAPEST);
   1.248 +  }
   1.249 +};
   1.250 +
   1.251 +// Algorithm class for Random Insertion 
   1.252 +template <typename CM>
   1.253 +class RandomInsertionTsp : public InsertionTsp<CM> {
   1.254 +public:
   1.255 +  RandomInsertionTsp(const FullGraph &gr, const CM &cost)
   1.256 +    : InsertionTsp<CM>(gr, cost) {}
   1.257 +  typename CM::Value run() {
   1.258 +    return InsertionTsp<CM>::run(InsertionTsp<CM>::RANDOM);
   1.259 +  }
   1.260 +};
   1.261 +
   1.262 +int main() {
   1.263 +  GRAPH_TYPEDEFS(FullGraph);
   1.264 +
   1.265 +  // metricCostTest();
   1.266 +
   1.267 +  tspTestSmall<NearestNeighborTsp<ConstMap<Edge, int> > >("Nearest Neighbor");
   1.268 +  tspTestSmall<GreedyTsp<ConstMap<Edge, int> > >("Greedy");
   1.269 +  tspTestSmall<NearestInsertionTsp<ConstMap<Edge, int> > >("Nearest Insertion");
   1.270 +  tspTestSmall<FarthestInsertionTsp<ConstMap<Edge, int> > >("Farthest Insertion");
   1.271 +  tspTestSmall<CheapestInsertionTsp<ConstMap<Edge, int> > >("Cheapest Insertion");
   1.272 +  tspTestSmall<RandomInsertionTsp<ConstMap<Edge, int> > >("Random Insertion");
   1.273 +  tspTestSmall<ChristofidesTsp<ConstMap<Edge, int> > >("Christofides");
   1.274 +  tspTestSmall<Opt2Tsp<ConstMap<Edge, int> > >("2-opt");
   1.275 +
   1.276 +  tspTestRandom<NearestNeighborTsp<DoubleEdgeMap > >("Nearest Neighbor");
   1.277 +  tspTestRandom<GreedyTsp<DoubleEdgeMap > >("Greedy");
   1.278 +  tspTestRandom<NearestInsertionTsp<DoubleEdgeMap > >("Nearest Insertion");
   1.279 +  tspTestRandom<FarthestInsertionTsp<DoubleEdgeMap > >("Farthest Insertion");
   1.280 +  tspTestRandom<CheapestInsertionTsp<DoubleEdgeMap > >("Cheapest Insertion");
   1.281 +  tspTestRandom<RandomInsertionTsp<DoubleEdgeMap > >("Random Insertion");
   1.282 +  tspTestRandom<ChristofidesTsp<DoubleEdgeMap > >("Christofides");
   1.283 +  tspTestRandom<Opt2Tsp<DoubleEdgeMap > >("2-opt");
   1.284 +
   1.285 +  return 0;
   1.286 +}