3 * This file is a part of LEMON, a generic C++ optimization library
5 * Copyright (C) 2003-2007
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
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.
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
20 ///\brief Special plane graph generator.
22 ///Graph generator application for various types of plane graphs.
26 /// ./tools/lgf-gen [-2con|-tree|-tsp|-tsp2|-dela] [-disc|-square|-gauss]
27 /// [-rand|-seed int] [--help|-h|-help] [-area num] [-cities int] [-dir]
28 /// [-eps] [-g int] [-n int] [prefix]
31 /// Prefix of the output files. Default is 'lgf-gen-out'
33 /// Print a short help message
35 /// Create a two connected planar graph
37 /// Full relative area of the cities (default is 1)
39 /// Number of cities (default is 1)
41 /// Delaunay triangulation graph
43 /// Directed graph is generated (each edges are replaced by two directed ones)
45 /// Nodes are evenly distributed on a unit disc (default)
47 /// Also generate .eps output (prefix.eps)
49 /// Girth parameter (default is 10)
51 /// Nodes are located according to a two-dim gauss distribution
53 /// Number of nodes (default is 100)
55 /// Use time seed for random number generator
59 /// Nodes are evenly distributed on a unit square
61 /// Create a min. cost spanning tree
65 /// Create a TSP tour (tree based)
67 /// \image html plane_tree.png
68 /// \image latex plane_tree.eps "Eucledian spanning tree" width=\textwidth
72 #include <lemon/list_graph.h>
73 #include <lemon/graph_utils.h>
74 #include <lemon/random.h>
75 #include <lemon/dim2.h>
76 #include <lemon/bfs.h>
77 #include <lemon/counter.h>
78 #include <lemon/suurballe.h>
79 #include <lemon/graph_to_eps.h>
80 #include <lemon/graph_writer.h>
81 #include <lemon/arg_parser.h>
82 #include <lemon/euler.h>
85 #include <lemon/kruskal.h>
86 #include <lemon/time_measure.h>
88 using namespace lemon;
90 typedef dim2::Point<double> Point;
92 UGRAPH_TYPEDEFS(ListUGraph);
101 std::vector<Node> nodes;
102 ListUGraph::NodeMap<Point> coords(g);
107 for(UEdgeIt e(g);e!=INVALID;++e)
108 tlen+=sqrt((coords[g.source(e)]-coords[g.target(e)]).normSquare());
114 const double EPSILON=1e-8;
115 bool tsp_improve(Node u, Node v)
117 double luv=std::sqrt((coords[v]-coords[u]).normSquare());
122 for(IncEdgeIt e(g,v2);(n=g.runningNode(e))==u2;++e);
125 if(luv+std::sqrt((coords[v2]-coords[u2]).normSquare())-EPSILON>
126 std::sqrt((coords[u]-coords[u2]).normSquare())+
127 std::sqrt((coords[v]-coords[v2]).normSquare()))
129 g.erase(findUEdge(g,u,v));
130 g.erase(findUEdge(g,u2,v2));
140 bool tsp_improve(Node u)
142 for(IncEdgeIt e(g,u);e!=INVALID;++e)
143 if(tsp_improve(u,g.runningNode(e))) return true;
152 for(NodeIt n(g);n!=INVALID;++n)
153 if(tsp_improve(n)) b=true;
159 for(int i=0;i<N;i++) g.addEdge(nodes[i],nodes[(i+1)%N]);
168 Line(Point _a,Point _b) :a(_a),b(_b) {}
169 Line(Node _a,Node _b) : a(coords[_a]),b(coords[_b]) {}
170 Line(const Edge &e) : a(coords[g.source(e)]),b(coords[g.target(e)]) {}
171 Line(const UEdge &e) : a(coords[g.source(e)]),b(coords[g.target(e)]) {}
174 inline std::ostream& operator<<(std::ostream &os, const Line &l)
176 os << l.a << "->" << l.b;
180 bool cross(Line a, Line b)
182 Point ao=rot90(a.b-a.a);
183 Point bo=rot90(b.b-b.a);
184 return (ao*(b.a-a.a))*(ao*(b.b-a.a))<0 &&
185 (bo*(a.a-b.a))*(bo*(a.b-b.a))<0;
195 bool pedgeLess(Pedge a,Pedge b)
200 std::vector<UEdge> edges;
202 namespace _delaunay_bits {
205 int prev, curr, next;
207 Part(int p, int c, int n) : prev(p), curr(c), next(n) {}
210 inline std::ostream& operator<<(std::ostream& os, const Part& part) {
211 os << '(' << part.prev << ',' << part.curr << ',' << part.next << ')';
215 inline double circle_point(const Point& p, const Point& q, const Point& r) {
216 double a = p.x * (q.y - r.y) + q.x * (r.y - p.y) + r.x * (p.y - q.y);
217 if (a == 0) return std::numeric_limits<double>::quiet_NaN();
219 double d = (p.x * p.x + p.y * p.y) * (q.y - r.y) +
220 (q.x * q.x + q.y * q.y) * (r.y - p.y) +
221 (r.x * r.x + r.y * r.y) * (p.y - q.y);
223 double e = (p.x * p.x + p.y * p.y) * (q.x - r.x) +
224 (q.x * q.x + q.y * q.y) * (r.x - p.x) +
225 (r.x * r.x + r.y * r.y) * (p.x - q.x);
227 double f = (p.x * p.x + p.y * p.y) * (q.x * r.y - r.x * q.y) +
228 (q.x * q.x + q.y * q.y) * (r.x * p.y - p.x * r.y) +
229 (r.x * r.x + r.y * r.y) * (p.x * q.y - q.x * p.y);
231 return d / (2 * a) + sqrt((d * d + e * e) / (4 * a * a) + f / a);
234 inline bool circle_form(const Point& p, const Point& q, const Point& r) {
235 return rot90(q - p) * (r - q) < 0.0;
238 inline double intersection(const Point& p, const Point& q, double sx) {
239 const double epsilon = 1e-8;
241 if (p.x == q.x) return (p.y + q.y) / 2.0;
243 if (sx < p.x + epsilon) return p.y;
244 if (sx < q.x + epsilon) return q.y;
246 double a = q.x - p.x;
247 double b = (q.x - sx) * p.y - (p.x - sx) * q.y;
248 double d = (q.x - sx) * (p.x - sx) * (p - q).normSquare();
249 return (b - sqrt(d)) / a;
255 YLess(const std::vector<Point>& points, double& sweep)
256 : _points(points), _sweep(sweep) {}
258 bool operator()(const Part& l, const Part& r) const {
259 const double epsilon = 1e-8;
261 // std::cerr << l << " vs " << r << std::endl;
262 double lbx = l.prev != -1 ?
263 intersection(_points[l.prev], _points[l.curr], _sweep) :
264 - std::numeric_limits<double>::infinity();
265 double rbx = r.prev != -1 ?
266 intersection(_points[r.prev], _points[r.curr], _sweep) :
267 - std::numeric_limits<double>::infinity();
268 double lex = l.next != -1 ?
269 intersection(_points[l.curr], _points[l.next], _sweep) :
270 std::numeric_limits<double>::infinity();
271 double rex = r.next != -1 ?
272 intersection(_points[r.curr], _points[r.next], _sweep) :
273 std::numeric_limits<double>::infinity();
275 if (lbx > lex) std::swap(lbx, lex);
276 if (rbx > rex) std::swap(rbx, rex);
278 if (lex < epsilon + rex && lbx + epsilon < rex) return true;
279 if (rex < epsilon + lex && rbx + epsilon < lex) return false;
283 const std::vector<Point>& _points;
289 typedef std::multimap<double, BeachIt> SpikeHeap;
291 typedef std::multimap<Part, SpikeHeap::iterator, YLess> Beach;
296 BeachIt(Beach::iterator iter) : it(iter) {}
301 inline void delaunay() {
302 Counter cnt("Number of edges added: ");
304 using namespace _delaunay_bits;
306 typedef _delaunay_bits::Part Part;
307 typedef std::vector<std::pair<double, int> > SiteHeap;
310 std::vector<Point> points;
311 std::vector<Node> nodes;
313 for (NodeIt it(g); it != INVALID; ++it) {
315 points.push_back(coords[it]);
318 SiteHeap siteheap(points.size());
323 for (int i = 0; i < int(siteheap.size()); ++i) {
324 siteheap[i] = std::make_pair(points[i].x, i);
327 std::sort(siteheap.begin(), siteheap.end());
328 sweep = siteheap.front().first;
330 YLess yless(points, sweep);
335 std::set<std::pair<int, int> > edges;
341 while (siteindex < int(siteheap.size()) &&
342 siteheap[0].first == siteheap[siteindex].first) {
343 front.push_back(std::make_pair(points[siteheap[siteindex].second].y,
344 siteheap[siteindex].second));
348 std::sort(front.begin(), front.end());
350 for (int i = 0; i < int(front.size()); ++i) {
351 int prev = (i == 0 ? -1 : front[i - 1].second);
352 int curr = front[i].second;
353 int next = (i + 1 == int(front.size()) ? -1 : front[i + 1].second);
355 beach.insert(std::make_pair(Part(prev, curr, next),
360 while (siteindex < int(points.size()) || !spikeheap.empty()) {
362 SpikeHeap::iterator spit = spikeheap.begin();
364 if (siteindex < int(points.size()) &&
365 (spit == spikeheap.end() || siteheap[siteindex].first < spit->first)) {
366 int site = siteheap[siteindex].second;
367 sweep = siteheap[siteindex].first;
369 Beach::iterator bit = beach.upper_bound(Part(site, site, site));
371 if (bit->second != spikeheap.end()) {
372 spikeheap.erase(bit->second);
375 int prev = bit->first.prev;
376 int curr = bit->first.curr;
377 int next = bit->first.next;
381 SpikeHeap::iterator pit = spikeheap.end();
383 circle_form(points[prev], points[curr], points[site])) {
384 double x = circle_point(points[prev], points[curr], points[site]);
385 pit = spikeheap.insert(std::make_pair(x, BeachIt(beach.end())));
387 beach.insert(std::make_pair(Part(prev, curr, site), pit));
389 beach.insert(std::make_pair(Part(prev, curr, site), pit));
392 beach.insert(std::make_pair(Part(curr, site, curr), spikeheap.end()));
394 SpikeHeap::iterator nit = spikeheap.end();
396 circle_form(points[site], points[curr],points[next])) {
397 double x = circle_point(points[site], points[curr], points[next]);
398 nit = spikeheap.insert(std::make_pair(x, BeachIt(beach.end())));
400 beach.insert(std::make_pair(Part(site, curr, next), nit));
402 beach.insert(std::make_pair(Part(site, curr, next), nit));
409 Beach::iterator bit = spit->second.it;
411 int prev = bit->first.prev;
412 int curr = bit->first.curr;
413 int next = bit->first.next;
416 std::pair<int, int> edge;
419 std::make_pair(prev, curr) : std::make_pair(curr, prev);
421 if (edges.find(edge) == edges.end()) {
423 g.addEdge(nodes[prev], nodes[curr]);
428 std::make_pair(curr, next) : std::make_pair(next, curr);
430 if (edges.find(edge) == edges.end()) {
432 g.addEdge(nodes[curr], nodes[next]);
437 Beach::iterator pbit = bit; --pbit;
438 int ppv = pbit->first.prev;
439 Beach::iterator nbit = bit; ++nbit;
440 int nnt = nbit->first.next;
442 if (bit->second != spikeheap.end()) spikeheap.erase(bit->second);
443 if (pbit->second != spikeheap.end()) spikeheap.erase(pbit->second);
444 if (nbit->second != spikeheap.end()) spikeheap.erase(nbit->second);
450 SpikeHeap::iterator pit = spikeheap.end();
451 if (ppv != -1 && ppv != next &&
452 circle_form(points[ppv], points[prev], points[next])) {
453 double x = circle_point(points[ppv], points[prev], points[next]);
454 if (x < sweep) x = sweep;
455 pit = spikeheap.insert(std::make_pair(x, BeachIt(beach.end())));
457 beach.insert(std::make_pair(Part(ppv, prev, next), pit));
459 beach.insert(std::make_pair(Part(ppv, prev, next), pit));
462 SpikeHeap::iterator nit = spikeheap.end();
463 if (nnt != -1 && prev != nnt &&
464 circle_form(points[prev], points[next], points[nnt])) {
465 double x = circle_point(points[prev], points[next], points[nnt]);
466 if (x < sweep) x = sweep;
467 nit = spikeheap.insert(std::make_pair(x, BeachIt(beach.end())));
469 beach.insert(std::make_pair(Part(prev, next, nnt), nit));
471 beach.insert(std::make_pair(Part(prev, next, nnt), nit));
477 for (Beach::iterator it = beach.begin(); it != beach.end(); ++it) {
478 int curr = it->first.curr;
479 int next = it->first.next;
481 if (next == -1) continue;
483 std::pair<int, int> edge;
486 std::make_pair(curr, next) : std::make_pair(next, curr);
488 if (edges.find(edge) == edges.end()) {
490 g.addEdge(nodes[curr], nodes[next]);
498 Counter cnt("Number of edges removed: ");
499 Bfs<ListUGraph> bfs(g);
500 for(std::vector<UEdge>::reverse_iterator ei=edges.rbegin();
501 ei!=edges.rend();++ei)
503 Node a=g.source(*ei);
504 Node b=g.target(*ei);
507 if(bfs.predEdge(b)==INVALID || bfs.dist(b)>d)
515 Counter cnt("Number of edges removed: ");
516 for(std::vector<UEdge>::reverse_iterator ei=edges.rbegin();
517 ei!=edges.rend();++ei)
519 Node a=g.source(*ei);
520 Node b=g.target(*ei);
522 ConstMap<Edge,int> cegy(1);
523 Suurballe<ListUGraph,ConstMap<Edge,int> > sur(g,cegy,a,b);
525 if(k<2 || sur.totalLength()>d)
528 // else std::cout << "Remove edge " << g.id(a) << "-" << g.id(b) << '\n';
532 void sparseTriangle(int d)
534 Counter cnt("Number of edges added: ");
535 std::vector<Pedge> pedges;
536 for(NodeIt n(g);n!=INVALID;++n)
537 for(NodeIt m=++(NodeIt(n));m!=INVALID;++m)
542 p.len=(coords[m]-coords[n]).normSquare();
545 std::sort(pedges.begin(),pedges.end(),pedgeLess);
546 for(std::vector<Pedge>::iterator pi=pedges.begin();pi!=pedges.end();++pi)
548 Line li(pi->a,pi->b);
550 for(;e!=INVALID && !cross(e,li);++e) ;
553 ConstMap<Edge,int> cegy(1);
554 Suurballe<ListUGraph,ConstMap<Edge,int> >
555 sur(g,cegy,pi->a,pi->b);
557 if(k<2 || sur.totalLength()>d)
559 ne=g.addEdge(pi->a,pi->b);
567 template <typename UGraph, typename CoordMap>
568 class LengthSquareMap {
570 typedef typename UGraph::UEdge Key;
571 typedef typename CoordMap::Value::Value Value;
573 LengthSquareMap(const UGraph& ugraph, const CoordMap& coords)
574 : _ugraph(ugraph), _coords(coords) {}
576 Value operator[](const Key& key) const {
577 return (_coords[_ugraph.target(key)] -
578 _coords[_ugraph.source(key)]).normSquare();
583 const UGraph& _ugraph;
584 const CoordMap& _coords;
588 std::vector<Pedge> pedges;
590 std::cout << T.realTime() << "s: Creating delaunay triangulation...\n";
592 std::cout << T.realTime() << "s: Calculating spanning tree...\n";
593 LengthSquareMap<ListUGraph, ListUGraph::NodeMap<Point> > ls(g, coords);
594 ListUGraph::UEdgeMap<bool> tree(g);
595 kruskal(g, ls, tree);
596 std::cout << T.realTime() << "s: Removing non tree edges...\n";
597 std::vector<UEdge> remove;
598 for (UEdgeIt e(g); e != INVALID; ++e) {
599 if (!tree[e]) remove.push_back(e);
601 for(int i = 0; i < int(remove.size()); ++i) {
604 std::cout << T.realTime() << "s: Done\n";
609 std::cout << "Find a tree..." << std::endl;
613 std::cout << "Total edge length (tree) : " << totalLen() << std::endl;
615 std::cout << "Make it Euler..." << std::endl;
618 std::vector<Node> leafs;
619 for(NodeIt n(g);n!=INVALID;++n)
620 if(countIncEdges(g,n)%2==1) leafs.push_back(n);
622 // for(unsigned int i=0;i<leafs.size();i+=2)
623 // g.addEdge(leafs[i],leafs[i+1]);
625 std::vector<Pedge> pedges;
626 for(unsigned int i=0;i<leafs.size()-1;i++)
627 for(unsigned int j=i+1;j<leafs.size();j++)
634 p.len=(coords[m]-coords[n]).normSquare();
637 std::sort(pedges.begin(),pedges.end(),pedgeLess);
638 for(unsigned int i=0;i<pedges.size();i++)
639 if(countIncEdges(g,pedges[i].a)%2 &&
640 countIncEdges(g,pedges[i].b)%2)
641 g.addEdge(pedges[i].a,pedges[i].b);
644 for(NodeIt n(g);n!=INVALID;++n)
645 if(countIncEdges(g,n)%2 || countIncEdges(g,n)==0 )
646 std::cout << "GEBASZ!!!" << std::endl;
648 for(UEdgeIt e(g);e!=INVALID;++e)
649 if(g.source(e)==g.target(e))
650 std::cout << "LOOP GEBASZ!!!" << std::endl;
652 std::cout << "Number of edges : " << countUEdges(g) << std::endl;
654 std::cout << "Total edge length (euler) : " << totalLen() << std::endl;
656 ListUGraph::UEdgeMap<Edge> enext(g);
658 UEulerIt<ListUGraph> e(g);
661 // std::cout << "Tour edge: " << g.id(UEdge(e)) << std::endl;
662 for(++e;e!=INVALID;++e)
664 // std::cout << "Tour edge: " << g.id(UEdge(e)) << std::endl;
671 std::cout << "Creating a tour from that..." << std::endl;
673 int nnum = countNodes(g);
674 int ednum = countUEdges(g);
676 for(Edge p=enext[UEdgeIt(g)];ednum>nnum;p=enext[p])
678 // std::cout << "Checking edge " << g.id(p) << std::endl;
682 Node n1=g.oppositeNode(n2,e);
683 Node n3=g.oppositeNode(n2,f);
684 if(countIncEdges(g,n2)>2)
686 // std::cout << "Remove an Edge" << std::endl;
692 Edge ne=g.direct(g.addEdge(n1,n3),n1);
704 std::cout << "Total edge length (tour) : " << totalLen() << std::endl;
706 std::cout << "2-opt the tour..." << std::endl;
710 std::cout << "Total edge length (2-opt tour) : " << totalLen() << std::endl;
714 int main(int argc,const char **argv)
716 ArgParser ap(argc,argv);
719 bool disc_d, square_d, gauss_d;
720 // bool tsp_a,two_a,tree_a;
725 std::string ndist("disc");
726 ap.refOption("n", "Number of nodes (default is 100)", N)
727 .intOption("g", "Girth parameter (default is 10)", 10)
728 .refOption("cities", "Number of cities (default is 1)", num_of_cities)
729 .refOption("area", "Full relative area of the cities (default is 1)", area)
730 .refOption("disc", "Nodes are evenly distributed on a unit disc (default)",disc_d)
731 .optionGroup("dist", "disc")
732 .refOption("square", "Nodes are evenly distributed on a unit square", square_d)
733 .optionGroup("dist", "square")
735 "Nodes are located according to a two-dim gauss distribution",
737 .optionGroup("dist", "gauss")
738 // .mandatoryGroup("dist")
739 .onlyOneGroup("dist")
740 .boolOption("eps", "Also generate .eps output (prefix.eps)")
741 .boolOption("dir", "Directed graph is generated (each edges are replaced by two directed ones)")
742 .boolOption("2con", "Create a two connected planar graph")
743 .optionGroup("alg","2con")
744 .boolOption("tree", "Create a min. cost spanning tree")
745 .optionGroup("alg","tree")
746 .boolOption("tsp", "Create a TSP tour")
747 .optionGroup("alg","tsp")
748 .boolOption("tsp2", "Create a TSP tour (tree based)")
749 .optionGroup("alg","tsp2")
750 .boolOption("dela", "Delaunay triangulation graph")
751 .optionGroup("alg","dela")
753 .boolOption("rand", "Use time seed for random number generator")
754 .optionGroup("rand", "rand")
755 .intOption("seed", "Random seed", -1)
756 .optionGroup("rand", "seed")
757 .onlyOneGroup("rand")
758 .other("[prefix]","Prefix of the output files. Default is 'lgf-gen-out'")
763 std::cout << "Random number seed: " << seed << std::endl;
766 if (ap.given("seed")) {
767 int seed = ap["seed"];
768 std::cout << "Random number seed: " << seed << std::endl;
773 switch(ap.files().size())
776 prefix="lgf-gen-out";
779 prefix=ap.files()[0];
782 std::cerr << "\nAt most one prefix can be given\n\n";
787 std::vector<double> sizes;
788 std::vector<double> cum_sizes;
789 for(int s=0;s<num_of_cities;s++)
791 // sum_sizes+=rnd.exponential();
795 cum_sizes.push_back(sum_sizes);
798 for(int s=0;s<num_of_cities;s++)
800 Point center=(num_of_cities==1?Point(0,0):rnd.disc());
802 for(;i<N*(cum_sizes[s]/sum_sizes);i++) {
805 coords[n]=center+rnd.gauss2()*area*
806 std::sqrt(sizes[s]/sum_sizes);
809 for(;i<N*(cum_sizes[s]/sum_sizes);i++) {
812 coords[n]=center+Point(rnd()*2-1,rnd()*2-1)*area*
813 std::sqrt(sizes[s]/sum_sizes);
815 else if(disc_d || true)
816 for(;i<N*(cum_sizes[s]/sum_sizes);i++) {
819 coords[n]=center+rnd.disc()*area*
820 std::sqrt(sizes[s]/sum_sizes);
824 // for (ListUGraph::NodeIt n(g); n != INVALID; ++n) {
825 // std::cerr << coords[n] << std::endl;
830 std::cout << "#2-opt improvements: " << tsp_impr_num << std::endl;
834 std::cout << "#2-opt improvements: " << tsp_impr_num << std::endl;
836 else if(ap["2con"]) {
837 std::cout << "Make triangles\n";
839 sparseTriangle(ap["g"]);
840 std::cout << "Make it sparser\n";
843 else if(ap["tree"]) {
846 else if(ap["dela"]) {
851 std::cout << "Number of nodes : " << countNodes(g) << std::endl;
852 std::cout << "Number of edges : " << countUEdges(g) << std::endl;
854 for(UEdgeIt e(g);e!=INVALID;++e)
855 tlen+=sqrt((coords[g.source(e)]-coords[g.target(e)]).normSquare());
856 std::cout << "Total edge length : " << tlen << std::endl;
859 graphToEps(g,prefix+".eps").scaleToA4().
860 scale(600).nodeScale(.2).edgeWidthScale(.001).preScale(false).
861 coords(coords).run();
864 GraphWriter<ListUGraph>(prefix+".lgf",g).
865 writeNodeMap("coordinates_x",scaleMap(xMap(coords),600)).
866 writeNodeMap("coordinates_y",scaleMap(yMap(coords),600)).
868 else UGraphWriter<ListUGraph>(prefix+".lgf",g).
869 writeNodeMap("coordinates_x",scaleMap(xMap(coords),600)).
870 writeNodeMap("coordinates_y",scaleMap(yMap(coords),600)).