tools/lgf-gen.cc
author Alpar Juttner <alpar@cs.elte.hu>
Wed, 15 Apr 2009 07:05:32 +0100
changeset 634 114920bd21ef
parent 571 06e0fb20a97c
child 631 33c6b6e755cd
permissions -rw-r--r--
Rotate and enlarge some images (#262)
alpar@570
     1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
alpar@570
     2
 *
alpar@570
     3
 * This file is a part of LEMON, a generic C++ optimization library.
alpar@570
     4
 *
alpar@570
     5
 * Copyright (C) 2003-2009
alpar@570
     6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
alpar@570
     7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
alpar@570
     8
 *
alpar@570
     9
 * Permission to use, modify and distribute this software is granted
alpar@570
    10
 * provided that this copyright notice appears in all copies. For
alpar@570
    11
 * precise terms see the accompanying LICENSE file.
alpar@570
    12
 *
alpar@570
    13
 * This software is provided "AS IS" with no warranty of any kind,
alpar@570
    14
 * express or implied, and with no claim as to its suitability for any
alpar@570
    15
 * purpose.
alpar@570
    16
 *
alpar@570
    17
 */
alpar@570
    18
alpar@570
    19
/// \ingroup tools
alpar@570
    20
/// \file
alpar@570
    21
/// \brief Special plane digraph generator.
alpar@570
    22
///
alpar@570
    23
/// Graph generator application for various types of plane graphs.
alpar@570
    24
///
alpar@570
    25
/// See
alpar@570
    26
/// \verbatim
alpar@570
    27
///  lgf-gen --help
alpar@570
    28
/// \endverbatim
alpar@570
    29
/// for more info on the usage.
alpar@570
    30
///
alpar@570
    31
alpar@570
    32
alpar@570
    33
#include <algorithm>
alpar@570
    34
#include <set>
ladanyi@617
    35
#include <ctime>
alpar@570
    36
#include <lemon/list_graph.h>
alpar@570
    37
#include <lemon/random.h>
alpar@570
    38
#include <lemon/dim2.h>
alpar@570
    39
#include <lemon/bfs.h>
alpar@570
    40
#include <lemon/counter.h>
alpar@570
    41
#include <lemon/suurballe.h>
alpar@570
    42
#include <lemon/graph_to_eps.h>
alpar@570
    43
#include <lemon/lgf_writer.h>
alpar@570
    44
#include <lemon/arg_parser.h>
alpar@570
    45
#include <lemon/euler.h>
alpar@570
    46
#include <lemon/math.h>
alpar@570
    47
#include <lemon/kruskal.h>
alpar@570
    48
#include <lemon/time_measure.h>
alpar@570
    49
alpar@570
    50
using namespace lemon;
alpar@570
    51
alpar@570
    52
typedef dim2::Point<double> Point;
alpar@570
    53
alpar@570
    54
GRAPH_TYPEDEFS(ListGraph);
alpar@570
    55
alpar@570
    56
bool progress=true;
alpar@570
    57
alpar@570
    58
int N;
alpar@570
    59
// int girth;
alpar@570
    60
alpar@570
    61
ListGraph g;
alpar@570
    62
alpar@570
    63
std::vector<Node> nodes;
alpar@570
    64
ListGraph::NodeMap<Point> coords(g);
alpar@570
    65
alpar@570
    66
alpar@570
    67
double totalLen(){
alpar@570
    68
  double tlen=0;
alpar@570
    69
  for(EdgeIt e(g);e!=INVALID;++e)
alpar@570
    70
    tlen+=sqrt((coords[g.v(e)]-coords[g.u(e)]).normSquare());
alpar@570
    71
  return tlen;
alpar@570
    72
}
alpar@570
    73
alpar@570
    74
int tsp_impr_num=0;
alpar@570
    75
alpar@570
    76
const double EPSILON=1e-8;
alpar@570
    77
bool tsp_improve(Node u, Node v)
alpar@570
    78
{
alpar@570
    79
  double luv=std::sqrt((coords[v]-coords[u]).normSquare());
alpar@570
    80
  Node u2=u;
alpar@570
    81
  Node v2=v;
alpar@570
    82
  do {
alpar@570
    83
    Node n;
alpar@570
    84
    for(IncEdgeIt e(g,v2);(n=g.runningNode(e))==u2;++e) { }
alpar@570
    85
    u2=v2;
alpar@570
    86
    v2=n;
alpar@570
    87
    if(luv+std::sqrt((coords[v2]-coords[u2]).normSquare())-EPSILON>
alpar@570
    88
       std::sqrt((coords[u]-coords[u2]).normSquare())+
alpar@570
    89
       std::sqrt((coords[v]-coords[v2]).normSquare()))
alpar@570
    90
      {
alpar@570
    91
         g.erase(findEdge(g,u,v));
alpar@570
    92
         g.erase(findEdge(g,u2,v2));
alpar@570
    93
        g.addEdge(u2,u);
alpar@570
    94
        g.addEdge(v,v2);
alpar@570
    95
        tsp_impr_num++;
alpar@570
    96
        return true;
alpar@570
    97
      }
alpar@570
    98
  } while(v2!=u);
alpar@570
    99
  return false;
alpar@570
   100
}
alpar@570
   101
alpar@570
   102
bool tsp_improve(Node u)
alpar@570
   103
{
alpar@570
   104
  for(IncEdgeIt e(g,u);e!=INVALID;++e)
alpar@570
   105
    if(tsp_improve(u,g.runningNode(e))) return true;
alpar@570
   106
  return false;
alpar@570
   107
}
alpar@570
   108
alpar@570
   109
void tsp_improve()
alpar@570
   110
{
alpar@570
   111
  bool b;
alpar@570
   112
  do {
alpar@570
   113
    b=false;
alpar@570
   114
    for(NodeIt n(g);n!=INVALID;++n)
alpar@570
   115
      if(tsp_improve(n)) b=true;
alpar@570
   116
  } while(b);
alpar@570
   117
}
alpar@570
   118
alpar@570
   119
void tsp()
alpar@570
   120
{
alpar@570
   121
  for(int i=0;i<N;i++) g.addEdge(nodes[i],nodes[(i+1)%N]);
alpar@570
   122
  tsp_improve();
alpar@570
   123
}
alpar@570
   124
alpar@570
   125
class Line
alpar@570
   126
{
alpar@570
   127
public:
alpar@570
   128
  Point a;
alpar@570
   129
  Point b;
alpar@570
   130
  Line(Point _a,Point _b) :a(_a),b(_b) {}
alpar@570
   131
  Line(Node _a,Node _b) : a(coords[_a]),b(coords[_b]) {}
alpar@570
   132
  Line(const Arc &e) : a(coords[g.source(e)]),b(coords[g.target(e)]) {}
alpar@570
   133
  Line(const Edge &e) : a(coords[g.u(e)]),b(coords[g.v(e)]) {}
alpar@570
   134
};
alpar@570
   135
alpar@570
   136
inline std::ostream& operator<<(std::ostream &os, const Line &l)
alpar@570
   137
{
alpar@570
   138
  os << l.a << "->" << l.b;
alpar@570
   139
  return os;
alpar@570
   140
}
alpar@570
   141
alpar@570
   142
bool cross(Line a, Line b)
alpar@570
   143
{
alpar@570
   144
  Point ao=rot90(a.b-a.a);
alpar@570
   145
  Point bo=rot90(b.b-b.a);
alpar@570
   146
  return (ao*(b.a-a.a))*(ao*(b.b-a.a))<0 &&
alpar@570
   147
    (bo*(a.a-b.a))*(bo*(a.b-b.a))<0;
alpar@570
   148
}
alpar@570
   149
alpar@570
   150
struct Parc
alpar@570
   151
{
alpar@570
   152
  Node a;
alpar@570
   153
  Node b;
alpar@570
   154
  double len;
alpar@570
   155
};
alpar@570
   156
alpar@570
   157
bool pedgeLess(Parc a,Parc b)
alpar@570
   158
{
alpar@570
   159
  return a.len<b.len;
alpar@570
   160
}
alpar@570
   161
alpar@570
   162
std::vector<Edge> arcs;
alpar@570
   163
alpar@570
   164
namespace _delaunay_bits {
alpar@570
   165
alpar@570
   166
  struct Part {
alpar@570
   167
    int prev, curr, next;
alpar@570
   168
alpar@570
   169
    Part(int p, int c, int n) : prev(p), curr(c), next(n) {}
alpar@570
   170
  };
alpar@570
   171
alpar@570
   172
  inline std::ostream& operator<<(std::ostream& os, const Part& part) {
alpar@570
   173
    os << '(' << part.prev << ',' << part.curr << ',' << part.next << ')';
alpar@570
   174
    return os;
alpar@570
   175
  }
alpar@570
   176
alpar@570
   177
  inline double circle_point(const Point& p, const Point& q, const Point& r) {
alpar@570
   178
    double a = p.x * (q.y - r.y) + q.x * (r.y - p.y) + r.x * (p.y - q.y);
alpar@570
   179
    if (a == 0) return std::numeric_limits<double>::quiet_NaN();
alpar@570
   180
alpar@570
   181
    double d = (p.x * p.x + p.y * p.y) * (q.y - r.y) +
alpar@570
   182
      (q.x * q.x + q.y * q.y) * (r.y - p.y) +
alpar@570
   183
      (r.x * r.x + r.y * r.y) * (p.y - q.y);
alpar@570
   184
alpar@570
   185
    double e = (p.x * p.x + p.y * p.y) * (q.x - r.x) +
alpar@570
   186
      (q.x * q.x + q.y * q.y) * (r.x - p.x) +
alpar@570
   187
      (r.x * r.x + r.y * r.y) * (p.x - q.x);
alpar@570
   188
alpar@570
   189
    double f = (p.x * p.x + p.y * p.y) * (q.x * r.y - r.x * q.y) +
alpar@570
   190
      (q.x * q.x + q.y * q.y) * (r.x * p.y - p.x * r.y) +
alpar@570
   191
      (r.x * r.x + r.y * r.y) * (p.x * q.y - q.x * p.y);
alpar@570
   192
alpar@570
   193
    return d / (2 * a) + sqrt((d * d + e * e) / (4 * a * a) + f / a);
alpar@570
   194
  }
alpar@570
   195
alpar@570
   196
  inline bool circle_form(const Point& p, const Point& q, const Point& r) {
alpar@570
   197
    return rot90(q - p) * (r - q) < 0.0;
alpar@570
   198
  }
alpar@570
   199
alpar@570
   200
  inline double intersection(const Point& p, const Point& q, double sx) {
alpar@570
   201
    const double epsilon = 1e-8;
alpar@570
   202
alpar@570
   203
    if (p.x == q.x) return (p.y + q.y) / 2.0;
alpar@570
   204
alpar@570
   205
    if (sx < p.x + epsilon) return p.y;
alpar@570
   206
    if (sx < q.x + epsilon) return q.y;
alpar@570
   207
alpar@570
   208
    double a = q.x - p.x;
alpar@570
   209
    double b = (q.x - sx) * p.y - (p.x - sx) * q.y;
alpar@570
   210
    double d = (q.x - sx) * (p.x - sx) * (p - q).normSquare();
alpar@570
   211
    return (b - sqrt(d)) / a;
alpar@570
   212
  }
alpar@570
   213
alpar@570
   214
  struct YLess {
alpar@570
   215
alpar@570
   216
alpar@570
   217
    YLess(const std::vector<Point>& points, double& sweep)
alpar@570
   218
      : _points(points), _sweep(sweep) {}
alpar@570
   219
alpar@570
   220
    bool operator()(const Part& l, const Part& r) const {
alpar@570
   221
      const double epsilon = 1e-8;
alpar@570
   222
alpar@570
   223
      //      std::cerr << l << " vs " << r << std::endl;
alpar@570
   224
      double lbx = l.prev != -1 ?
alpar@570
   225
        intersection(_points[l.prev], _points[l.curr], _sweep) :
alpar@570
   226
        - std::numeric_limits<double>::infinity();
alpar@570
   227
      double rbx = r.prev != -1 ?
alpar@570
   228
        intersection(_points[r.prev], _points[r.curr], _sweep) :
alpar@570
   229
        - std::numeric_limits<double>::infinity();
alpar@570
   230
      double lex = l.next != -1 ?
alpar@570
   231
        intersection(_points[l.curr], _points[l.next], _sweep) :
alpar@570
   232
        std::numeric_limits<double>::infinity();
alpar@570
   233
      double rex = r.next != -1 ?
alpar@570
   234
        intersection(_points[r.curr], _points[r.next], _sweep) :
alpar@570
   235
        std::numeric_limits<double>::infinity();
alpar@570
   236
alpar@570
   237
      if (lbx > lex) std::swap(lbx, lex);
alpar@570
   238
      if (rbx > rex) std::swap(rbx, rex);
alpar@570
   239
alpar@570
   240
      if (lex < epsilon + rex && lbx + epsilon < rex) return true;
alpar@570
   241
      if (rex < epsilon + lex && rbx + epsilon < lex) return false;
alpar@570
   242
      return lex < rex;
alpar@570
   243
    }
alpar@570
   244
alpar@570
   245
    const std::vector<Point>& _points;
alpar@570
   246
    double& _sweep;
alpar@570
   247
  };
alpar@570
   248
alpar@570
   249
  struct BeachIt;
alpar@570
   250
alpar@570
   251
  typedef std::multimap<double, BeachIt> SpikeHeap;
alpar@570
   252
alpar@570
   253
  typedef std::multimap<Part, SpikeHeap::iterator, YLess> Beach;
alpar@570
   254
alpar@570
   255
  struct BeachIt {
alpar@570
   256
    Beach::iterator it;
alpar@570
   257
alpar@570
   258
    BeachIt(Beach::iterator iter) : it(iter) {}
alpar@570
   259
  };
alpar@570
   260
alpar@570
   261
}
alpar@570
   262
alpar@570
   263
inline void delaunay() {
alpar@570
   264
  Counter cnt("Number of arcs added: ");
alpar@570
   265
alpar@570
   266
  using namespace _delaunay_bits;
alpar@570
   267
alpar@570
   268
  typedef _delaunay_bits::Part Part;
alpar@570
   269
  typedef std::vector<std::pair<double, int> > SiteHeap;
alpar@570
   270
alpar@570
   271
alpar@570
   272
  std::vector<Point> points;
alpar@570
   273
  std::vector<Node> nodes;
alpar@570
   274
alpar@570
   275
  for (NodeIt it(g); it != INVALID; ++it) {
alpar@570
   276
    nodes.push_back(it);
alpar@570
   277
    points.push_back(coords[it]);
alpar@570
   278
  }
alpar@570
   279
alpar@570
   280
  SiteHeap siteheap(points.size());
alpar@570
   281
alpar@570
   282
  double sweep;
alpar@570
   283
alpar@570
   284
alpar@570
   285
  for (int i = 0; i < int(siteheap.size()); ++i) {
alpar@570
   286
    siteheap[i] = std::make_pair(points[i].x, i);
alpar@570
   287
  }
alpar@570
   288
alpar@570
   289
  std::sort(siteheap.begin(), siteheap.end());
alpar@570
   290
  sweep = siteheap.front().first;
alpar@570
   291
alpar@570
   292
  YLess yless(points, sweep);
alpar@570
   293
  Beach beach(yless);
alpar@570
   294
alpar@570
   295
  SpikeHeap spikeheap;
alpar@570
   296
alpar@570
   297
  std::set<std::pair<int, int> > arcs;
alpar@570
   298
alpar@570
   299
  int siteindex = 0;
alpar@570
   300
  {
alpar@570
   301
    SiteHeap front;
alpar@570
   302
alpar@570
   303
    while (siteindex < int(siteheap.size()) &&
alpar@570
   304
           siteheap[0].first == siteheap[siteindex].first) {
alpar@570
   305
      front.push_back(std::make_pair(points[siteheap[siteindex].second].y,
alpar@570
   306
                                     siteheap[siteindex].second));
alpar@570
   307
      ++siteindex;
alpar@570
   308
    }
alpar@570
   309
alpar@570
   310
    std::sort(front.begin(), front.end());
alpar@570
   311
alpar@570
   312
    for (int i = 0; i < int(front.size()); ++i) {
alpar@570
   313
      int prev = (i == 0 ? -1 : front[i - 1].second);
alpar@570
   314
      int curr = front[i].second;
alpar@570
   315
      int next = (i + 1 == int(front.size()) ? -1 : front[i + 1].second);
alpar@570
   316
alpar@570
   317
      beach.insert(std::make_pair(Part(prev, curr, next),
alpar@570
   318
                                  spikeheap.end()));
alpar@570
   319
    }
alpar@570
   320
  }
alpar@570
   321
alpar@570
   322
  while (siteindex < int(points.size()) || !spikeheap.empty()) {
alpar@570
   323
alpar@570
   324
    SpikeHeap::iterator spit = spikeheap.begin();
alpar@570
   325
alpar@570
   326
    if (siteindex < int(points.size()) &&
alpar@570
   327
        (spit == spikeheap.end() || siteheap[siteindex].first < spit->first)) {
alpar@570
   328
      int site = siteheap[siteindex].second;
alpar@570
   329
      sweep = siteheap[siteindex].first;
alpar@570
   330
alpar@570
   331
      Beach::iterator bit = beach.upper_bound(Part(site, site, site));
alpar@570
   332
alpar@570
   333
      if (bit->second != spikeheap.end()) {
alpar@570
   334
        spikeheap.erase(bit->second);
alpar@570
   335
      }
alpar@570
   336
alpar@570
   337
      int prev = bit->first.prev;
alpar@570
   338
      int curr = bit->first.curr;
alpar@570
   339
      int next = bit->first.next;
alpar@570
   340
alpar@570
   341
      beach.erase(bit);
alpar@570
   342
alpar@570
   343
      SpikeHeap::iterator pit = spikeheap.end();
alpar@570
   344
      if (prev != -1 &&
alpar@570
   345
          circle_form(points[prev], points[curr], points[site])) {
alpar@570
   346
        double x = circle_point(points[prev], points[curr], points[site]);
alpar@570
   347
        pit = spikeheap.insert(std::make_pair(x, BeachIt(beach.end())));
alpar@570
   348
        pit->second.it =
alpar@570
   349
          beach.insert(std::make_pair(Part(prev, curr, site), pit));
alpar@570
   350
      } else {
alpar@570
   351
        beach.insert(std::make_pair(Part(prev, curr, site), pit));
alpar@570
   352
      }
alpar@570
   353
alpar@570
   354
      beach.insert(std::make_pair(Part(curr, site, curr), spikeheap.end()));
alpar@570
   355
alpar@570
   356
      SpikeHeap::iterator nit = spikeheap.end();
alpar@570
   357
      if (next != -1 &&
alpar@570
   358
          circle_form(points[site], points[curr],points[next])) {
alpar@570
   359
        double x = circle_point(points[site], points[curr], points[next]);
alpar@570
   360
        nit = spikeheap.insert(std::make_pair(x, BeachIt(beach.end())));
alpar@570
   361
        nit->second.it =
alpar@570
   362
          beach.insert(std::make_pair(Part(site, curr, next), nit));
alpar@570
   363
      } else {
alpar@570
   364
        beach.insert(std::make_pair(Part(site, curr, next), nit));
alpar@570
   365
      }
alpar@570
   366
alpar@570
   367
      ++siteindex;
alpar@570
   368
    } else {
alpar@570
   369
      sweep = spit->first;
alpar@570
   370
alpar@570
   371
      Beach::iterator bit = spit->second.it;
alpar@570
   372
alpar@570
   373
      int prev = bit->first.prev;
alpar@570
   374
      int curr = bit->first.curr;
alpar@570
   375
      int next = bit->first.next;
alpar@570
   376
alpar@570
   377
      {
alpar@570
   378
        std::pair<int, int> arc;
alpar@570
   379
alpar@570
   380
        arc = prev < curr ?
alpar@570
   381
          std::make_pair(prev, curr) : std::make_pair(curr, prev);
alpar@570
   382
alpar@570
   383
        if (arcs.find(arc) == arcs.end()) {
alpar@570
   384
          arcs.insert(arc);
alpar@570
   385
          g.addEdge(nodes[prev], nodes[curr]);
alpar@570
   386
          ++cnt;
alpar@570
   387
        }
alpar@570
   388
alpar@570
   389
        arc = curr < next ?
alpar@570
   390
          std::make_pair(curr, next) : std::make_pair(next, curr);
alpar@570
   391
alpar@570
   392
        if (arcs.find(arc) == arcs.end()) {
alpar@570
   393
          arcs.insert(arc);
alpar@570
   394
          g.addEdge(nodes[curr], nodes[next]);
alpar@570
   395
          ++cnt;
alpar@570
   396
        }
alpar@570
   397
      }
alpar@570
   398
alpar@570
   399
      Beach::iterator pbit = bit; --pbit;
alpar@570
   400
      int ppv = pbit->first.prev;
alpar@570
   401
      Beach::iterator nbit = bit; ++nbit;
alpar@570
   402
      int nnt = nbit->first.next;
alpar@570
   403
alpar@570
   404
      if (bit->second != spikeheap.end()) spikeheap.erase(bit->second);
alpar@570
   405
      if (pbit->second != spikeheap.end()) spikeheap.erase(pbit->second);
alpar@570
   406
      if (nbit->second != spikeheap.end()) spikeheap.erase(nbit->second);
alpar@570
   407
alpar@570
   408
      beach.erase(nbit);
alpar@570
   409
      beach.erase(bit);
alpar@570
   410
      beach.erase(pbit);
alpar@570
   411
alpar@570
   412
      SpikeHeap::iterator pit = spikeheap.end();
alpar@570
   413
      if (ppv != -1 && ppv != next &&
alpar@570
   414
          circle_form(points[ppv], points[prev], points[next])) {
alpar@570
   415
        double x = circle_point(points[ppv], points[prev], points[next]);
alpar@570
   416
        if (x < sweep) x = sweep;
alpar@570
   417
        pit = spikeheap.insert(std::make_pair(x, BeachIt(beach.end())));
alpar@570
   418
        pit->second.it =
alpar@570
   419
          beach.insert(std::make_pair(Part(ppv, prev, next), pit));
alpar@570
   420
      } else {
alpar@570
   421
        beach.insert(std::make_pair(Part(ppv, prev, next), pit));
alpar@570
   422
      }
alpar@570
   423
alpar@570
   424
      SpikeHeap::iterator nit = spikeheap.end();
alpar@570
   425
      if (nnt != -1 && prev != nnt &&
alpar@570
   426
          circle_form(points[prev], points[next], points[nnt])) {
alpar@570
   427
        double x = circle_point(points[prev], points[next], points[nnt]);
alpar@570
   428
        if (x < sweep) x = sweep;
alpar@570
   429
        nit = spikeheap.insert(std::make_pair(x, BeachIt(beach.end())));
alpar@570
   430
        nit->second.it =
alpar@570
   431
          beach.insert(std::make_pair(Part(prev, next, nnt), nit));
alpar@570
   432
      } else {
alpar@570
   433
        beach.insert(std::make_pair(Part(prev, next, nnt), nit));
alpar@570
   434
      }
alpar@570
   435
alpar@570
   436
    }
alpar@570
   437
  }
alpar@570
   438
alpar@570
   439
  for (Beach::iterator it = beach.begin(); it != beach.end(); ++it) {
alpar@570
   440
    int curr = it->first.curr;
alpar@570
   441
    int next = it->first.next;
alpar@570
   442
alpar@570
   443
    if (next == -1) continue;
alpar@570
   444
alpar@570
   445
    std::pair<int, int> arc;
alpar@570
   446
alpar@570
   447
    arc = curr < next ?
alpar@570
   448
      std::make_pair(curr, next) : std::make_pair(next, curr);
alpar@570
   449
alpar@570
   450
    if (arcs.find(arc) == arcs.end()) {
alpar@570
   451
      arcs.insert(arc);
alpar@570
   452
      g.addEdge(nodes[curr], nodes[next]);
alpar@570
   453
      ++cnt;
alpar@570
   454
    }
alpar@570
   455
  }
alpar@570
   456
}
alpar@570
   457
alpar@570
   458
void sparse(int d)
alpar@570
   459
{
alpar@570
   460
  Counter cnt("Number of arcs removed: ");
alpar@570
   461
  Bfs<ListGraph> bfs(g);
alpar@570
   462
  for(std::vector<Edge>::reverse_iterator ei=arcs.rbegin();
alpar@570
   463
      ei!=arcs.rend();++ei)
alpar@570
   464
    {
alpar@570
   465
      Node a=g.u(*ei);
alpar@570
   466
      Node b=g.v(*ei);
alpar@570
   467
      g.erase(*ei);
alpar@570
   468
      bfs.run(a,b);
alpar@570
   469
      if(bfs.predArc(b)==INVALID || bfs.dist(b)>d)
alpar@570
   470
        g.addEdge(a,b);
alpar@570
   471
      else cnt++;
alpar@570
   472
    }
alpar@570
   473
}
alpar@570
   474
alpar@570
   475
void sparse2(int d)
alpar@570
   476
{
alpar@570
   477
  Counter cnt("Number of arcs removed: ");
alpar@570
   478
  for(std::vector<Edge>::reverse_iterator ei=arcs.rbegin();
alpar@570
   479
      ei!=arcs.rend();++ei)
alpar@570
   480
    {
alpar@570
   481
      Node a=g.u(*ei);
alpar@570
   482
      Node b=g.v(*ei);
alpar@570
   483
      g.erase(*ei);
alpar@570
   484
      ConstMap<Arc,int> cegy(1);
alpar@570
   485
      Suurballe<ListGraph,ConstMap<Arc,int> > sur(g,cegy,a,b);
alpar@570
   486
      int k=sur.run(2);
alpar@570
   487
      if(k<2 || sur.totalLength()>d)
alpar@570
   488
        g.addEdge(a,b);
alpar@570
   489
      else cnt++;
alpar@570
   490
//       else std::cout << "Remove arc " << g.id(a) << "-" << g.id(b) << '\n';
alpar@570
   491
    }
alpar@570
   492
}
alpar@570
   493
alpar@570
   494
void sparseTriangle(int d)
alpar@570
   495
{
alpar@570
   496
  Counter cnt("Number of arcs added: ");
alpar@570
   497
  std::vector<Parc> pedges;
alpar@570
   498
  for(NodeIt n(g);n!=INVALID;++n)
alpar@570
   499
    for(NodeIt m=++(NodeIt(n));m!=INVALID;++m)
alpar@570
   500
      {
alpar@570
   501
        Parc p;
alpar@570
   502
        p.a=n;
alpar@570
   503
        p.b=m;
alpar@570
   504
        p.len=(coords[m]-coords[n]).normSquare();
alpar@570
   505
        pedges.push_back(p);
alpar@570
   506
      }
alpar@570
   507
  std::sort(pedges.begin(),pedges.end(),pedgeLess);
alpar@570
   508
  for(std::vector<Parc>::iterator pi=pedges.begin();pi!=pedges.end();++pi)
alpar@570
   509
    {
alpar@570
   510
      Line li(pi->a,pi->b);
alpar@570
   511
      EdgeIt e(g);
alpar@570
   512
      for(;e!=INVALID && !cross(e,li);++e) ;
alpar@570
   513
      Edge ne;
alpar@570
   514
      if(e==INVALID) {
alpar@570
   515
        ConstMap<Arc,int> cegy(1);
alpar@570
   516
        Suurballe<ListGraph,ConstMap<Arc,int> >
alpar@570
   517
          sur(g,cegy,pi->a,pi->b);
alpar@570
   518
        int k=sur.run(2);
alpar@570
   519
        if(k<2 || sur.totalLength()>d)
alpar@570
   520
          {
alpar@570
   521
            ne=g.addEdge(pi->a,pi->b);
alpar@570
   522
            arcs.push_back(ne);
alpar@570
   523
            cnt++;
alpar@570
   524
          }
alpar@570
   525
      }
alpar@570
   526
    }
alpar@570
   527
}
alpar@570
   528
alpar@570
   529
template <typename Graph, typename CoordMap>
alpar@570
   530
class LengthSquareMap {
alpar@570
   531
public:
alpar@570
   532
  typedef typename Graph::Edge Key;
alpar@570
   533
  typedef typename CoordMap::Value::Value Value;
alpar@570
   534
alpar@570
   535
  LengthSquareMap(const Graph& graph, const CoordMap& coords)
alpar@570
   536
    : _graph(graph), _coords(coords) {}
alpar@570
   537
alpar@570
   538
  Value operator[](const Key& key) const {
alpar@570
   539
    return (_coords[_graph.v(key)] -
alpar@570
   540
            _coords[_graph.u(key)]).normSquare();
alpar@570
   541
  }
alpar@570
   542
alpar@570
   543
private:
alpar@570
   544
alpar@570
   545
  const Graph& _graph;
alpar@570
   546
  const CoordMap& _coords;
alpar@570
   547
};
alpar@570
   548
alpar@570
   549
void minTree() {
alpar@570
   550
  std::vector<Parc> pedges;
alpar@570
   551
  Timer T;
alpar@570
   552
  std::cout << T.realTime() << "s: Creating delaunay triangulation...\n";
alpar@570
   553
  delaunay();
alpar@570
   554
  std::cout << T.realTime() << "s: Calculating spanning tree...\n";
alpar@570
   555
  LengthSquareMap<ListGraph, ListGraph::NodeMap<Point> > ls(g, coords);
alpar@570
   556
  ListGraph::EdgeMap<bool> tree(g);
alpar@570
   557
  kruskal(g, ls, tree);
alpar@570
   558
  std::cout << T.realTime() << "s: Removing non tree arcs...\n";
alpar@570
   559
  std::vector<Edge> remove;
alpar@570
   560
  for (EdgeIt e(g); e != INVALID; ++e) {
alpar@570
   561
    if (!tree[e]) remove.push_back(e);
alpar@570
   562
  }
alpar@570
   563
  for(int i = 0; i < int(remove.size()); ++i) {
alpar@570
   564
    g.erase(remove[i]);
alpar@570
   565
  }
alpar@570
   566
  std::cout << T.realTime() << "s: Done\n";
alpar@570
   567
}
alpar@570
   568
alpar@570
   569
void tsp2()
alpar@570
   570
{
alpar@570
   571
  std::cout << "Find a tree..." << std::endl;
alpar@570
   572
alpar@570
   573
  minTree();
alpar@570
   574
alpar@570
   575
  std::cout << "Total arc length (tree) : " << totalLen() << std::endl;
alpar@570
   576
alpar@570
   577
  std::cout << "Make it Euler..." << std::endl;
alpar@570
   578
alpar@570
   579
  {
alpar@570
   580
    std::vector<Node> leafs;
alpar@570
   581
    for(NodeIt n(g);n!=INVALID;++n)
alpar@570
   582
      if(countIncEdges(g,n)%2==1) leafs.push_back(n);
alpar@570
   583
alpar@570
   584
//    for(unsigned int i=0;i<leafs.size();i+=2)
alpar@570
   585
//       g.addArc(leafs[i],leafs[i+1]);
alpar@570
   586
alpar@570
   587
    std::vector<Parc> pedges;
alpar@570
   588
    for(unsigned int i=0;i<leafs.size()-1;i++)
alpar@570
   589
      for(unsigned int j=i+1;j<leafs.size();j++)
alpar@570
   590
        {
alpar@570
   591
          Node n=leafs[i];
alpar@570
   592
          Node m=leafs[j];
alpar@570
   593
          Parc p;
alpar@570
   594
          p.a=n;
alpar@570
   595
          p.b=m;
alpar@570
   596
          p.len=(coords[m]-coords[n]).normSquare();
alpar@570
   597
          pedges.push_back(p);
alpar@570
   598
        }
alpar@570
   599
    std::sort(pedges.begin(),pedges.end(),pedgeLess);
alpar@570
   600
    for(unsigned int i=0;i<pedges.size();i++)
alpar@570
   601
      if(countIncEdges(g,pedges[i].a)%2 &&
alpar@570
   602
         countIncEdges(g,pedges[i].b)%2)
alpar@570
   603
        g.addEdge(pedges[i].a,pedges[i].b);
alpar@570
   604
  }
alpar@570
   605
alpar@570
   606
  for(NodeIt n(g);n!=INVALID;++n)
alpar@570
   607
    if(countIncEdges(g,n)%2 || countIncEdges(g,n)==0 )
alpar@570
   608
      std::cout << "GEBASZ!!!" << std::endl;
alpar@570
   609
alpar@570
   610
  for(EdgeIt e(g);e!=INVALID;++e)
alpar@570
   611
    if(g.u(e)==g.v(e))
alpar@570
   612
      std::cout << "LOOP GEBASZ!!!" << std::endl;
alpar@570
   613
alpar@570
   614
  std::cout << "Number of arcs : " << countEdges(g) << std::endl;
alpar@570
   615
alpar@570
   616
  std::cout << "Total arc length (euler) : " << totalLen() << std::endl;
alpar@570
   617
alpar@570
   618
  ListGraph::EdgeMap<Arc> enext(g);
alpar@570
   619
  {
alpar@570
   620
    EulerIt<ListGraph> e(g);
alpar@570
   621
    Arc eo=e;
alpar@570
   622
    Arc ef=e;
alpar@570
   623
//     std::cout << "Tour arc: " << g.id(Edge(e)) << std::endl;
alpar@570
   624
    for(++e;e!=INVALID;++e)
alpar@570
   625
      {
alpar@570
   626
//         std::cout << "Tour arc: " << g.id(Edge(e)) << std::endl;
alpar@570
   627
        enext[eo]=e;
alpar@570
   628
        eo=e;
alpar@570
   629
      }
alpar@570
   630
    enext[eo]=ef;
alpar@570
   631
  }
alpar@570
   632
alpar@570
   633
  std::cout << "Creating a tour from that..." << std::endl;
alpar@570
   634
alpar@570
   635
  int nnum = countNodes(g);
alpar@570
   636
  int ednum = countEdges(g);
alpar@570
   637
alpar@570
   638
  for(Arc p=enext[EdgeIt(g)];ednum>nnum;p=enext[p])
alpar@570
   639
    {
alpar@570
   640
//       std::cout << "Checking arc " << g.id(p) << std::endl;
alpar@570
   641
      Arc e=enext[p];
alpar@570
   642
      Arc f=enext[e];
alpar@570
   643
      Node n2=g.source(f);
alpar@570
   644
      Node n1=g.oppositeNode(n2,e);
alpar@570
   645
      Node n3=g.oppositeNode(n2,f);
alpar@570
   646
      if(countIncEdges(g,n2)>2)
alpar@570
   647
        {
alpar@570
   648
//           std::cout << "Remove an Arc" << std::endl;
alpar@570
   649
          Arc ff=enext[f];
alpar@570
   650
          g.erase(e);
alpar@570
   651
          g.erase(f);
alpar@570
   652
          if(n1!=n3)
alpar@570
   653
            {
alpar@570
   654
              Arc ne=g.direct(g.addEdge(n1,n3),n1);
alpar@570
   655
              enext[p]=ne;
alpar@570
   656
              enext[ne]=ff;
alpar@570
   657
              ednum--;
alpar@570
   658
            }
alpar@570
   659
          else {
alpar@570
   660
            enext[p]=ff;
alpar@570
   661
            ednum-=2;
alpar@570
   662
          }
alpar@570
   663
        }
alpar@570
   664
    }
alpar@570
   665
alpar@570
   666
  std::cout << "Total arc length (tour) : " << totalLen() << std::endl;
alpar@570
   667
alpar@570
   668
  std::cout << "2-opt the tour..." << std::endl;
alpar@570
   669
alpar@570
   670
  tsp_improve();
alpar@570
   671
alpar@570
   672
  std::cout << "Total arc length (2-opt tour) : " << totalLen() << std::endl;
alpar@570
   673
}
alpar@570
   674
alpar@570
   675
alpar@570
   676
int main(int argc,const char **argv)
alpar@570
   677
{
alpar@570
   678
  ArgParser ap(argc,argv);
alpar@570
   679
alpar@570
   680
//   bool eps;
alpar@570
   681
  bool disc_d, square_d, gauss_d;
alpar@570
   682
//   bool tsp_a,two_a,tree_a;
alpar@570
   683
  int num_of_cities=1;
alpar@570
   684
  double area=1;
alpar@570
   685
  N=100;
alpar@570
   686
//   girth=10;
alpar@570
   687
  std::string ndist("disc");
alpar@570
   688
  ap.refOption("n", "Number of nodes (default is 100)", N)
alpar@570
   689
    .intOption("g", "Girth parameter (default is 10)", 10)
alpar@570
   690
    .refOption("cities", "Number of cities (default is 1)", num_of_cities)
alpar@570
   691
    .refOption("area", "Full relative area of the cities (default is 1)", area)
alpar@570
   692
    .refOption("disc", "Nodes are evenly distributed on a unit disc (default)",disc_d)
alpar@570
   693
    .optionGroup("dist", "disc")
alpar@570
   694
    .refOption("square", "Nodes are evenly distributed on a unit square", square_d)
alpar@570
   695
    .optionGroup("dist", "square")
alpar@570
   696
    .refOption("gauss",
alpar@570
   697
            "Nodes are located according to a two-dim gauss distribution",
alpar@570
   698
            gauss_d)
alpar@570
   699
    .optionGroup("dist", "gauss")
alpar@570
   700
//     .mandatoryGroup("dist")
alpar@570
   701
    .onlyOneGroup("dist")
alpar@570
   702
    .boolOption("eps", "Also generate .eps output (prefix.eps)")
alpar@571
   703
    .boolOption("nonodes", "Draw the edges only in the generated .eps")
alpar@570
   704
    .boolOption("dir", "Directed digraph is generated (each arcs are replaced by two directed ones)")
alpar@570
   705
    .boolOption("2con", "Create a two connected planar digraph")
alpar@570
   706
    .optionGroup("alg","2con")
alpar@570
   707
    .boolOption("tree", "Create a min. cost spanning tree")
alpar@570
   708
    .optionGroup("alg","tree")
alpar@570
   709
    .boolOption("tsp", "Create a TSP tour")
alpar@570
   710
    .optionGroup("alg","tsp")
alpar@570
   711
    .boolOption("tsp2", "Create a TSP tour (tree based)")
alpar@570
   712
    .optionGroup("alg","tsp2")
alpar@570
   713
    .boolOption("dela", "Delaunay triangulation digraph")
alpar@570
   714
    .optionGroup("alg","dela")
alpar@570
   715
    .onlyOneGroup("alg")
alpar@570
   716
    .boolOption("rand", "Use time seed for random number generator")
alpar@570
   717
    .optionGroup("rand", "rand")
alpar@570
   718
    .intOption("seed", "Random seed", -1)
alpar@570
   719
    .optionGroup("rand", "seed")
alpar@570
   720
    .onlyOneGroup("rand")
alpar@570
   721
    .other("[prefix]","Prefix of the output files. Default is 'lgf-gen-out'")
alpar@570
   722
    .run();
alpar@570
   723
alpar@570
   724
  if (ap["rand"]) {
alpar@570
   725
    int seed = time(0);
alpar@570
   726
    std::cout << "Random number seed: " << seed << std::endl;
alpar@570
   727
    rnd = Random(seed);
alpar@570
   728
  }
alpar@570
   729
  if (ap.given("seed")) {
alpar@570
   730
    int seed = ap["seed"];
alpar@570
   731
    std::cout << "Random number seed: " << seed << std::endl;
alpar@570
   732
    rnd = Random(seed);
alpar@570
   733
  }
alpar@570
   734
alpar@570
   735
  std::string prefix;
alpar@570
   736
  switch(ap.files().size())
alpar@570
   737
    {
alpar@570
   738
    case 0:
alpar@570
   739
      prefix="lgf-gen-out";
alpar@570
   740
      break;
alpar@570
   741
    case 1:
alpar@570
   742
      prefix=ap.files()[0];
alpar@570
   743
      break;
alpar@570
   744
    default:
alpar@570
   745
      std::cerr << "\nAt most one prefix can be given\n\n";
alpar@570
   746
      exit(1);
alpar@570
   747
    }
alpar@570
   748
alpar@570
   749
  double sum_sizes=0;
alpar@570
   750
  std::vector<double> sizes;
alpar@570
   751
  std::vector<double> cum_sizes;
alpar@570
   752
  for(int s=0;s<num_of_cities;s++)
alpar@570
   753
    {
alpar@570
   754
      //         sum_sizes+=rnd.exponential();
alpar@570
   755
      double d=rnd();
alpar@570
   756
      sum_sizes+=d;
alpar@570
   757
      sizes.push_back(d);
alpar@570
   758
      cum_sizes.push_back(sum_sizes);
alpar@570
   759
    }
alpar@570
   760
  int i=0;
alpar@570
   761
  for(int s=0;s<num_of_cities;s++)
alpar@570
   762
    {
alpar@570
   763
      Point center=(num_of_cities==1?Point(0,0):rnd.disc());
alpar@570
   764
      if(gauss_d)
alpar@570
   765
        for(;i<N*(cum_sizes[s]/sum_sizes);i++) {
alpar@570
   766
          Node n=g.addNode();
alpar@570
   767
          nodes.push_back(n);
alpar@570
   768
          coords[n]=center+rnd.gauss2()*area*
alpar@570
   769
            std::sqrt(sizes[s]/sum_sizes);
alpar@570
   770
        }
alpar@570
   771
      else if(square_d)
alpar@570
   772
        for(;i<N*(cum_sizes[s]/sum_sizes);i++) {
alpar@570
   773
          Node n=g.addNode();
alpar@570
   774
          nodes.push_back(n);
alpar@570
   775
          coords[n]=center+Point(rnd()*2-1,rnd()*2-1)*area*
alpar@570
   776
            std::sqrt(sizes[s]/sum_sizes);
alpar@570
   777
        }
alpar@570
   778
      else if(disc_d || true)
alpar@570
   779
        for(;i<N*(cum_sizes[s]/sum_sizes);i++) {
alpar@570
   780
          Node n=g.addNode();
alpar@570
   781
          nodes.push_back(n);
alpar@570
   782
          coords[n]=center+rnd.disc()*area*
alpar@570
   783
            std::sqrt(sizes[s]/sum_sizes);
alpar@570
   784
        }
alpar@570
   785
    }
alpar@570
   786
alpar@570
   787
//   for (ListGraph::NodeIt n(g); n != INVALID; ++n) {
alpar@570
   788
//     std::cerr << coords[n] << std::endl;
alpar@570
   789
//   }
alpar@570
   790
alpar@570
   791
  if(ap["tsp"]) {
alpar@570
   792
    tsp();
alpar@570
   793
    std::cout << "#2-opt improvements: " << tsp_impr_num << std::endl;
alpar@570
   794
  }
alpar@570
   795
  if(ap["tsp2"]) {
alpar@570
   796
    tsp2();
alpar@570
   797
    std::cout << "#2-opt improvements: " << tsp_impr_num << std::endl;
alpar@570
   798
  }
alpar@570
   799
  else if(ap["2con"]) {
alpar@570
   800
    std::cout << "Make triangles\n";
alpar@570
   801
    //   triangle();
alpar@570
   802
    sparseTriangle(ap["g"]);
alpar@570
   803
    std::cout << "Make it sparser\n";
alpar@570
   804
    sparse2(ap["g"]);
alpar@570
   805
  }
alpar@570
   806
  else if(ap["tree"]) {
alpar@570
   807
    minTree();
alpar@570
   808
  }
alpar@570
   809
  else if(ap["dela"]) {
alpar@570
   810
    delaunay();
alpar@570
   811
  }
alpar@570
   812
alpar@570
   813
alpar@570
   814
  std::cout << "Number of nodes    : " << countNodes(g) << std::endl;
alpar@570
   815
  std::cout << "Number of arcs    : " << countEdges(g) << std::endl;
alpar@570
   816
  double tlen=0;
alpar@570
   817
  for(EdgeIt e(g);e!=INVALID;++e)
alpar@570
   818
    tlen+=sqrt((coords[g.v(e)]-coords[g.u(e)]).normSquare());
alpar@570
   819
  std::cout << "Total arc length  : " << tlen << std::endl;
alpar@570
   820
alpar@570
   821
  if(ap["eps"])
alpar@570
   822
    graphToEps(g,prefix+".eps").scaleToA4().
alpar@570
   823
      scale(600).nodeScale(.005).arcWidthScale(.001).preScale(false).
alpar@571
   824
      coords(coords).hideNodes(ap.given("nonodes")).run();
alpar@570
   825
alpar@570
   826
  if(ap["dir"])
alpar@570
   827
    DigraphWriter<ListGraph>(g,prefix+".lgf").
alpar@570
   828
      nodeMap("coordinates_x",scaleMap(xMap(coords),600)).
alpar@570
   829
      nodeMap("coordinates_y",scaleMap(yMap(coords),600)).
alpar@570
   830
      run();
alpar@570
   831
  else GraphWriter<ListGraph>(g,prefix+".lgf").
alpar@570
   832
         nodeMap("coordinates_x",scaleMap(xMap(coords),600)).
alpar@570
   833
         nodeMap("coordinates_y",scaleMap(yMap(coords),600)).
alpar@570
   834
         run();
alpar@570
   835
}
alpar@570
   836