graph_to_eps mission accomplished.
- lemon/graph_to_eps.h header created
- lemon/bezier.h: Tools to compute with bezier curves (unclean and undocumented
interface, used internally by graph_to_eps.h)
- demo/graph_to_eps_demo.cc: a simple demo for lemon/graph_to_eps.h
2 * src/lemon/graph_to_eps.h - Part of LEMON, a generic C++ optimization library
4 * Copyright (C) 2004 Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
5 * (Egervary Combinatorial Optimization Research Group, EGRES).
7 * Permission to use, modify and distribute this software is granted
8 * provided that this copyright notice appears in all copies. For
9 * precise terms see the accompanying LICENSE file.
11 * This software is provided "AS IS" with no warranty of any kind,
12 * express or implied, and with no claim as to its suitability for any
17 #ifndef LEMON_GRAPH_TO_EPS_H
18 #define LEMON_GRAPH_TO_EPS_H
27 #include<lemon/maps.h>
28 #include<lemon/bezier.h>
32 ///\brief Simple graph drawer
34 ///\author Alpar Juttner
38 ///Data structure representing RGB colors.
40 ///Data structure representing RGB colors.
46 ///Default constructor
49 Color(double r,double g,double b) :_r(r),_g(g),_b(b) {};
50 ///Returns the red component
51 double getR() {return _r;}
52 ///Returns the green component
53 double getG() {return _g;}
54 ///Returns the blue component
55 double getB() {return _b;}
56 ///Set the color components
57 void set(double r,double g,double b) { _r=r;_g=g;_b=b; };
60 ///Default traits class of \ref GraphToEps
62 ///Default traits class of \ref GraphToEps
64 ///\c G is the type of the underlying graph.
66 struct DefaultGraphToEpsTraits
69 typedef typename Graph::Node Node;
70 typedef typename Graph::NodeIt NodeIt;
71 typedef typename Graph::Edge Edge;
72 typedef typename Graph::EdgeIt EdgeIt;
73 typedef typename Graph::InEdgeIt InEdgeIt;
74 typedef typename Graph::OutEdgeIt OutEdgeIt;
81 ConstMap<typename Graph::Node,xy<double> > _coords;
82 ConstMap<typename Graph::Node,double > _nodeSizes;
84 ConstMap<typename Graph::Node,Color > _nodeColors;
85 ConstMap<typename Graph::Edge,Color > _edgeColors;
87 ConstMap<typename Graph::Edge,double > _edgeWidths;
89 double _edgeWidthScale;
92 double _xBorder, _yBorder;
94 double _nodeBorderQuotient;
97 double _arrowLength, _arrowWidth;
99 bool _showNodes, _showEdges;
101 bool _enableParallel;
105 ConstMap<typename Graph::Node,bool > _nodeTexts;
106 double _nodeTextSize;
109 bool _pleaseRemoveOsStream;
113 ///\param _g is a reference to the graph to be printed
114 ///\param _os is a reference to the output stream.
115 ///\param _os is a reference to the output stream.
116 ///\param _pros If it is \c true, then the \c ostream referenced by \c _os
117 ///will be explicitly deallocated by the destructor.
118 ///By default it is <tt>std::cout</tt>
119 DefaultGraphToEpsTraits(const G &_g,std::ostream& _os=std::cout,
122 _coords(xy<double>(1,1)), _nodeSizes(1.0),
123 _nodeColors(Color(1,1,1)), _edgeColors(Color(0,0,0)),
124 _edgeWidths(1), _edgeWidthScale(0.3),
125 _nodeScale(1.0), _xBorder(10), _yBorder(10), _scale(1.0),
126 _nodeBorderQuotient(.1),
127 _drawArrows(false), _arrowLength(1), _arrowWidth(0.3),
128 _showNodes(true), _showEdges(true),
129 _enableParallel(false), _parEdgeDist(1),
130 _showNodeText(false), _nodeTexts(false), _nodeTextSize(1),
132 _pleaseRemoveOsStream(_pros) {}
135 ///Helper class to implement the named parameters of \ref graphToEps()
137 ///Helper class to implement the named parameters of \ref graphToEps()
138 ///\todo Is 'helper class' a good name for this?
140 template<class T> class GraphToEps : public T
142 typedef typename T::Graph Graph;
143 typedef typename Graph::Node Node;
144 typedef typename Graph::NodeIt NodeIt;
145 typedef typename Graph::Edge Edge;
146 typedef typename Graph::EdgeIt EdgeIt;
147 typedef typename Graph::InEdgeIt InEdgeIt;
148 typedef typename Graph::OutEdgeIt OutEdgeIt;
155 edgeLess(const Graph &_g) : g(_g) {}
156 bool operator()(Edge a,Edge b) const
158 Node ai=min(g.source(a),g.target(a));
159 Node aa=max(g.source(a),g.target(a));
160 Node bi=min(g.source(b),g.target(b));
161 Node ba=max(g.source(b),g.target(b));
163 (ai==bi && (aa < ba ||
164 (aa==ba && ai==g.source(a) && bi==g.target(b))));
167 bool isParallel(Edge e,Edge f) const
169 return (g.source(e)==g.source(f)&&g.target(e)==g.target(f))||
170 (g.source(e)==g.target(f)&&g.target(e)==g.source(f));
172 static xy<double> rot(xy<double> v)
174 return xy<double>(v.y,-v.x);
177 static std::string psOut(const xy &p)
179 std::ostringstream os;
180 os << p.x << ' ' << p.y;
185 GraphToEps(const T &t) : T(t), dontPrint(false) {};
187 template<class X> struct CoordsTraits : public T {
189 CoordsTraits(const T &t,const X &x) : T(t), _coords(x) {}
191 ///Sets the map of the node coordinates
193 ///Sets the map of the node coordinates.
194 ///\param x must be a node map with xy<double> or xy<int> values.
195 template<class X> GraphToEps<CoordsTraits<X> > coords(const X &x) {
197 return GraphToEps<CoordsTraits<X> >(CoordsTraits<X>(*this,x));
199 template<class X> struct NodeSizesTraits : public T {
201 NodeSizesTraits(const T &t,const X &x) : T(t), _nodeSizes(x) {}
203 ///Sets the map of the node sizes
205 ///Sets the map of the node sizes
206 ///\param x must be a node map with \c double (or convertible) values.
207 template<class X> GraphToEps<NodeSizesTraits<X> > nodeSizes(const X &x)
210 return GraphToEps<NodeSizesTraits<X> >(NodeSizesTraits<X>(*this,x));
212 template<class X> struct NodeTextsTraits : public T {
214 NodeTextsTraits(const T &t,const X &x) : T(t), _nodeTexts(x) {}
216 ///Sets the text printed on the nodes
218 ///Sets the text printed on the nodes
219 ///\param x must be a node map with type that can be pushed to a standard
221 template<class X> GraphToEps<NodeTextsTraits<X> > nodeTexts(const X &x)
225 return GraphToEps<NodeTextsTraits<X> >(NodeTextsTraits<X>(*this,x));
227 template<class X> struct EdgeWidthsTraits : public T {
228 const X &_edgeWidths;
229 EdgeWidthsTraits(const T &t,const X &x) : T(t), _edgeWidths(x) {}
231 ///Sets the map of the edge widths
233 ///Sets the map of the edge widths
234 ///\param x must be a edge map with \c double (or convertible) values.
235 template<class X> GraphToEps<EdgeWidthsTraits<X> > edgeWidths(const X &x)
238 return GraphToEps<EdgeWidthsTraits<X> >(EdgeWidthsTraits<X>(*this,x));
241 template<class X> struct NodeColorsTraits : public T {
242 const X &_nodeColors;
243 NodeColorsTraits(const T &t,const X &x) : T(t), _nodeColors(x) {}
245 ///Sets the map of the node colors
247 ///Sets the map of the node colors
248 ///\param x must be a node map with \ref Color values.
249 template<class X> GraphToEps<NodeColorsTraits<X> >
250 nodeColors(const X &x)
253 return GraphToEps<NodeColorsTraits<X> >(NodeColorsTraits<X>(*this,x));
255 template<class X> struct EdgeColorsTraits : public T {
256 const X &_edgeColors;
257 EdgeColorsTraits(const T &t,const X &x) : T(t), _edgeColors(x) {}
259 ///Sets the map of the edge colors
261 ///Sets the map of the edge colors
262 ///\param x must be a edge map with \ref Color values.
263 template<class X> GraphToEps<EdgeColorsTraits<X> >
264 edgeColors(const X &x)
267 return GraphToEps<EdgeColorsTraits<X> >(EdgeColorsTraits<X>(*this,x));
269 ///Sets a global scale factor for node sizes
271 ///Sets a global scale factor for node sizes
273 GraphToEps<T> &nodeScale(double d) {_nodeScale=d;return *this;}
274 ///Sets a global scale factor for edge widths
276 ///Sets a global scale factor for edge widths
278 GraphToEps<T> &edgeWidthScale(double d) {_edgeWidthScale=d;return *this;}
279 ///Sets a global scale factor for the whole picture
281 ///Sets a global scale factor for the whole picture
283 GraphToEps<T> &scale(double d) {_scale=d;return *this;}
284 ///Sets the width of the border around the picture
286 ///Sets the width of the border around the picture
288 GraphToEps<T> &border(double b) {_xBorder=_yBorder=b;return *this;}
289 ///Sets the width of the border around the picture
291 ///Sets the width of the border around the picture
293 GraphToEps<T> &border(double x, double y) {
294 _xBorder=x;_yBorder=y;return *this;
296 ///Sets whether to draw arrows
298 ///Sets whether to draw arrows
300 GraphToEps<T> &drawArrows(bool b=true) {_drawArrows=b;return *this;}
301 ///Sets the length of the arrowheads
303 ///Sets the length of the arrowheads
305 GraphToEps<T> &arrowLength(double d) {_arrowLength*=d;return *this;}
306 ///Sets the width of the arrowheads
308 ///Sets the width of the arrowheads
310 GraphToEps<T> &arrowWidth(double d) {_arrowWidth*=d;return *this;}
312 ///Enables parallel edges
314 ///Enables parallel edges
315 ///\todo Partially implemented
316 GraphToEps<T> &enableParallel(bool b=true) {_enableParallel=b;return *this;}
322 GraphToEps<T> &parEdgeDist(double d) {_parEdgeDist*=d;return *this;}
328 GraphToEps<T> &hideEdges(bool b=true) {_showEdges=!b;return *this;}
333 GraphToEps<T> &hideNodes(bool b=true) {_showNodes=!b;return *this;}
335 ///Sets the size of the node texts
337 ///Sets the size of the node texts
339 GraphToEps<T> &nodeTextSize(double d) {_nodeTextSize=d;return *this;}
340 ///Sets whether the the graph is undirected
342 ///Sets whether the the graph is undirected
344 GraphToEps<T> &undir(bool b=true) {_undir=b;return *this;}
345 ///Sets whether the the graph is directed
347 ///Sets whether the the graph is directed.
348 ///Use it to show the undirected edges as a pair of directed ones.
349 GraphToEps<T> &bidir(bool b=true) {_undir=!b;return *this;}
353 if(dontPrint) return;
355 os << "%!PS-Adobe-2.0 EPSF-2.0\n";
356 //\todo: Chech whether the graph is empty.
357 BoundingBox<double> bb;
358 for(NodeIt n(g);n!=INVALID;++n) {
359 double ns=_nodeSizes[n]*_nodeScale;
364 os << "%%BoundingBox: "
365 << bb.left()* _scale-_xBorder << ' '
366 << bb.bottom()*_scale-_yBorder << ' '
367 << bb.right()* _scale+_xBorder << ' '
368 << bb.top()* _scale+_yBorder << '\n';
369 //x1 y1 x2 y2 x3 y3 cr cg cb w
370 os << "/lb { setlinewidth setrgbcolor newpath moveto\n"
371 << " 4 2 roll 1 index 1 index curveto stroke } bind def\n";
372 os << "/l { setlinewidth setrgbcolor newpath moveto lineto stroke } bind def\n";
373 os << "/c { newpath dup 3 index add 2 index moveto 0 360 arc closepath } bind def\n";
375 os << "/n { setrgbcolor 2 index 2 index 2 index c fill\n"
376 << " 0 0 0 setrgbcolor dup "
377 << _nodeBorderQuotient << " mul setlinewidth "
378 << 1+_nodeBorderQuotient/2 << " div c stroke\n"
380 os << "/arrl " << _arrowLength << " def\n";
381 os << "/arrw " << _arrowWidth << " def\n";
383 os << "/lrl { 2 index mul exch 2 index mul exch rlineto pop} bind def\n";
384 //len w dx_norm dy_norm x1 y1 cr cg cb
385 os << "/arr { setrgbcolor /y1 exch def /x1 exch def /dy exch def /dx exch def\n"
386 << " /w exch def /len exch def\n"
387 // << " 0.1 setlinewidth x1 y1 moveto dx len mul dy len mul rlineto stroke"
388 << " newpath x1 dy w 2 div mul add y1 dx w 2 div mul sub moveto\n"
389 << " len w sub arrl sub dx dy lrl\n"
390 << " arrw dy dx neg lrl\n"
391 << " dx arrl w add mul dy w 2 div arrw add mul sub\n"
392 << " dy arrl w add mul dx w 2 div arrw add mul add rlineto\n"
393 << " dx arrl w add mul neg dy w 2 div arrw add mul sub\n"
394 << " dy arrl w add mul neg dx w 2 div arrw add mul add rlineto\n"
395 << " arrw dy dx neg lrl\n"
396 << " len w sub arrl sub neg dx dy lrl\n"
397 << " closepath fill } bind def\n";
398 os << "/cshow { 2 index 2 index moveto dup stringwidth pop\n"
399 << " neg 2 div fosi .35 mul neg rmoveto show pop pop} def\n";
402 if(_scale!=1.0) os << _scale << " dup scale\n";
404 os << "%Edges:\ngsave\n";
407 if(_enableParallel) {
408 std::vector<Edge> el;
409 for(EdgeIt e(g);e!=INVALID;++e)
410 if(!_undir||g.source(e)<g.target(e)) el.push_back(e);
411 sort(el.begin(),el.end(),edgeLess(g));
413 typename std::vector<Edge>::iterator j;
414 for(typename std::vector<Edge>::iterator i=el.begin();i!=el.end();i=j) {
415 for(j=i+1;j!=el.end()&&isParallel(*i,*j);++j) ;
418 for(typename std::vector<Edge>::iterator e=i;e!=j;++e)
419 sw+=_edgeWidths[*e]*_edgeWidthScale+_parEdgeDist;
422 xy<double> d(_coords[g.target(*i)]-_coords[g.source(*i)]);
423 double l=sqrt(d.normSquare());
426 for(typename std::vector<Edge>::iterator e=i;e!=j;++e) {
427 sw+=_edgeWidths[*e]*_edgeWidthScale/2.0;
428 xy<double> m(_coords[g.target(*e)]+_coords[g.source(*e)]);
429 m=m/2.0+rot(d)*sw/.75;
431 const int INERPOL_PREC=20;
432 xy<double> s=_coords[g.source(*e)];
433 xy<double> t=_coords[g.target(*e)];
434 double rn=_nodeSizes[g.target(*e)]*_nodeScale;
436 Bezier3 bez(s,m,m,t);
438 for(int i=0;i<INERPOL_PREC;++i)
439 if((bez((t1+t2)/2)-t).normSquare()>rn) t1=(t1+t2)/2;
441 xy<double> apoint=bez((t1+t2)/2);
442 rn = _nodeSizes[g.target(*e)]*_nodeScale+_arrowLength+
443 _edgeWidths[*e]*_edgeWidthScale;
446 for(int i=0;i<INERPOL_PREC;++i)
447 if((bez((t1+t2)/2)-t).normSquare()>rn) t1=(t1+t2)/2;
449 xy<double> linend=bez((t1+t2)/2);
450 bez=bez.before((t1+t2)/2);
451 rn=_nodeSizes[g.source(*e)]*_nodeScale; rn*=rn;
453 for(int i=0;i<INERPOL_PREC;++i)
454 if((bez((t1+t2)/2)-s).normSquare()>rn) t2=(t1+t2)/2;
456 bez=bez.after((t1+t2)/2);
457 os << _edgeWidths[*e]*_edgeWidthScale << " setlinewidth "
458 << _edgeColors[*e].getR() << ' '
459 << _edgeColors[*e].getG() << ' '
460 << _edgeColors[*e].getB() << " setrgbcolor newpath\n"
461 << bez.p1.x << ' ' << bez.p1.y << " moveto\n"
462 << bez.p2.x << ' ' << bez.p2.y << ' '
463 << bez.p3.x << ' ' << bez.p3.y << ' '
464 << bez.p4.x << ' ' << bez.p4.y << " curveto stroke\n";
465 xy<double> dd(rot(linend-apoint));
466 dd*=(_edgeWidths[*e]*_edgeWidthScale+_arrowWidth)/
467 sqrt(dd.normSquare());
468 os << "newpath " << psOut(apoint) << " moveto "
469 << psOut(linend+dd) << " lineto "
470 << psOut(linend-dd) << " lineto closepath fill\n";
473 os << _coords[g.source(*e)].x << ' '
474 << _coords[g.source(*e)].y << ' '
475 << m.x << ' ' << m.y << ' '
476 << _coords[g.target(*e)].x << ' '
477 << _coords[g.target(*e)].y << ' '
478 << _edgeColors[*e].getR() << ' '
479 << _edgeColors[*e].getG() << ' '
480 << _edgeColors[*e].getB() << ' '
481 << _edgeWidths[*e]*_edgeWidthScale << " lb\n";
483 sw+=_edgeWidths[*e]*_edgeWidthScale/2.0+_parEdgeDist;
487 else for(EdgeIt e(g);e!=INVALID;++e)
488 if(!_undir||g.source(e)<g.target(e))
490 xy<double> d(_coords[g.target(e)]-_coords[g.source(e)]);
491 double l=sqrt(d.normSquare());
493 xy<double> x1(d*_nodeScale*_nodeSizes[g.source(e)]+
494 _coords[g.source(e)]);
495 os << l-(_nodeSizes[g.source(e)]+
496 _nodeSizes[g.target(e)])*_nodeScale << ' '
497 << _edgeWidths[e]*_edgeWidthScale << ' '
498 << d.x << ' ' << d.y << ' '
499 << x1.x << ' ' << x1.y << ' '
500 << _edgeColors[e].getR() << ' '
501 << _edgeColors[e].getG() << ' '
502 << _edgeColors[e].getB() << " arr\n";
504 else os << _coords[g.source(e)].x << ' '
505 << _coords[g.source(e)].y << ' '
506 << _coords[g.target(e)].x << ' '
507 << _coords[g.target(e)].y << ' '
508 << _edgeColors[e].getR() << ' '
509 << _edgeColors[e].getG() << ' '
510 << _edgeColors[e].getB() << ' '
511 << _edgeWidths[e]*_edgeWidthScale << " l\n";
512 os << "grestore\n%Nodes:\ngsave\n";
514 for(NodeIt n(g);n!=INVALID;++n)
515 os << _coords[n].x << ' ' << _coords[n].y << ' '
516 << _nodeSizes[n]*_nodeScale << ' '
517 << _nodeColors[n].getR() << ' '
518 << _nodeColors[n].getG() << ' '
519 << _nodeColors[n].getB() << " n\n";
521 os << "grestore\n%Node texts:\ngsave\n";
522 os << "/fosi " << _nodeTextSize << " def\n";
523 os << "(Helvetica) findfont fosi scalefont setfont\n";
524 os << "0 0 0 setrgbcolor\n";
525 for(NodeIt n(g);n!=INVALID;++n)
526 os << _coords[n].x << ' ' << _coords[n].y
527 << " (" << _nodeTexts[n] << ") cshow\n";
529 os << "grestore\ngrestore\n";
532 if(_pleaseRemoveOsStream) {delete &os;}
537 ///Generates an EPS file from a graph
540 ///Generates an EPS file from a graph.
541 ///\param g is a reference to the graph to be printed
542 ///\param os is a reference to the output stream.
543 ///By default it is <tt>std::cout</tt>
545 ///This function also has a lot of \ref named-templ-param "named parameters",
546 ///they are declared as the members of class \ref GraphToEps. The following
547 ///example shows how to use these parameters.
549 /// graphToEps(g).scale(10).coords(coords)
550 /// .nodeScale(2).nodeSizes(sizes)
551 /// .edgeWidthScale(.4);
554 ///\sa graphToEps(G &g, char *file_name)
556 GraphToEps<DefaultGraphToEpsTraits<G> >
557 graphToEps(G &g, std::ostream& os=std::cout)
560 GraphToEps<DefaultGraphToEpsTraits<G> >(DefaultGraphToEpsTraits<G>(g,os));
563 ///Generates an EPS file from a graph
566 ///This function does the same as
567 ///\ref graphToEps(G &g,std::ostream& os)
568 ///but it writes its output into the file \c file_name
569 ///instead of a stream.
570 ///\sa graphToEps(G &g, std::ostream& os)
572 GraphToEps<DefaultGraphToEpsTraits<G> >
573 graphToEps(G &g,char *file_name)
575 return GraphToEps<DefaultGraphToEpsTraits<G> >
576 (DefaultGraphToEpsTraits<G>(g,*new std::ofstream(file_name),true));
579 //Generates an EPS file from a graph.
580 //\param g is a reference to the graph to be printed
581 //\param file_name is the output file_name.
583 //This function also has a lot of \ref named-templ-param "named parameters",
584 //they are declared as the members of class \ref GraphToEps. The following
585 //example shows how to use these parameters.
587 // graphToEps(g).scale(10).coords(coords)
588 // .nodeScale(2).nodeSizes(sizes)
589 // .edgeWidthScale(.4);
592 //\todo Avoid duplicated documentation
593 //\bug Exception handling is missing? (Or we can just ignore it?)
595 } //END OF NAMESPACE LEMON
597 #endif // LEMON_GRAPH_TO_EPS_H