tools/lgf-gen.cc
changeset 523 d9e43511d11c
child 524 06e0fb20a97c
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/tools/lgf-gen.cc	Mon Feb 23 11:30:15 2009 +0000
     1.3 @@ -0,0 +1,834 @@
     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-2009
     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 +/// \ingroup tools
    1.23 +/// \file
    1.24 +/// \brief Special plane digraph generator.
    1.25 +///
    1.26 +/// Graph generator application for various types of plane graphs.
    1.27 +///
    1.28 +/// See
    1.29 +/// \verbatim
    1.30 +///  lgf-gen --help
    1.31 +/// \endverbatim
    1.32 +/// for more info on the usage.
    1.33 +///
    1.34 +
    1.35 +
    1.36 +#include <algorithm>
    1.37 +#include <set>
    1.38 +#include <lemon/list_graph.h>
    1.39 +#include <lemon/random.h>
    1.40 +#include <lemon/dim2.h>
    1.41 +#include <lemon/bfs.h>
    1.42 +#include <lemon/counter.h>
    1.43 +#include <lemon/suurballe.h>
    1.44 +#include <lemon/graph_to_eps.h>
    1.45 +#include <lemon/lgf_writer.h>
    1.46 +#include <lemon/arg_parser.h>
    1.47 +#include <lemon/euler.h>
    1.48 +#include <lemon/math.h>
    1.49 +#include <lemon/kruskal.h>
    1.50 +#include <lemon/time_measure.h>
    1.51 +
    1.52 +using namespace lemon;
    1.53 +
    1.54 +typedef dim2::Point<double> Point;
    1.55 +
    1.56 +GRAPH_TYPEDEFS(ListGraph);
    1.57 +
    1.58 +bool progress=true;
    1.59 +
    1.60 +int N;
    1.61 +// int girth;
    1.62 +
    1.63 +ListGraph g;
    1.64 +
    1.65 +std::vector<Node> nodes;
    1.66 +ListGraph::NodeMap<Point> coords(g);
    1.67 +
    1.68 +
    1.69 +double totalLen(){
    1.70 +  double tlen=0;
    1.71 +  for(EdgeIt e(g);e!=INVALID;++e)
    1.72 +    tlen+=sqrt((coords[g.v(e)]-coords[g.u(e)]).normSquare());
    1.73 +  return tlen;
    1.74 +}
    1.75 +
    1.76 +int tsp_impr_num=0;
    1.77 +
    1.78 +const double EPSILON=1e-8;
    1.79 +bool tsp_improve(Node u, Node v)
    1.80 +{
    1.81 +  double luv=std::sqrt((coords[v]-coords[u]).normSquare());
    1.82 +  Node u2=u;
    1.83 +  Node v2=v;
    1.84 +  do {
    1.85 +    Node n;
    1.86 +    for(IncEdgeIt e(g,v2);(n=g.runningNode(e))==u2;++e) { }
    1.87 +    u2=v2;
    1.88 +    v2=n;
    1.89 +    if(luv+std::sqrt((coords[v2]-coords[u2]).normSquare())-EPSILON>
    1.90 +       std::sqrt((coords[u]-coords[u2]).normSquare())+
    1.91 +       std::sqrt((coords[v]-coords[v2]).normSquare()))
    1.92 +      {
    1.93 +         g.erase(findEdge(g,u,v));
    1.94 +         g.erase(findEdge(g,u2,v2));
    1.95 +        g.addEdge(u2,u);
    1.96 +        g.addEdge(v,v2);
    1.97 +        tsp_impr_num++;
    1.98 +        return true;
    1.99 +      }
   1.100 +  } while(v2!=u);
   1.101 +  return false;
   1.102 +}
   1.103 +
   1.104 +bool tsp_improve(Node u)
   1.105 +{
   1.106 +  for(IncEdgeIt e(g,u);e!=INVALID;++e)
   1.107 +    if(tsp_improve(u,g.runningNode(e))) return true;
   1.108 +  return false;
   1.109 +}
   1.110 +
   1.111 +void tsp_improve()
   1.112 +{
   1.113 +  bool b;
   1.114 +  do {
   1.115 +    b=false;
   1.116 +    for(NodeIt n(g);n!=INVALID;++n)
   1.117 +      if(tsp_improve(n)) b=true;
   1.118 +  } while(b);
   1.119 +}
   1.120 +
   1.121 +void tsp()
   1.122 +{
   1.123 +  for(int i=0;i<N;i++) g.addEdge(nodes[i],nodes[(i+1)%N]);
   1.124 +  tsp_improve();
   1.125 +}
   1.126 +
   1.127 +class Line
   1.128 +{
   1.129 +public:
   1.130 +  Point a;
   1.131 +  Point b;
   1.132 +  Line(Point _a,Point _b) :a(_a),b(_b) {}
   1.133 +  Line(Node _a,Node _b) : a(coords[_a]),b(coords[_b]) {}
   1.134 +  Line(const Arc &e) : a(coords[g.source(e)]),b(coords[g.target(e)]) {}
   1.135 +  Line(const Edge &e) : a(coords[g.u(e)]),b(coords[g.v(e)]) {}
   1.136 +};
   1.137 +
   1.138 +inline std::ostream& operator<<(std::ostream &os, const Line &l)
   1.139 +{
   1.140 +  os << l.a << "->" << l.b;
   1.141 +  return os;
   1.142 +}
   1.143 +
   1.144 +bool cross(Line a, Line b)
   1.145 +{
   1.146 +  Point ao=rot90(a.b-a.a);
   1.147 +  Point bo=rot90(b.b-b.a);
   1.148 +  return (ao*(b.a-a.a))*(ao*(b.b-a.a))<0 &&
   1.149 +    (bo*(a.a-b.a))*(bo*(a.b-b.a))<0;
   1.150 +}
   1.151 +
   1.152 +struct Parc
   1.153 +{
   1.154 +  Node a;
   1.155 +  Node b;
   1.156 +  double len;
   1.157 +};
   1.158 +
   1.159 +bool pedgeLess(Parc a,Parc b)
   1.160 +{
   1.161 +  return a.len<b.len;
   1.162 +}
   1.163 +
   1.164 +std::vector<Edge> arcs;
   1.165 +
   1.166 +namespace _delaunay_bits {
   1.167 +
   1.168 +  struct Part {
   1.169 +    int prev, curr, next;
   1.170 +
   1.171 +    Part(int p, int c, int n) : prev(p), curr(c), next(n) {}
   1.172 +  };
   1.173 +
   1.174 +  inline std::ostream& operator<<(std::ostream& os, const Part& part) {
   1.175 +    os << '(' << part.prev << ',' << part.curr << ',' << part.next << ')';
   1.176 +    return os;
   1.177 +  }
   1.178 +
   1.179 +  inline double circle_point(const Point& p, const Point& q, const Point& r) {
   1.180 +    double a = p.x * (q.y - r.y) + q.x * (r.y - p.y) + r.x * (p.y - q.y);
   1.181 +    if (a == 0) return std::numeric_limits<double>::quiet_NaN();
   1.182 +
   1.183 +    double d = (p.x * p.x + p.y * p.y) * (q.y - r.y) +
   1.184 +      (q.x * q.x + q.y * q.y) * (r.y - p.y) +
   1.185 +      (r.x * r.x + r.y * r.y) * (p.y - q.y);
   1.186 +
   1.187 +    double e = (p.x * p.x + p.y * p.y) * (q.x - r.x) +
   1.188 +      (q.x * q.x + q.y * q.y) * (r.x - p.x) +
   1.189 +      (r.x * r.x + r.y * r.y) * (p.x - q.x);
   1.190 +
   1.191 +    double f = (p.x * p.x + p.y * p.y) * (q.x * r.y - r.x * q.y) +
   1.192 +      (q.x * q.x + q.y * q.y) * (r.x * p.y - p.x * r.y) +
   1.193 +      (r.x * r.x + r.y * r.y) * (p.x * q.y - q.x * p.y);
   1.194 +
   1.195 +    return d / (2 * a) + sqrt((d * d + e * e) / (4 * a * a) + f / a);
   1.196 +  }
   1.197 +
   1.198 +  inline bool circle_form(const Point& p, const Point& q, const Point& r) {
   1.199 +    return rot90(q - p) * (r - q) < 0.0;
   1.200 +  }
   1.201 +
   1.202 +  inline double intersection(const Point& p, const Point& q, double sx) {
   1.203 +    const double epsilon = 1e-8;
   1.204 +
   1.205 +    if (p.x == q.x) return (p.y + q.y) / 2.0;
   1.206 +
   1.207 +    if (sx < p.x + epsilon) return p.y;
   1.208 +    if (sx < q.x + epsilon) return q.y;
   1.209 +
   1.210 +    double a = q.x - p.x;
   1.211 +    double b = (q.x - sx) * p.y - (p.x - sx) * q.y;
   1.212 +    double d = (q.x - sx) * (p.x - sx) * (p - q).normSquare();
   1.213 +    return (b - sqrt(d)) / a;
   1.214 +  }
   1.215 +
   1.216 +  struct YLess {
   1.217 +
   1.218 +
   1.219 +    YLess(const std::vector<Point>& points, double& sweep)
   1.220 +      : _points(points), _sweep(sweep) {}
   1.221 +
   1.222 +    bool operator()(const Part& l, const Part& r) const {
   1.223 +      const double epsilon = 1e-8;
   1.224 +
   1.225 +      //      std::cerr << l << " vs " << r << std::endl;
   1.226 +      double lbx = l.prev != -1 ?
   1.227 +        intersection(_points[l.prev], _points[l.curr], _sweep) :
   1.228 +        - std::numeric_limits<double>::infinity();
   1.229 +      double rbx = r.prev != -1 ?
   1.230 +        intersection(_points[r.prev], _points[r.curr], _sweep) :
   1.231 +        - std::numeric_limits<double>::infinity();
   1.232 +      double lex = l.next != -1 ?
   1.233 +        intersection(_points[l.curr], _points[l.next], _sweep) :
   1.234 +        std::numeric_limits<double>::infinity();
   1.235 +      double rex = r.next != -1 ?
   1.236 +        intersection(_points[r.curr], _points[r.next], _sweep) :
   1.237 +        std::numeric_limits<double>::infinity();
   1.238 +
   1.239 +      if (lbx > lex) std::swap(lbx, lex);
   1.240 +      if (rbx > rex) std::swap(rbx, rex);
   1.241 +
   1.242 +      if (lex < epsilon + rex && lbx + epsilon < rex) return true;
   1.243 +      if (rex < epsilon + lex && rbx + epsilon < lex) return false;
   1.244 +      return lex < rex;
   1.245 +    }
   1.246 +
   1.247 +    const std::vector<Point>& _points;
   1.248 +    double& _sweep;
   1.249 +  };
   1.250 +
   1.251 +  struct BeachIt;
   1.252 +
   1.253 +  typedef std::multimap<double, BeachIt> SpikeHeap;
   1.254 +
   1.255 +  typedef std::multimap<Part, SpikeHeap::iterator, YLess> Beach;
   1.256 +
   1.257 +  struct BeachIt {
   1.258 +    Beach::iterator it;
   1.259 +
   1.260 +    BeachIt(Beach::iterator iter) : it(iter) {}
   1.261 +  };
   1.262 +
   1.263 +}
   1.264 +
   1.265 +inline void delaunay() {
   1.266 +  Counter cnt("Number of arcs added: ");
   1.267 +
   1.268 +  using namespace _delaunay_bits;
   1.269 +
   1.270 +  typedef _delaunay_bits::Part Part;
   1.271 +  typedef std::vector<std::pair<double, int> > SiteHeap;
   1.272 +
   1.273 +
   1.274 +  std::vector<Point> points;
   1.275 +  std::vector<Node> nodes;
   1.276 +
   1.277 +  for (NodeIt it(g); it != INVALID; ++it) {
   1.278 +    nodes.push_back(it);
   1.279 +    points.push_back(coords[it]);
   1.280 +  }
   1.281 +
   1.282 +  SiteHeap siteheap(points.size());
   1.283 +
   1.284 +  double sweep;
   1.285 +
   1.286 +
   1.287 +  for (int i = 0; i < int(siteheap.size()); ++i) {
   1.288 +    siteheap[i] = std::make_pair(points[i].x, i);
   1.289 +  }
   1.290 +
   1.291 +  std::sort(siteheap.begin(), siteheap.end());
   1.292 +  sweep = siteheap.front().first;
   1.293 +
   1.294 +  YLess yless(points, sweep);
   1.295 +  Beach beach(yless);
   1.296 +
   1.297 +  SpikeHeap spikeheap;
   1.298 +
   1.299 +  std::set<std::pair<int, int> > arcs;
   1.300 +
   1.301 +  int siteindex = 0;
   1.302 +  {
   1.303 +    SiteHeap front;
   1.304 +
   1.305 +    while (siteindex < int(siteheap.size()) &&
   1.306 +           siteheap[0].first == siteheap[siteindex].first) {
   1.307 +      front.push_back(std::make_pair(points[siteheap[siteindex].second].y,
   1.308 +                                     siteheap[siteindex].second));
   1.309 +      ++siteindex;
   1.310 +    }
   1.311 +
   1.312 +    std::sort(front.begin(), front.end());
   1.313 +
   1.314 +    for (int i = 0; i < int(front.size()); ++i) {
   1.315 +      int prev = (i == 0 ? -1 : front[i - 1].second);
   1.316 +      int curr = front[i].second;
   1.317 +      int next = (i + 1 == int(front.size()) ? -1 : front[i + 1].second);
   1.318 +
   1.319 +      beach.insert(std::make_pair(Part(prev, curr, next),
   1.320 +                                  spikeheap.end()));
   1.321 +    }
   1.322 +  }
   1.323 +
   1.324 +  while (siteindex < int(points.size()) || !spikeheap.empty()) {
   1.325 +
   1.326 +    SpikeHeap::iterator spit = spikeheap.begin();
   1.327 +
   1.328 +    if (siteindex < int(points.size()) &&
   1.329 +        (spit == spikeheap.end() || siteheap[siteindex].first < spit->first)) {
   1.330 +      int site = siteheap[siteindex].second;
   1.331 +      sweep = siteheap[siteindex].first;
   1.332 +
   1.333 +      Beach::iterator bit = beach.upper_bound(Part(site, site, site));
   1.334 +
   1.335 +      if (bit->second != spikeheap.end()) {
   1.336 +        spikeheap.erase(bit->second);
   1.337 +      }
   1.338 +
   1.339 +      int prev = bit->first.prev;
   1.340 +      int curr = bit->first.curr;
   1.341 +      int next = bit->first.next;
   1.342 +
   1.343 +      beach.erase(bit);
   1.344 +
   1.345 +      SpikeHeap::iterator pit = spikeheap.end();
   1.346 +      if (prev != -1 &&
   1.347 +          circle_form(points[prev], points[curr], points[site])) {
   1.348 +        double x = circle_point(points[prev], points[curr], points[site]);
   1.349 +        pit = spikeheap.insert(std::make_pair(x, BeachIt(beach.end())));
   1.350 +        pit->second.it =
   1.351 +          beach.insert(std::make_pair(Part(prev, curr, site), pit));
   1.352 +      } else {
   1.353 +        beach.insert(std::make_pair(Part(prev, curr, site), pit));
   1.354 +      }
   1.355 +
   1.356 +      beach.insert(std::make_pair(Part(curr, site, curr), spikeheap.end()));
   1.357 +
   1.358 +      SpikeHeap::iterator nit = spikeheap.end();
   1.359 +      if (next != -1 &&
   1.360 +          circle_form(points[site], points[curr],points[next])) {
   1.361 +        double x = circle_point(points[site], points[curr], points[next]);
   1.362 +        nit = spikeheap.insert(std::make_pair(x, BeachIt(beach.end())));
   1.363 +        nit->second.it =
   1.364 +          beach.insert(std::make_pair(Part(site, curr, next), nit));
   1.365 +      } else {
   1.366 +        beach.insert(std::make_pair(Part(site, curr, next), nit));
   1.367 +      }
   1.368 +
   1.369 +      ++siteindex;
   1.370 +    } else {
   1.371 +      sweep = spit->first;
   1.372 +
   1.373 +      Beach::iterator bit = spit->second.it;
   1.374 +
   1.375 +      int prev = bit->first.prev;
   1.376 +      int curr = bit->first.curr;
   1.377 +      int next = bit->first.next;
   1.378 +
   1.379 +      {
   1.380 +        std::pair<int, int> arc;
   1.381 +
   1.382 +        arc = prev < curr ?
   1.383 +          std::make_pair(prev, curr) : std::make_pair(curr, prev);
   1.384 +
   1.385 +        if (arcs.find(arc) == arcs.end()) {
   1.386 +          arcs.insert(arc);
   1.387 +          g.addEdge(nodes[prev], nodes[curr]);
   1.388 +          ++cnt;
   1.389 +        }
   1.390 +
   1.391 +        arc = curr < next ?
   1.392 +          std::make_pair(curr, next) : std::make_pair(next, curr);
   1.393 +
   1.394 +        if (arcs.find(arc) == arcs.end()) {
   1.395 +          arcs.insert(arc);
   1.396 +          g.addEdge(nodes[curr], nodes[next]);
   1.397 +          ++cnt;
   1.398 +        }
   1.399 +      }
   1.400 +
   1.401 +      Beach::iterator pbit = bit; --pbit;
   1.402 +      int ppv = pbit->first.prev;
   1.403 +      Beach::iterator nbit = bit; ++nbit;
   1.404 +      int nnt = nbit->first.next;
   1.405 +
   1.406 +      if (bit->second != spikeheap.end()) spikeheap.erase(bit->second);
   1.407 +      if (pbit->second != spikeheap.end()) spikeheap.erase(pbit->second);
   1.408 +      if (nbit->second != spikeheap.end()) spikeheap.erase(nbit->second);
   1.409 +
   1.410 +      beach.erase(nbit);
   1.411 +      beach.erase(bit);
   1.412 +      beach.erase(pbit);
   1.413 +
   1.414 +      SpikeHeap::iterator pit = spikeheap.end();
   1.415 +      if (ppv != -1 && ppv != next &&
   1.416 +          circle_form(points[ppv], points[prev], points[next])) {
   1.417 +        double x = circle_point(points[ppv], points[prev], points[next]);
   1.418 +        if (x < sweep) x = sweep;
   1.419 +        pit = spikeheap.insert(std::make_pair(x, BeachIt(beach.end())));
   1.420 +        pit->second.it =
   1.421 +          beach.insert(std::make_pair(Part(ppv, prev, next), pit));
   1.422 +      } else {
   1.423 +        beach.insert(std::make_pair(Part(ppv, prev, next), pit));
   1.424 +      }
   1.425 +
   1.426 +      SpikeHeap::iterator nit = spikeheap.end();
   1.427 +      if (nnt != -1 && prev != nnt &&
   1.428 +          circle_form(points[prev], points[next], points[nnt])) {
   1.429 +        double x = circle_point(points[prev], points[next], points[nnt]);
   1.430 +        if (x < sweep) x = sweep;
   1.431 +        nit = spikeheap.insert(std::make_pair(x, BeachIt(beach.end())));
   1.432 +        nit->second.it =
   1.433 +          beach.insert(std::make_pair(Part(prev, next, nnt), nit));
   1.434 +      } else {
   1.435 +        beach.insert(std::make_pair(Part(prev, next, nnt), nit));
   1.436 +      }
   1.437 +
   1.438 +    }
   1.439 +  }
   1.440 +
   1.441 +  for (Beach::iterator it = beach.begin(); it != beach.end(); ++it) {
   1.442 +    int curr = it->first.curr;
   1.443 +    int next = it->first.next;
   1.444 +
   1.445 +    if (next == -1) continue;
   1.446 +
   1.447 +    std::pair<int, int> arc;
   1.448 +
   1.449 +    arc = curr < next ?
   1.450 +      std::make_pair(curr, next) : std::make_pair(next, curr);
   1.451 +
   1.452 +    if (arcs.find(arc) == arcs.end()) {
   1.453 +      arcs.insert(arc);
   1.454 +      g.addEdge(nodes[curr], nodes[next]);
   1.455 +      ++cnt;
   1.456 +    }
   1.457 +  }
   1.458 +}
   1.459 +
   1.460 +void sparse(int d)
   1.461 +{
   1.462 +  Counter cnt("Number of arcs removed: ");
   1.463 +  Bfs<ListGraph> bfs(g);
   1.464 +  for(std::vector<Edge>::reverse_iterator ei=arcs.rbegin();
   1.465 +      ei!=arcs.rend();++ei)
   1.466 +    {
   1.467 +      Node a=g.u(*ei);
   1.468 +      Node b=g.v(*ei);
   1.469 +      g.erase(*ei);
   1.470 +      bfs.run(a,b);
   1.471 +      if(bfs.predArc(b)==INVALID || bfs.dist(b)>d)
   1.472 +        g.addEdge(a,b);
   1.473 +      else cnt++;
   1.474 +    }
   1.475 +}
   1.476 +
   1.477 +void sparse2(int d)
   1.478 +{
   1.479 +  Counter cnt("Number of arcs removed: ");
   1.480 +  for(std::vector<Edge>::reverse_iterator ei=arcs.rbegin();
   1.481 +      ei!=arcs.rend();++ei)
   1.482 +    {
   1.483 +      Node a=g.u(*ei);
   1.484 +      Node b=g.v(*ei);
   1.485 +      g.erase(*ei);
   1.486 +      ConstMap<Arc,int> cegy(1);
   1.487 +      Suurballe<ListGraph,ConstMap<Arc,int> > sur(g,cegy,a,b);
   1.488 +      int k=sur.run(2);
   1.489 +      if(k<2 || sur.totalLength()>d)
   1.490 +        g.addEdge(a,b);
   1.491 +      else cnt++;
   1.492 +//       else std::cout << "Remove arc " << g.id(a) << "-" << g.id(b) << '\n';
   1.493 +    }
   1.494 +}
   1.495 +
   1.496 +void sparseTriangle(int d)
   1.497 +{
   1.498 +  Counter cnt("Number of arcs added: ");
   1.499 +  std::vector<Parc> pedges;
   1.500 +  for(NodeIt n(g);n!=INVALID;++n)
   1.501 +    for(NodeIt m=++(NodeIt(n));m!=INVALID;++m)
   1.502 +      {
   1.503 +        Parc p;
   1.504 +        p.a=n;
   1.505 +        p.b=m;
   1.506 +        p.len=(coords[m]-coords[n]).normSquare();
   1.507 +        pedges.push_back(p);
   1.508 +      }
   1.509 +  std::sort(pedges.begin(),pedges.end(),pedgeLess);
   1.510 +  for(std::vector<Parc>::iterator pi=pedges.begin();pi!=pedges.end();++pi)
   1.511 +    {
   1.512 +      Line li(pi->a,pi->b);
   1.513 +      EdgeIt e(g);
   1.514 +      for(;e!=INVALID && !cross(e,li);++e) ;
   1.515 +      Edge ne;
   1.516 +      if(e==INVALID) {
   1.517 +        ConstMap<Arc,int> cegy(1);
   1.518 +        Suurballe<ListGraph,ConstMap<Arc,int> >
   1.519 +          sur(g,cegy,pi->a,pi->b);
   1.520 +        int k=sur.run(2);
   1.521 +        if(k<2 || sur.totalLength()>d)
   1.522 +          {
   1.523 +            ne=g.addEdge(pi->a,pi->b);
   1.524 +            arcs.push_back(ne);
   1.525 +            cnt++;
   1.526 +          }
   1.527 +      }
   1.528 +    }
   1.529 +}
   1.530 +
   1.531 +template <typename Graph, typename CoordMap>
   1.532 +class LengthSquareMap {
   1.533 +public:
   1.534 +  typedef typename Graph::Edge Key;
   1.535 +  typedef typename CoordMap::Value::Value Value;
   1.536 +
   1.537 +  LengthSquareMap(const Graph& graph, const CoordMap& coords)
   1.538 +    : _graph(graph), _coords(coords) {}
   1.539 +
   1.540 +  Value operator[](const Key& key) const {
   1.541 +    return (_coords[_graph.v(key)] -
   1.542 +            _coords[_graph.u(key)]).normSquare();
   1.543 +  }
   1.544 +
   1.545 +private:
   1.546 +
   1.547 +  const Graph& _graph;
   1.548 +  const CoordMap& _coords;
   1.549 +};
   1.550 +
   1.551 +void minTree() {
   1.552 +  std::vector<Parc> pedges;
   1.553 +  Timer T;
   1.554 +  std::cout << T.realTime() << "s: Creating delaunay triangulation...\n";
   1.555 +  delaunay();
   1.556 +  std::cout << T.realTime() << "s: Calculating spanning tree...\n";
   1.557 +  LengthSquareMap<ListGraph, ListGraph::NodeMap<Point> > ls(g, coords);
   1.558 +  ListGraph::EdgeMap<bool> tree(g);
   1.559 +  kruskal(g, ls, tree);
   1.560 +  std::cout << T.realTime() << "s: Removing non tree arcs...\n";
   1.561 +  std::vector<Edge> remove;
   1.562 +  for (EdgeIt e(g); e != INVALID; ++e) {
   1.563 +    if (!tree[e]) remove.push_back(e);
   1.564 +  }
   1.565 +  for(int i = 0; i < int(remove.size()); ++i) {
   1.566 +    g.erase(remove[i]);
   1.567 +  }
   1.568 +  std::cout << T.realTime() << "s: Done\n";
   1.569 +}
   1.570 +
   1.571 +void tsp2()
   1.572 +{
   1.573 +  std::cout << "Find a tree..." << std::endl;
   1.574 +
   1.575 +  minTree();
   1.576 +
   1.577 +  std::cout << "Total arc length (tree) : " << totalLen() << std::endl;
   1.578 +
   1.579 +  std::cout << "Make it Euler..." << std::endl;
   1.580 +
   1.581 +  {
   1.582 +    std::vector<Node> leafs;
   1.583 +    for(NodeIt n(g);n!=INVALID;++n)
   1.584 +      if(countIncEdges(g,n)%2==1) leafs.push_back(n);
   1.585 +
   1.586 +//    for(unsigned int i=0;i<leafs.size();i+=2)
   1.587 +//       g.addArc(leafs[i],leafs[i+1]);
   1.588 +
   1.589 +    std::vector<Parc> pedges;
   1.590 +    for(unsigned int i=0;i<leafs.size()-1;i++)
   1.591 +      for(unsigned int j=i+1;j<leafs.size();j++)
   1.592 +        {
   1.593 +          Node n=leafs[i];
   1.594 +          Node m=leafs[j];
   1.595 +          Parc p;
   1.596 +          p.a=n;
   1.597 +          p.b=m;
   1.598 +          p.len=(coords[m]-coords[n]).normSquare();
   1.599 +          pedges.push_back(p);
   1.600 +        }
   1.601 +    std::sort(pedges.begin(),pedges.end(),pedgeLess);
   1.602 +    for(unsigned int i=0;i<pedges.size();i++)
   1.603 +      if(countIncEdges(g,pedges[i].a)%2 &&
   1.604 +         countIncEdges(g,pedges[i].b)%2)
   1.605 +        g.addEdge(pedges[i].a,pedges[i].b);
   1.606 +  }
   1.607 +
   1.608 +  for(NodeIt n(g);n!=INVALID;++n)
   1.609 +    if(countIncEdges(g,n)%2 || countIncEdges(g,n)==0 )
   1.610 +      std::cout << "GEBASZ!!!" << std::endl;
   1.611 +
   1.612 +  for(EdgeIt e(g);e!=INVALID;++e)
   1.613 +    if(g.u(e)==g.v(e))
   1.614 +      std::cout << "LOOP GEBASZ!!!" << std::endl;
   1.615 +
   1.616 +  std::cout << "Number of arcs : " << countEdges(g) << std::endl;
   1.617 +
   1.618 +  std::cout << "Total arc length (euler) : " << totalLen() << std::endl;
   1.619 +
   1.620 +  ListGraph::EdgeMap<Arc> enext(g);
   1.621 +  {
   1.622 +    EulerIt<ListGraph> e(g);
   1.623 +    Arc eo=e;
   1.624 +    Arc ef=e;
   1.625 +//     std::cout << "Tour arc: " << g.id(Edge(e)) << std::endl;
   1.626 +    for(++e;e!=INVALID;++e)
   1.627 +      {
   1.628 +//         std::cout << "Tour arc: " << g.id(Edge(e)) << std::endl;
   1.629 +        enext[eo]=e;
   1.630 +        eo=e;
   1.631 +      }
   1.632 +    enext[eo]=ef;
   1.633 +  }
   1.634 +
   1.635 +  std::cout << "Creating a tour from that..." << std::endl;
   1.636 +
   1.637 +  int nnum = countNodes(g);
   1.638 +  int ednum = countEdges(g);
   1.639 +
   1.640 +  for(Arc p=enext[EdgeIt(g)];ednum>nnum;p=enext[p])
   1.641 +    {
   1.642 +//       std::cout << "Checking arc " << g.id(p) << std::endl;
   1.643 +      Arc e=enext[p];
   1.644 +      Arc f=enext[e];
   1.645 +      Node n2=g.source(f);
   1.646 +      Node n1=g.oppositeNode(n2,e);
   1.647 +      Node n3=g.oppositeNode(n2,f);
   1.648 +      if(countIncEdges(g,n2)>2)
   1.649 +        {
   1.650 +//           std::cout << "Remove an Arc" << std::endl;
   1.651 +          Arc ff=enext[f];
   1.652 +          g.erase(e);
   1.653 +          g.erase(f);
   1.654 +          if(n1!=n3)
   1.655 +            {
   1.656 +              Arc ne=g.direct(g.addEdge(n1,n3),n1);
   1.657 +              enext[p]=ne;
   1.658 +              enext[ne]=ff;
   1.659 +              ednum--;
   1.660 +            }
   1.661 +          else {
   1.662 +            enext[p]=ff;
   1.663 +            ednum-=2;
   1.664 +          }
   1.665 +        }
   1.666 +    }
   1.667 +
   1.668 +  std::cout << "Total arc length (tour) : " << totalLen() << std::endl;
   1.669 +
   1.670 +  std::cout << "2-opt the tour..." << std::endl;
   1.671 +
   1.672 +  tsp_improve();
   1.673 +
   1.674 +  std::cout << "Total arc length (2-opt tour) : " << totalLen() << std::endl;
   1.675 +}
   1.676 +
   1.677 +
   1.678 +int main(int argc,const char **argv)
   1.679 +{
   1.680 +  ArgParser ap(argc,argv);
   1.681 +
   1.682 +//   bool eps;
   1.683 +  bool disc_d, square_d, gauss_d;
   1.684 +//   bool tsp_a,two_a,tree_a;
   1.685 +  int num_of_cities=1;
   1.686 +  double area=1;
   1.687 +  N=100;
   1.688 +//   girth=10;
   1.689 +  std::string ndist("disc");
   1.690 +  ap.refOption("n", "Number of nodes (default is 100)", N)
   1.691 +    .intOption("g", "Girth parameter (default is 10)", 10)
   1.692 +    .refOption("cities", "Number of cities (default is 1)", num_of_cities)
   1.693 +    .refOption("area", "Full relative area of the cities (default is 1)", area)
   1.694 +    .refOption("disc", "Nodes are evenly distributed on a unit disc (default)",disc_d)
   1.695 +    .optionGroup("dist", "disc")
   1.696 +    .refOption("square", "Nodes are evenly distributed on a unit square", square_d)
   1.697 +    .optionGroup("dist", "square")
   1.698 +    .refOption("gauss",
   1.699 +            "Nodes are located according to a two-dim gauss distribution",
   1.700 +            gauss_d)
   1.701 +    .optionGroup("dist", "gauss")
   1.702 +//     .mandatoryGroup("dist")
   1.703 +    .onlyOneGroup("dist")
   1.704 +    .boolOption("eps", "Also generate .eps output (prefix.eps)")
   1.705 +    .boolOption("dir", "Directed digraph is generated (each arcs are replaced by two directed ones)")
   1.706 +    .boolOption("2con", "Create a two connected planar digraph")
   1.707 +    .optionGroup("alg","2con")
   1.708 +    .boolOption("tree", "Create a min. cost spanning tree")
   1.709 +    .optionGroup("alg","tree")
   1.710 +    .boolOption("tsp", "Create a TSP tour")
   1.711 +    .optionGroup("alg","tsp")
   1.712 +    .boolOption("tsp2", "Create a TSP tour (tree based)")
   1.713 +    .optionGroup("alg","tsp2")
   1.714 +    .boolOption("dela", "Delaunay triangulation digraph")
   1.715 +    .optionGroup("alg","dela")
   1.716 +    .onlyOneGroup("alg")
   1.717 +    .boolOption("rand", "Use time seed for random number generator")
   1.718 +    .optionGroup("rand", "rand")
   1.719 +    .intOption("seed", "Random seed", -1)
   1.720 +    .optionGroup("rand", "seed")
   1.721 +    .onlyOneGroup("rand")
   1.722 +    .other("[prefix]","Prefix of the output files. Default is 'lgf-gen-out'")
   1.723 +    .run();
   1.724 +
   1.725 +  if (ap["rand"]) {
   1.726 +    int seed = time(0);
   1.727 +    std::cout << "Random number seed: " << seed << std::endl;
   1.728 +    rnd = Random(seed);
   1.729 +  }
   1.730 +  if (ap.given("seed")) {
   1.731 +    int seed = ap["seed"];
   1.732 +    std::cout << "Random number seed: " << seed << std::endl;
   1.733 +    rnd = Random(seed);
   1.734 +  }
   1.735 +
   1.736 +  std::string prefix;
   1.737 +  switch(ap.files().size())
   1.738 +    {
   1.739 +    case 0:
   1.740 +      prefix="lgf-gen-out";
   1.741 +      break;
   1.742 +    case 1:
   1.743 +      prefix=ap.files()[0];
   1.744 +      break;
   1.745 +    default:
   1.746 +      std::cerr << "\nAt most one prefix can be given\n\n";
   1.747 +      exit(1);
   1.748 +    }
   1.749 +
   1.750 +  double sum_sizes=0;
   1.751 +  std::vector<double> sizes;
   1.752 +  std::vector<double> cum_sizes;
   1.753 +  for(int s=0;s<num_of_cities;s++)
   1.754 +    {
   1.755 +      //         sum_sizes+=rnd.exponential();
   1.756 +      double d=rnd();
   1.757 +      sum_sizes+=d;
   1.758 +      sizes.push_back(d);
   1.759 +      cum_sizes.push_back(sum_sizes);
   1.760 +    }
   1.761 +  int i=0;
   1.762 +  for(int s=0;s<num_of_cities;s++)
   1.763 +    {
   1.764 +      Point center=(num_of_cities==1?Point(0,0):rnd.disc());
   1.765 +      if(gauss_d)
   1.766 +        for(;i<N*(cum_sizes[s]/sum_sizes);i++) {
   1.767 +          Node n=g.addNode();
   1.768 +          nodes.push_back(n);
   1.769 +          coords[n]=center+rnd.gauss2()*area*
   1.770 +            std::sqrt(sizes[s]/sum_sizes);
   1.771 +        }
   1.772 +      else if(square_d)
   1.773 +        for(;i<N*(cum_sizes[s]/sum_sizes);i++) {
   1.774 +          Node n=g.addNode();
   1.775 +          nodes.push_back(n);
   1.776 +          coords[n]=center+Point(rnd()*2-1,rnd()*2-1)*area*
   1.777 +            std::sqrt(sizes[s]/sum_sizes);
   1.778 +        }
   1.779 +      else if(disc_d || true)
   1.780 +        for(;i<N*(cum_sizes[s]/sum_sizes);i++) {
   1.781 +          Node n=g.addNode();
   1.782 +          nodes.push_back(n);
   1.783 +          coords[n]=center+rnd.disc()*area*
   1.784 +            std::sqrt(sizes[s]/sum_sizes);
   1.785 +        }
   1.786 +    }
   1.787 +
   1.788 +//   for (ListGraph::NodeIt n(g); n != INVALID; ++n) {
   1.789 +//     std::cerr << coords[n] << std::endl;
   1.790 +//   }
   1.791 +
   1.792 +  if(ap["tsp"]) {
   1.793 +    tsp();
   1.794 +    std::cout << "#2-opt improvements: " << tsp_impr_num << std::endl;
   1.795 +  }
   1.796 +  if(ap["tsp2"]) {
   1.797 +    tsp2();
   1.798 +    std::cout << "#2-opt improvements: " << tsp_impr_num << std::endl;
   1.799 +  }
   1.800 +  else if(ap["2con"]) {
   1.801 +    std::cout << "Make triangles\n";
   1.802 +    //   triangle();
   1.803 +    sparseTriangle(ap["g"]);
   1.804 +    std::cout << "Make it sparser\n";
   1.805 +    sparse2(ap["g"]);
   1.806 +  }
   1.807 +  else if(ap["tree"]) {
   1.808 +    minTree();
   1.809 +  }
   1.810 +  else if(ap["dela"]) {
   1.811 +    delaunay();
   1.812 +  }
   1.813 +
   1.814 +
   1.815 +  std::cout << "Number of nodes    : " << countNodes(g) << std::endl;
   1.816 +  std::cout << "Number of arcs    : " << countEdges(g) << std::endl;
   1.817 +  double tlen=0;
   1.818 +  for(EdgeIt e(g);e!=INVALID;++e)
   1.819 +    tlen+=sqrt((coords[g.v(e)]-coords[g.u(e)]).normSquare());
   1.820 +  std::cout << "Total arc length  : " << tlen << std::endl;
   1.821 +
   1.822 +  if(ap["eps"])
   1.823 +    graphToEps(g,prefix+".eps").scaleToA4().
   1.824 +      scale(600).nodeScale(.005).arcWidthScale(.001).preScale(false).
   1.825 +      coords(coords).run();
   1.826 +
   1.827 +  if(ap["dir"])
   1.828 +    DigraphWriter<ListGraph>(g,prefix+".lgf").
   1.829 +      nodeMap("coordinates_x",scaleMap(xMap(coords),600)).
   1.830 +      nodeMap("coordinates_y",scaleMap(yMap(coords),600)).
   1.831 +      run();
   1.832 +  else GraphWriter<ListGraph>(g,prefix+".lgf").
   1.833 +         nodeMap("coordinates_x",scaleMap(xMap(coords),600)).
   1.834 +         nodeMap("coordinates_y",scaleMap(yMap(coords),600)).
   1.835 +         run();
   1.836 +}
   1.837 +