test/tsp_test.cc
author Alpar Juttner <alpar@cs.elte.hu>
Fri, 15 Mar 2013 17:15:46 +0100
changeset 1215 f7247b5c04bf
parent 1203 07682e24c4e8
child 1270 dceba191c00d
permissions -rw-r--r--
Merge
     1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
     2  *
     3  * This file is a part of LEMON, a generic C++ optimization library.
     4  *
     5  * Copyright (C) 2003-2010
     6  * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
     7  * (Egervary Research Group on Combinatorial Optimization, EGRES).
     8  *
     9  * Permission to use, modify and distribute this software is granted
    10  * provided that this copyright notice appears in all copies. For
    11  * precise terms see the accompanying LICENSE file.
    12  *
    13  * This software is provided "AS IS" with no warranty of any kind,
    14  * express or implied, and with no claim as to its suitability for any
    15  * purpose.
    16  *
    17  */
    18 
    19 #include <iostream>
    20 
    21 #include <lemon/full_graph.h>
    22 #include <lemon/math.h>
    23 #include <lemon/maps.h>
    24 #include <lemon/random.h>
    25 #include <lemon/dim2.h>
    26 
    27 #include <lemon/nearest_neighbor_tsp.h>
    28 #include <lemon/greedy_tsp.h>
    29 #include <lemon/insertion_tsp.h>
    30 #include <lemon/christofides_tsp.h>
    31 #include <lemon/opt2_tsp.h>
    32 
    33 #include "test_tools.h"
    34 
    35 using namespace lemon;
    36 
    37 // // Tests checkMetricCost() function
    38 // void metricCostTest() {
    39 //   GRAPH_TYPEDEFS(FullGraph);
    40 //   FullGraph g(10);
    41 //   check(checkMetricCost(g, constMap<Edge>(0)), "Wrong checkMetricCost()");
    42 //   check(checkMetricCost(g, constMap<Edge>(1)), "Wrong checkMetricCost()");
    43 //   check(!checkMetricCost(g, constMap<Edge>(-1)), "Wrong checkMetricCost()");
    44 //   
    45 //   FullGraph::EdgeMap<float> cost(g);
    46 //   for (NodeIt u(g); u != INVALID; ++u) {
    47 //     for (NodeIt v(g); v != INVALID; ++v) {
    48 //       if (u == v) continue;
    49 //       float x1 = g.id(u), x2 = g.id(v);
    50 //       float y1 = x1 * x1, y2 = x2 * x2;
    51 //       cost[g.edge(u, v)] = std::sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));
    52 //     }
    53 //   }
    54 //   check(checkMetricCost(g, cost), "Wrong checkMetricCost()");
    55 //   float eps = Tolerance<float>::defaultEpsilon();
    56 //   cost[g.edge(g(0), g(9))] =
    57 //     cost[g.edge(g(0), g(8))] + cost[g.edge(g(8), g(9))] + eps * 2;
    58 //   check(!checkMetricCost(g, cost), "Wrong checkMetricCost()");
    59 //   check(checkMetricCost(g, cost, Tolerance<float>(eps * 4)),
    60 //     "Wrong checkMetricCost()");
    61 // }
    62 
    63 // Checks tour validity
    64 template <typename Container>
    65 bool checkTour(const FullGraph &gr, const Container &p) {
    66   FullGraph::NodeMap<bool> used(gr, false);
    67   
    68   int node_cnt = 0;
    69   for (typename Container::const_iterator it = p.begin(); it != p.end(); ++it) {
    70     FullGraph::Node node = *it;
    71     if (used[node]) return false;
    72     used[node] = true;
    73     ++node_cnt;
    74   }
    75   
    76   return (node_cnt == gr.nodeNum());
    77 }
    78 
    79 // Checks tour validity
    80 bool checkTourPath(const FullGraph &gr, const Path<FullGraph> &p) {
    81   FullGraph::NodeMap<bool> used(gr, false);
    82   
    83   if (!checkPath(gr, p)) return false;
    84   if (gr.nodeNum() <= 1 && p.length() != 0) return false;
    85   if (gr.nodeNum() > 1 && p.length() != gr.nodeNum()) return false;
    86 
    87   for (int i = 0; i < p.length(); ++i) {
    88     if (used[gr.target(p.nth(i))]) return false;
    89     used[gr.target(p.nth(i))] = true;
    90   }
    91   return true;
    92 }
    93 
    94 // Checks tour cost
    95 template <typename CostMap>
    96 bool checkCost(const FullGraph &gr, const std::vector<FullGraph::Node> &p,
    97                const CostMap &cost, typename CostMap::Value total)
    98 {
    99   typedef typename CostMap::Value Cost;
   100 
   101   Cost s = 0;
   102   for (int i = 0; i < int(p.size()) - 1; ++i)
   103     s += cost[gr.edge(p[i], p[i+1])];
   104   if (int(p.size()) >= 2)
   105     s += cost[gr.edge(p.back(), p.front())];
   106 
   107   return !Tolerance<Cost>().different(s, total);
   108 }
   109 
   110 // Checks tour cost
   111 template <typename CostMap>
   112 bool checkCost(const FullGraph &, const Path<FullGraph> &p,
   113                const CostMap &cost, typename CostMap::Value total)
   114 {
   115   typedef typename CostMap::Value Cost;
   116 
   117   Cost s = 0;
   118   for (int i = 0; i < p.length(); ++i)
   119     s += cost[p.nth(i)];
   120 
   121   return !Tolerance<Cost>().different(s, total);
   122 }
   123 
   124 // Tests a TSP algorithm on small graphs
   125 template <typename TSP>
   126 void tspTestSmall(const std::string &alg_name) {
   127   GRAPH_TYPEDEFS(FullGraph);
   128 
   129   for (int n = 0; n <= 5; ++n) {
   130     FullGraph g(n);
   131     unsigned nsize = n;
   132     int esize = n <= 1 ? 0 : n;
   133 
   134     TSP alg(g, constMap<Edge, int>(1));
   135 
   136     check(alg.run() == esize, alg_name + ": Wrong total cost");
   137     check(alg.tourCost() == esize, alg_name + ": Wrong total cost");
   138 
   139     std::list<Node> list1(nsize), list2;
   140     std::vector<Node> vec1(nsize), vec2;
   141     alg.tourNodes(list1.begin());
   142     alg.tourNodes(vec1.begin());
   143     alg.tourNodes(std::front_inserter(list2));
   144     alg.tourNodes(std::back_inserter(vec2));
   145     check(checkTour(g, alg.tourNodes()), alg_name + ": Wrong node sequence");
   146     check(checkTour(g, list1), alg_name + ": Wrong node sequence");
   147     check(checkTour(g, vec1), alg_name + ": Wrong node sequence");
   148     check(checkTour(g, list2), alg_name + ": Wrong node sequence");
   149     check(checkTour(g, vec2), alg_name + ": Wrong node sequence");
   150     check(checkCost(g, vec1, constMap<Edge, int>(1), esize),
   151       alg_name + ": Wrong tour cost");
   152 
   153     SimplePath<FullGraph> path;
   154     alg.tour(path);
   155     check(path.length() == esize, alg_name + ": Wrong tour");
   156     check(checkTourPath(g, path), alg_name + ": Wrong tour");
   157     check(checkCost(g, path, constMap<Edge, int>(1), esize),
   158       alg_name + ": Wrong tour cost");
   159   }
   160 }
   161 
   162 // Tests a TSP algorithm on random graphs
   163 template <typename TSP>
   164 void tspTestRandom(const std::string &alg_name) {
   165   GRAPH_TYPEDEFS(FullGraph);
   166 
   167   FullGraph g(20);
   168   FullGraph::NodeMap<dim2::Point<double> > pos(g);
   169   DoubleEdgeMap cost(g);
   170 
   171   TSP alg(g, cost);
   172   Opt2Tsp<DoubleEdgeMap > opt2(g, cost);
   173 
   174   for (int i = 1; i <= 3; i++) {
   175     for (NodeIt u(g); u != INVALID; ++u) {
   176       pos[u] = dim2::Point<double>(rnd(), rnd());
   177     }
   178     for (NodeIt u(g); u != INVALID; ++u) {
   179       for (NodeIt v(g); v != INVALID; ++v) {
   180         if (u == v) continue;
   181         cost[g.edge(u, v)] = (pos[u] - pos[v]).normSquare();
   182       }
   183     }
   184     
   185     check(alg.run() > 0, alg_name + ": Wrong total cost");
   186 
   187     std::vector<Node> vec;
   188     alg.tourNodes(std::back_inserter(vec));
   189     check(checkTour(g, vec), alg_name + ": Wrong node sequence");
   190     check(checkCost(g, vec, cost, alg.tourCost()),
   191       alg_name + ": Wrong tour cost");
   192 
   193     SimplePath<FullGraph> path;
   194     alg.tour(path);
   195     check(checkTourPath(g, path), alg_name + ": Wrong tour");
   196     check(checkCost(g, path, cost, alg.tourCost()),
   197       alg_name + ": Wrong tour cost");
   198     
   199     check(!Tolerance<double>().less(alg.tourCost(), opt2.run(alg.tourNodes())),
   200       "2-opt improvement: Wrong total cost");
   201     check(checkTour(g, opt2.tourNodes()),
   202       "2-opt improvement: Wrong node sequence");
   203     check(checkCost(g, opt2.tourNodes(), cost, opt2.tourCost()),
   204       "2-opt improvement: Wrong tour cost");
   205     
   206     check(!Tolerance<double>().less(alg.tourCost(), opt2.run(path)),
   207       "2-opt improvement: Wrong total cost");
   208     check(checkTour(g, opt2.tourNodes()),
   209       "2-opt improvement: Wrong node sequence");
   210     check(checkCost(g, opt2.tourNodes(), cost, opt2.tourCost()),
   211       "2-opt improvement: Wrong tour cost");
   212   }
   213 }
   214 
   215 // Algorithm class for Nearest Insertion 
   216 template <typename CM>
   217 class NearestInsertionTsp : public InsertionTsp<CM> {
   218 public:
   219   NearestInsertionTsp(const FullGraph &gr, const CM &cost)
   220     : InsertionTsp<CM>(gr, cost) {}
   221   typename CM::Value run() {
   222     return InsertionTsp<CM>::run(InsertionTsp<CM>::NEAREST);
   223   }
   224 };
   225 
   226 // Algorithm class for Farthest Insertion 
   227 template <typename CM>
   228 class FarthestInsertionTsp : public InsertionTsp<CM> {
   229 public:
   230   FarthestInsertionTsp(const FullGraph &gr, const CM &cost)
   231     : InsertionTsp<CM>(gr, cost) {}
   232   typename CM::Value run() {
   233     return InsertionTsp<CM>::run(InsertionTsp<CM>::FARTHEST);
   234   }
   235 };
   236 
   237 // Algorithm class for Cheapest Insertion 
   238 template <typename CM>
   239 class CheapestInsertionTsp : public InsertionTsp<CM> {
   240 public:
   241   CheapestInsertionTsp(const FullGraph &gr, const CM &cost)
   242     : InsertionTsp<CM>(gr, cost) {}
   243   typename CM::Value run() {
   244     return InsertionTsp<CM>::run(InsertionTsp<CM>::CHEAPEST);
   245   }
   246 };
   247 
   248 // Algorithm class for Random Insertion 
   249 template <typename CM>
   250 class RandomInsertionTsp : public InsertionTsp<CM> {
   251 public:
   252   RandomInsertionTsp(const FullGraph &gr, const CM &cost)
   253     : InsertionTsp<CM>(gr, cost) {}
   254   typename CM::Value run() {
   255     return InsertionTsp<CM>::run(InsertionTsp<CM>::RANDOM);
   256   }
   257 };
   258 
   259 int main() {
   260   GRAPH_TYPEDEFS(FullGraph);
   261 
   262   // metricCostTest();
   263 
   264   tspTestSmall<NearestNeighborTsp<ConstMap<Edge, int> > >("Nearest Neighbor");
   265   tspTestSmall<GreedyTsp<ConstMap<Edge, int> > >("Greedy");
   266   tspTestSmall<NearestInsertionTsp<ConstMap<Edge, int> > >("Nearest Insertion");
   267   tspTestSmall<FarthestInsertionTsp<ConstMap<Edge, int> > >("Farthest Insertion");
   268   tspTestSmall<CheapestInsertionTsp<ConstMap<Edge, int> > >("Cheapest Insertion");
   269   tspTestSmall<RandomInsertionTsp<ConstMap<Edge, int> > >("Random Insertion");
   270   tspTestSmall<ChristofidesTsp<ConstMap<Edge, int> > >("Christofides");
   271   tspTestSmall<Opt2Tsp<ConstMap<Edge, int> > >("2-opt");
   272 
   273   tspTestRandom<NearestNeighborTsp<DoubleEdgeMap > >("Nearest Neighbor");
   274   tspTestRandom<GreedyTsp<DoubleEdgeMap > >("Greedy");
   275   tspTestRandom<NearestInsertionTsp<DoubleEdgeMap > >("Nearest Insertion");
   276   tspTestRandom<FarthestInsertionTsp<DoubleEdgeMap > >("Farthest Insertion");
   277   tspTestRandom<CheapestInsertionTsp<DoubleEdgeMap > >("Cheapest Insertion");
   278   tspTestRandom<RandomInsertionTsp<DoubleEdgeMap > >("Random Insertion");
   279   tspTestRandom<ChristofidesTsp<DoubleEdgeMap > >("Christofides");
   280   tspTestRandom<Opt2Tsp<DoubleEdgeMap > >("2-opt");
   281 
   282   return 0;
   283 }