COIN-OR::LEMON - Graph Library

source: lemon-1.2/lemon/graph_to_eps.h @ 584:33c6b6e755cd

Last change on this file since 584:33c6b6e755cd was 584:33c6b6e755cd, checked in by Peter Kovacs <kpeter@…>, 11 years ago

Small doc improvements (#263)

File size: 37.7 KB
Line 
1/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 *
3 * This file is a part of LEMON, a generic C++ optimization library.
4 *
5 * Copyright (C) 2003-2009
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 *
9 * Permission to use, modify and distribute this software is granted
10 * provided that this copyright notice appears in all copies. For
11 * precise terms see the accompanying LICENSE file.
12 *
13 * This software is provided "AS IS" with no warranty of any kind,
14 * express or implied, and with no claim as to its suitability for any
15 * purpose.
16 *
17 */
18
19#ifndef LEMON_GRAPH_TO_EPS_H
20#define LEMON_GRAPH_TO_EPS_H
21
22#include<iostream>
23#include<fstream>
24#include<sstream>
25#include<algorithm>
26#include<vector>
27
28#ifndef WIN32
29#include<sys/time.h>
30#include<ctime>
31#else
32#include<lemon/bits/windows.h>
33#endif
34
35#include<lemon/math.h>
36#include<lemon/core.h>
37#include<lemon/dim2.h>
38#include<lemon/maps.h>
39#include<lemon/color.h>
40#include<lemon/bits/bezier.h>
41#include<lemon/error.h>
42
43
44///\ingroup eps_io
45///\file
46///\brief A well configurable tool for visualizing graphs
47
48namespace lemon {
49
50  namespace _graph_to_eps_bits {
51    template<class MT>
52    class _NegY {
53    public:
54      typedef typename MT::Key Key;
55      typedef typename MT::Value Value;
56      const MT &map;
57      int yscale;
58      _NegY(const MT &m,bool b) : map(m), yscale(1-b*2) {}
59      Value operator[](Key n) { return Value(map[n].x,map[n].y*yscale);}
60    };
61  }
62
63///Default traits class of GraphToEps
64
65///Default traits class of \ref GraphToEps.
66///
67///\param GR is the type of the underlying graph.
68template<class GR>
69struct DefaultGraphToEpsTraits
70{
71  typedef GR Graph;
72  typedef typename Graph::Node Node;
73  typedef typename Graph::NodeIt NodeIt;
74  typedef typename Graph::Arc Arc;
75  typedef typename Graph::ArcIt ArcIt;
76  typedef typename Graph::InArcIt InArcIt;
77  typedef typename Graph::OutArcIt OutArcIt;
78
79
80  const Graph &g;
81
82  std::ostream& os;
83
84  typedef ConstMap<typename Graph::Node,dim2::Point<double> > CoordsMapType;
85  CoordsMapType _coords;
86  ConstMap<typename Graph::Node,double > _nodeSizes;
87  ConstMap<typename Graph::Node,int > _nodeShapes;
88
89  ConstMap<typename Graph::Node,Color > _nodeColors;
90  ConstMap<typename Graph::Arc,Color > _arcColors;
91
92  ConstMap<typename Graph::Arc,double > _arcWidths;
93
94  double _arcWidthScale;
95
96  double _nodeScale;
97  double _xBorder, _yBorder;
98  double _scale;
99  double _nodeBorderQuotient;
100
101  bool _drawArrows;
102  double _arrowLength, _arrowWidth;
103
104  bool _showNodes, _showArcs;
105
106  bool _enableParallel;
107  double _parArcDist;
108
109  bool _showNodeText;
110  ConstMap<typename Graph::Node,bool > _nodeTexts;
111  double _nodeTextSize;
112
113  bool _showNodePsText;
114  ConstMap<typename Graph::Node,bool > _nodePsTexts;
115  char *_nodePsTextsPreamble;
116
117  bool _undirected;
118
119  bool _pleaseRemoveOsStream;
120
121  bool _scaleToA4;
122
123  std::string _title;
124  std::string _copyright;
125
126  enum NodeTextColorType
127    { DIST_COL=0, DIST_BW=1, CUST_COL=2, SAME_COL=3 } _nodeTextColorType;
128  ConstMap<typename Graph::Node,Color > _nodeTextColors;
129
130  bool _autoNodeScale;
131  bool _autoArcWidthScale;
132
133  bool _absoluteNodeSizes;
134  bool _absoluteArcWidths;
135
136  bool _negY;
137
138  bool _preScale;
139  ///Constructor
140
141  ///Constructor
142  ///\param gr  Reference to the graph to be printed.
143  ///\param ost Reference to the output stream.
144  ///By default it is <tt>std::cout</tt>.
145  ///\param pros If it is \c true, then the \c ostream referenced by \c os
146  ///will be explicitly deallocated by the destructor.
147  DefaultGraphToEpsTraits(const GR &gr, std::ostream& ost = std::cout,
148                          bool pros = false) :
149    g(gr), os(ost),
150    _coords(dim2::Point<double>(1,1)), _nodeSizes(1), _nodeShapes(0),
151    _nodeColors(WHITE), _arcColors(BLACK),
152    _arcWidths(1.0), _arcWidthScale(0.003),
153    _nodeScale(.01), _xBorder(10), _yBorder(10), _scale(1.0),
154    _nodeBorderQuotient(.1),
155    _drawArrows(false), _arrowLength(1), _arrowWidth(0.3),
156    _showNodes(true), _showArcs(true),
157    _enableParallel(false), _parArcDist(1),
158    _showNodeText(false), _nodeTexts(false), _nodeTextSize(1),
159    _showNodePsText(false), _nodePsTexts(false), _nodePsTextsPreamble(0),
160    _undirected(lemon::UndirectedTagIndicator<GR>::value),
161    _pleaseRemoveOsStream(pros), _scaleToA4(false),
162    _nodeTextColorType(SAME_COL), _nodeTextColors(BLACK),
163    _autoNodeScale(false),
164    _autoArcWidthScale(false),
165    _absoluteNodeSizes(false),
166    _absoluteArcWidths(false),
167    _negY(false),
168    _preScale(true)
169  {}
170};
171
172///Auxiliary class to implement the named parameters of \ref graphToEps()
173
174///Auxiliary class to implement the named parameters of \ref graphToEps().
175///
176///For detailed examples see the \ref graph_to_eps_demo.cc demo file.
177template<class T> class GraphToEps : public T
178{
179  // Can't believe it is required by the C++ standard
180  using T::g;
181  using T::os;
182
183  using T::_coords;
184  using T::_nodeSizes;
185  using T::_nodeShapes;
186  using T::_nodeColors;
187  using T::_arcColors;
188  using T::_arcWidths;
189
190  using T::_arcWidthScale;
191  using T::_nodeScale;
192  using T::_xBorder;
193  using T::_yBorder;
194  using T::_scale;
195  using T::_nodeBorderQuotient;
196
197  using T::_drawArrows;
198  using T::_arrowLength;
199  using T::_arrowWidth;
200
201  using T::_showNodes;
202  using T::_showArcs;
203
204  using T::_enableParallel;
205  using T::_parArcDist;
206
207  using T::_showNodeText;
208  using T::_nodeTexts;
209  using T::_nodeTextSize;
210
211  using T::_showNodePsText;
212  using T::_nodePsTexts;
213  using T::_nodePsTextsPreamble;
214
215  using T::_undirected;
216
217  using T::_pleaseRemoveOsStream;
218
219  using T::_scaleToA4;
220
221  using T::_title;
222  using T::_copyright;
223
224  using T::NodeTextColorType;
225  using T::CUST_COL;
226  using T::DIST_COL;
227  using T::DIST_BW;
228  using T::_nodeTextColorType;
229  using T::_nodeTextColors;
230
231  using T::_autoNodeScale;
232  using T::_autoArcWidthScale;
233
234  using T::_absoluteNodeSizes;
235  using T::_absoluteArcWidths;
236
237
238  using T::_negY;
239  using T::_preScale;
240
241  // dradnats ++C eht yb deriuqer si ti eveileb t'naC
242
243  typedef typename T::Graph Graph;
244  typedef typename Graph::Node Node;
245  typedef typename Graph::NodeIt NodeIt;
246  typedef typename Graph::Arc Arc;
247  typedef typename Graph::ArcIt ArcIt;
248  typedef typename Graph::InArcIt InArcIt;
249  typedef typename Graph::OutArcIt OutArcIt;
250
251  static const int INTERPOL_PREC;
252  static const double A4HEIGHT;
253  static const double A4WIDTH;
254  static const double A4BORDER;
255
256  bool dontPrint;
257
258public:
259  ///Node shapes
260
261  ///Node shapes.
262  ///
263  enum NodeShapes {
264    /// = 0
265    ///\image html nodeshape_0.png
266    ///\image latex nodeshape_0.eps "CIRCLE shape (0)" width=2cm
267    CIRCLE=0,
268    /// = 1
269    ///\image html nodeshape_1.png
270    ///\image latex nodeshape_1.eps "SQUARE shape (1)" width=2cm
271    SQUARE=1,
272    /// = 2
273    ///\image html nodeshape_2.png
274    ///\image latex nodeshape_2.eps "DIAMOND shape (2)" width=2cm
275    DIAMOND=2,
276    /// = 3
277    ///\image html nodeshape_3.png
278    ///\image latex nodeshape_3.eps "MALE shape (3)" width=2cm
279    MALE=3,
280    /// = 4
281    ///\image html nodeshape_4.png
282    ///\image latex nodeshape_4.eps "FEMALE shape (4)" width=2cm
283    FEMALE=4
284  };
285
286private:
287  class arcLess {
288    const Graph &g;
289  public:
290    arcLess(const Graph &_g) : g(_g) {}
291    bool operator()(Arc a,Arc b) const
292    {
293      Node ai=std::min(g.source(a),g.target(a));
294      Node aa=std::max(g.source(a),g.target(a));
295      Node bi=std::min(g.source(b),g.target(b));
296      Node ba=std::max(g.source(b),g.target(b));
297      return ai<bi ||
298        (ai==bi && (aa < ba ||
299                    (aa==ba && ai==g.source(a) && bi==g.target(b))));
300    }
301  };
302  bool isParallel(Arc e,Arc f) const
303  {
304    return (g.source(e)==g.source(f)&&
305            g.target(e)==g.target(f)) ||
306      (g.source(e)==g.target(f)&&
307       g.target(e)==g.source(f));
308  }
309  template<class TT>
310  static std::string psOut(const dim2::Point<TT> &p)
311    {
312      std::ostringstream os;
313      os << p.x << ' ' << p.y;
314      return os.str();
315    }
316  static std::string psOut(const Color &c)
317    {
318      std::ostringstream os;
319      os << c.red() << ' ' << c.green() << ' ' << c.blue();
320      return os.str();
321    }
322
323public:
324  GraphToEps(const T &t) : T(t), dontPrint(false) {};
325
326  template<class X> struct CoordsTraits : public T {
327  typedef X CoordsMapType;
328    const X &_coords;
329    CoordsTraits(const T &t,const X &x) : T(t), _coords(x) {}
330  };
331  ///Sets the map of the node coordinates
332
333  ///Sets the map of the node coordinates.
334  ///\param x must be a node map with \ref dim2::Point "dim2::Point<double>" or
335  ///\ref dim2::Point "dim2::Point<int>" values.
336  template<class X> GraphToEps<CoordsTraits<X> > coords(const X &x) {
337    dontPrint=true;
338    return GraphToEps<CoordsTraits<X> >(CoordsTraits<X>(*this,x));
339  }
340  template<class X> struct NodeSizesTraits : public T {
341    const X &_nodeSizes;
342    NodeSizesTraits(const T &t,const X &x) : T(t), _nodeSizes(x) {}
343  };
344  ///Sets the map of the node sizes
345
346  ///Sets the map of the node sizes.
347  ///\param x must be a node map with \c double (or convertible) values.
348  template<class X> GraphToEps<NodeSizesTraits<X> > nodeSizes(const X &x)
349  {
350    dontPrint=true;
351    return GraphToEps<NodeSizesTraits<X> >(NodeSizesTraits<X>(*this,x));
352  }
353  template<class X> struct NodeShapesTraits : public T {
354    const X &_nodeShapes;
355    NodeShapesTraits(const T &t,const X &x) : T(t), _nodeShapes(x) {}
356  };
357  ///Sets the map of the node shapes
358
359  ///Sets the map of the node shapes.
360  ///The available shape values
361  ///can be found in \ref NodeShapes "enum NodeShapes".
362  ///\param x must be a node map with \c int (or convertible) values.
363  ///\sa NodeShapes
364  template<class X> GraphToEps<NodeShapesTraits<X> > nodeShapes(const X &x)
365  {
366    dontPrint=true;
367    return GraphToEps<NodeShapesTraits<X> >(NodeShapesTraits<X>(*this,x));
368  }
369  template<class X> struct NodeTextsTraits : public T {
370    const X &_nodeTexts;
371    NodeTextsTraits(const T &t,const X &x) : T(t), _nodeTexts(x) {}
372  };
373  ///Sets the text printed on the nodes
374
375  ///Sets the text printed on the nodes.
376  ///\param x must be a node map with type that can be pushed to a standard
377  ///\c ostream.
378  template<class X> GraphToEps<NodeTextsTraits<X> > nodeTexts(const X &x)
379  {
380    dontPrint=true;
381    _showNodeText=true;
382    return GraphToEps<NodeTextsTraits<X> >(NodeTextsTraits<X>(*this,x));
383  }
384  template<class X> struct NodePsTextsTraits : public T {
385    const X &_nodePsTexts;
386    NodePsTextsTraits(const T &t,const X &x) : T(t), _nodePsTexts(x) {}
387  };
388  ///Inserts a PostScript block to the nodes
389
390  ///With this command it is possible to insert a verbatim PostScript
391  ///block to the nodes.
392  ///The PS current point will be moved to the center of the node before
393  ///the PostScript block inserted.
394  ///
395  ///Before and after the block a newline character is inserted so you
396  ///don't have to bother with the separators.
397  ///
398  ///\param x must be a node map with type that can be pushed to a standard
399  ///\c ostream.
400  ///
401  ///\sa nodePsTextsPreamble()
402  template<class X> GraphToEps<NodePsTextsTraits<X> > nodePsTexts(const X &x)
403  {
404    dontPrint=true;
405    _showNodePsText=true;
406    return GraphToEps<NodePsTextsTraits<X> >(NodePsTextsTraits<X>(*this,x));
407  }
408  template<class X> struct ArcWidthsTraits : public T {
409    const X &_arcWidths;
410    ArcWidthsTraits(const T &t,const X &x) : T(t), _arcWidths(x) {}
411  };
412  ///Sets the map of the arc widths
413
414  ///Sets the map of the arc widths.
415  ///\param x must be an arc map with \c double (or convertible) values.
416  template<class X> GraphToEps<ArcWidthsTraits<X> > arcWidths(const X &x)
417  {
418    dontPrint=true;
419    return GraphToEps<ArcWidthsTraits<X> >(ArcWidthsTraits<X>(*this,x));
420  }
421
422  template<class X> struct NodeColorsTraits : public T {
423    const X &_nodeColors;
424    NodeColorsTraits(const T &t,const X &x) : T(t), _nodeColors(x) {}
425  };
426  ///Sets the map of the node colors
427
428  ///Sets the map of the node colors.
429  ///\param x must be a node map with \ref Color values.
430  ///
431  ///\sa Palette
432  template<class X> GraphToEps<NodeColorsTraits<X> >
433  nodeColors(const X &x)
434  {
435    dontPrint=true;
436    return GraphToEps<NodeColorsTraits<X> >(NodeColorsTraits<X>(*this,x));
437  }
438  template<class X> struct NodeTextColorsTraits : public T {
439    const X &_nodeTextColors;
440    NodeTextColorsTraits(const T &t,const X &x) : T(t), _nodeTextColors(x) {}
441  };
442  ///Sets the map of the node text colors
443
444  ///Sets the map of the node text colors.
445  ///\param x must be a node map with \ref Color values.
446  ///
447  ///\sa Palette
448  template<class X> GraphToEps<NodeTextColorsTraits<X> >
449  nodeTextColors(const X &x)
450  {
451    dontPrint=true;
452    _nodeTextColorType=CUST_COL;
453    return GraphToEps<NodeTextColorsTraits<X> >
454      (NodeTextColorsTraits<X>(*this,x));
455  }
456  template<class X> struct ArcColorsTraits : public T {
457    const X &_arcColors;
458    ArcColorsTraits(const T &t,const X &x) : T(t), _arcColors(x) {}
459  };
460  ///Sets the map of the arc colors
461
462  ///Sets the map of the arc colors.
463  ///\param x must be an arc map with \ref Color values.
464  ///
465  ///\sa Palette
466  template<class X> GraphToEps<ArcColorsTraits<X> >
467  arcColors(const X &x)
468  {
469    dontPrint=true;
470    return GraphToEps<ArcColorsTraits<X> >(ArcColorsTraits<X>(*this,x));
471  }
472  ///Sets a global scale factor for node sizes
473
474  ///Sets a global scale factor for node sizes.
475  ///
476  /// If nodeSizes() is not given, this function simply sets the node
477  /// sizes to \c d.  If nodeSizes() is given, but
478  /// autoNodeScale() is not, then the node size given by
479  /// nodeSizes() will be multiplied by the value \c d.
480  /// If both nodeSizes() and autoNodeScale() are used, then the
481  /// node sizes will be scaled in such a way that the greatest size will be
482  /// equal to \c d.
483  /// \sa nodeSizes()
484  /// \sa autoNodeScale()
485  GraphToEps<T> &nodeScale(double d=.01) {_nodeScale=d;return *this;}
486  ///Turns on/off the automatic node size scaling.
487
488  ///Turns on/off the automatic node size scaling.
489  ///
490  ///\sa nodeScale()
491  ///
492  GraphToEps<T> &autoNodeScale(bool b=true) {
493    _autoNodeScale=b;return *this;
494  }
495
496  ///Turns on/off the absolutematic node size scaling.
497
498  ///Turns on/off the absolutematic node size scaling.
499  ///
500  ///\sa nodeScale()
501  ///
502  GraphToEps<T> &absoluteNodeSizes(bool b=true) {
503    _absoluteNodeSizes=b;return *this;
504  }
505
506  ///Negates the Y coordinates.
507  GraphToEps<T> &negateY(bool b=true) {
508    _negY=b;return *this;
509  }
510
511  ///Turn on/off pre-scaling
512
513  ///By default graphToEps() rescales the whole image in order to avoid
514  ///very big or very small bounding boxes.
515  ///
516  ///This (p)rescaling can be turned off with this function.
517  ///
518  GraphToEps<T> &preScale(bool b=true) {
519    _preScale=b;return *this;
520  }
521
522  ///Sets a global scale factor for arc widths
523
524  /// Sets a global scale factor for arc widths.
525  ///
526  /// If arcWidths() is not given, this function simply sets the arc
527  /// widths to \c d.  If arcWidths() is given, but
528  /// autoArcWidthScale() is not, then the arc withs given by
529  /// arcWidths() will be multiplied by the value \c d.
530  /// If both arcWidths() and autoArcWidthScale() are used, then the
531  /// arc withs will be scaled in such a way that the greatest width will be
532  /// equal to \c d.
533  GraphToEps<T> &arcWidthScale(double d=.003) {_arcWidthScale=d;return *this;}
534  ///Turns on/off the automatic arc width scaling.
535
536  ///Turns on/off the automatic arc width scaling.
537  ///
538  ///\sa arcWidthScale()
539  ///
540  GraphToEps<T> &autoArcWidthScale(bool b=true) {
541    _autoArcWidthScale=b;return *this;
542  }
543  ///Turns on/off the absolutematic arc width scaling.
544
545  ///Turns on/off the absolutematic arc width scaling.
546  ///
547  ///\sa arcWidthScale()
548  ///
549  GraphToEps<T> &absoluteArcWidths(bool b=true) {
550    _absoluteArcWidths=b;return *this;
551  }
552  ///Sets a global scale factor for the whole picture
553  GraphToEps<T> &scale(double d) {_scale=d;return *this;}
554  ///Sets the width of the border around the picture
555  GraphToEps<T> &border(double b=10) {_xBorder=_yBorder=b;return *this;}
556  ///Sets the width of the border around the picture
557  GraphToEps<T> &border(double x, double y) {
558    _xBorder=x;_yBorder=y;return *this;
559  }
560  ///Sets whether to draw arrows
561  GraphToEps<T> &drawArrows(bool b=true) {_drawArrows=b;return *this;}
562  ///Sets the length of the arrowheads
563  GraphToEps<T> &arrowLength(double d=1.0) {_arrowLength*=d;return *this;}
564  ///Sets the width of the arrowheads
565  GraphToEps<T> &arrowWidth(double d=.3) {_arrowWidth*=d;return *this;}
566
567  ///Scales the drawing to fit to A4 page
568  GraphToEps<T> &scaleToA4() {_scaleToA4=true;return *this;}
569
570  ///Enables parallel arcs
571  GraphToEps<T> &enableParallel(bool b=true) {_enableParallel=b;return *this;}
572
573  ///Sets the distance between parallel arcs
574  GraphToEps<T> &parArcDist(double d) {_parArcDist*=d;return *this;}
575
576  ///Hides the arcs
577  GraphToEps<T> &hideArcs(bool b=true) {_showArcs=!b;return *this;}
578  ///Hides the nodes
579  GraphToEps<T> &hideNodes(bool b=true) {_showNodes=!b;return *this;}
580
581  ///Sets the size of the node texts
582  GraphToEps<T> &nodeTextSize(double d) {_nodeTextSize=d;return *this;}
583
584  ///Sets the color of the node texts to be different from the node color
585
586  ///Sets the color of the node texts to be as different from the node color
587  ///as it is possible.
588  GraphToEps<T> &distantColorNodeTexts()
589  {_nodeTextColorType=DIST_COL;return *this;}
590  ///Sets the color of the node texts to be black or white and always visible.
591
592  ///Sets the color of the node texts to be black or white according to
593  ///which is more different from the node color.
594  GraphToEps<T> &distantBWNodeTexts()
595  {_nodeTextColorType=DIST_BW;return *this;}
596
597  ///Gives a preamble block for node Postscript block.
598
599  ///Gives a preamble block for node Postscript block.
600  ///
601  ///\sa nodePsTexts()
602  GraphToEps<T> & nodePsTextsPreamble(const char *str) {
603    _nodePsTextsPreamble=str ;return *this;
604  }
605  ///Sets whether the graph is undirected
606
607  ///Sets whether the graph is undirected.
608  ///
609  ///This setting is the default for undirected graphs.
610  ///
611  ///\sa directed()
612   GraphToEps<T> &undirected(bool b=true) {_undirected=b;return *this;}
613
614  ///Sets whether the graph is directed
615
616  ///Sets whether the graph is directed.
617  ///Use it to show the edges as a pair of directed ones.
618  ///
619  ///This setting is the default for digraphs.
620  ///
621  ///\sa undirected()
622  GraphToEps<T> &directed(bool b=true) {_undirected=!b;return *this;}
623
624  ///Sets the title.
625
626  ///Sets the title of the generated image,
627  ///namely it inserts a <tt>%%Title:</tt> DSC field to the header of
628  ///the EPS file.
629  GraphToEps<T> &title(const std::string &t) {_title=t;return *this;}
630  ///Sets the copyright statement.
631
632  ///Sets the copyright statement of the generated image,
633  ///namely it inserts a <tt>%%Copyright:</tt> DSC field to the header of
634  ///the EPS file.
635  GraphToEps<T> &copyright(const std::string &t) {_copyright=t;return *this;}
636
637protected:
638  bool isInsideNode(dim2::Point<double> p, double r,int t)
639  {
640    switch(t) {
641    case CIRCLE:
642    case MALE:
643    case FEMALE:
644      return p.normSquare()<=r*r;
645    case SQUARE:
646      return p.x<=r&&p.x>=-r&&p.y<=r&&p.y>=-r;
647    case DIAMOND:
648      return p.x+p.y<=r && p.x-p.y<=r && -p.x+p.y<=r && -p.x-p.y<=r;
649    }
650    return false;
651  }
652
653public:
654  ~GraphToEps() { }
655
656  ///Draws the graph.
657
658  ///Like other functions using
659  ///\ref named-templ-func-param "named template parameters",
660  ///this function calls the algorithm itself, i.e. in this case
661  ///it draws the graph.
662  void run() {
663    const double EPSILON=1e-9;
664    if(dontPrint) return;
665
666    _graph_to_eps_bits::_NegY<typename T::CoordsMapType>
667      mycoords(_coords,_negY);
668
669    os << "%!PS-Adobe-2.0 EPSF-2.0\n";
670    if(_title.size()>0) os << "%%Title: " << _title << '\n';
671     if(_copyright.size()>0) os << "%%Copyright: " << _copyright << '\n';
672    os << "%%Creator: LEMON, graphToEps()\n";
673
674    {
675      os << "%%CreationDate: ";
676#ifndef WIN32
677      timeval tv;
678      gettimeofday(&tv, 0);
679
680      char cbuf[26];
681      ctime_r(&tv.tv_sec,cbuf);
682      os << cbuf;
683#else
684      os << bits::getWinFormattedDate();
685#endif
686    }
687    os << std::endl;
688
689    if (_autoArcWidthScale) {
690      double max_w=0;
691      for(ArcIt e(g);e!=INVALID;++e)
692        max_w=std::max(double(_arcWidths[e]),max_w);
693      if(max_w>EPSILON) {
694        _arcWidthScale/=max_w;
695      }
696    }
697
698    if (_autoNodeScale) {
699      double max_s=0;
700      for(NodeIt n(g);n!=INVALID;++n)
701        max_s=std::max(double(_nodeSizes[n]),max_s);
702      if(max_s>EPSILON) {
703        _nodeScale/=max_s;
704      }
705    }
706
707    double diag_len = 1;
708    if(!(_absoluteNodeSizes&&_absoluteArcWidths)) {
709      dim2::Box<double> bb;
710      for(NodeIt n(g);n!=INVALID;++n) bb.add(mycoords[n]);
711      if (bb.empty()) {
712        bb = dim2::Box<double>(dim2::Point<double>(0,0));
713      }
714      diag_len = std::sqrt((bb.bottomLeft()-bb.topRight()).normSquare());
715      if(diag_len<EPSILON) diag_len = 1;
716      if(!_absoluteNodeSizes) _nodeScale*=diag_len;
717      if(!_absoluteArcWidths) _arcWidthScale*=diag_len;
718    }
719
720    dim2::Box<double> bb;
721    for(NodeIt n(g);n!=INVALID;++n) {
722      double ns=_nodeSizes[n]*_nodeScale;
723      dim2::Point<double> p(ns,ns);
724      switch(_nodeShapes[n]) {
725      case CIRCLE:
726      case SQUARE:
727      case DIAMOND:
728        bb.add(p+mycoords[n]);
729        bb.add(-p+mycoords[n]);
730        break;
731      case MALE:
732        bb.add(-p+mycoords[n]);
733        bb.add(dim2::Point<double>(1.5*ns,1.5*std::sqrt(3.0)*ns)+mycoords[n]);
734        break;
735      case FEMALE:
736        bb.add(p+mycoords[n]);
737        bb.add(dim2::Point<double>(-ns,-3.01*ns)+mycoords[n]);
738        break;
739      }
740    }
741    if (bb.empty()) {
742      bb = dim2::Box<double>(dim2::Point<double>(0,0));
743    }
744
745    if(_scaleToA4)
746      os <<"%%BoundingBox: 0 0 596 842\n%%DocumentPaperSizes: a4\n";
747    else {
748      if(_preScale) {
749        //Rescale so that BoundingBox won't be neither to big nor too small.
750        while(bb.height()*_scale>1000||bb.width()*_scale>1000) _scale/=10;
751        while(bb.height()*_scale<100||bb.width()*_scale<100) _scale*=10;
752      }
753
754      os << "%%BoundingBox: "
755         << int(floor(bb.left()   * _scale - _xBorder)) << ' '
756         << int(floor(bb.bottom() * _scale - _yBorder)) << ' '
757         << int(ceil(bb.right()  * _scale + _xBorder)) << ' '
758         << int(ceil(bb.top()    * _scale + _yBorder)) << '\n';
759    }
760
761    os << "%%EndComments\n";
762
763    //x1 y1 x2 y2 x3 y3 cr cg cb w
764    os << "/lb { setlinewidth setrgbcolor newpath moveto\n"
765       << "      4 2 roll 1 index 1 index curveto stroke } bind def\n";
766    os << "/l { setlinewidth setrgbcolor newpath moveto lineto stroke }"
767       << " bind def\n";
768    //x y r
769    os << "/c { newpath dup 3 index add 2 index moveto 0 360 arc closepath }"
770       << " bind def\n";
771    //x y r
772    os << "/sq { newpath 2 index 1 index add 2 index 2 index add moveto\n"
773       << "      2 index 1 index sub 2 index 2 index add lineto\n"
774       << "      2 index 1 index sub 2 index 2 index sub lineto\n"
775       << "      2 index 1 index add 2 index 2 index sub lineto\n"
776       << "      closepath pop pop pop} bind def\n";
777    //x y r
778    os << "/di { newpath 2 index 1 index add 2 index moveto\n"
779       << "      2 index             2 index 2 index add lineto\n"
780       << "      2 index 1 index sub 2 index             lineto\n"
781       << "      2 index             2 index 2 index sub lineto\n"
782       << "      closepath pop pop pop} bind def\n";
783    // x y r cr cg cb
784    os << "/nc { 0 0 0 setrgbcolor 5 index 5 index 5 index c fill\n"
785       << "     setrgbcolor " << 1+_nodeBorderQuotient << " div c fill\n"
786       << "   } bind def\n";
787    os << "/nsq { 0 0 0 setrgbcolor 5 index 5 index 5 index sq fill\n"
788       << "     setrgbcolor " << 1+_nodeBorderQuotient << " div sq fill\n"
789       << "   } bind def\n";
790    os << "/ndi { 0 0 0 setrgbcolor 5 index 5 index 5 index di fill\n"
791       << "     setrgbcolor " << 1+_nodeBorderQuotient << " div di fill\n"
792       << "   } bind def\n";
793    os << "/nfemale { 0 0 0 setrgbcolor 3 index "
794       << _nodeBorderQuotient/(1+_nodeBorderQuotient)
795       << " 1.5 mul mul setlinewidth\n"
796       << "  newpath 5 index 5 index moveto "
797       << "5 index 5 index 5 index 3.01 mul sub\n"
798       << "  lineto 5 index 4 index .7 mul sub 5 index 5 index 2.2 mul sub"
799       << " moveto\n"
800       << "  5 index 4 index .7 mul add 5 index 5 index 2.2 mul sub lineto "
801       << "stroke\n"
802       << "  5 index 5 index 5 index c fill\n"
803       << "  setrgbcolor " << 1+_nodeBorderQuotient << " div c fill\n"
804       << "  } bind def\n";
805    os << "/nmale {\n"
806       << "  0 0 0 setrgbcolor 3 index "
807       << _nodeBorderQuotient/(1+_nodeBorderQuotient)
808       <<" 1.5 mul mul setlinewidth\n"
809       << "  newpath 5 index 5 index moveto\n"
810       << "  5 index 4 index 1 mul 1.5 mul add\n"
811       << "  5 index 5 index 3 sqrt 1.5 mul mul add\n"
812       << "  1 index 1 index lineto\n"
813       << "  1 index 1 index 7 index sub moveto\n"
814       << "  1 index 1 index lineto\n"
815       << "  exch 5 index 3 sqrt .5 mul mul sub exch 5 index .5 mul sub"
816       << " lineto\n"
817       << "  stroke\n"
818       << "  5 index 5 index 5 index c fill\n"
819       << "  setrgbcolor " << 1+_nodeBorderQuotient << " div c fill\n"
820       << "  } bind def\n";
821
822
823    os << "/arrl " << _arrowLength << " def\n";
824    os << "/arrw " << _arrowWidth << " def\n";
825    // l dx_norm dy_norm
826    os << "/lrl { 2 index mul exch 2 index mul exch rlineto pop} bind def\n";
827    //len w dx_norm dy_norm x1 y1 cr cg cb
828    os << "/arr { setrgbcolor /y1 exch def /x1 exch def /dy exch def /dx "
829       << "exch def\n"
830       << "       /w exch def /len exch def\n"
831      //<< "0.1 setlinewidth x1 y1 moveto dx len mul dy len mul rlineto stroke"
832       << "       newpath x1 dy w 2 div mul add y1 dx w 2 div mul sub moveto\n"
833       << "       len w sub arrl sub dx dy lrl\n"
834       << "       arrw dy dx neg lrl\n"
835       << "       dx arrl w add mul dy w 2 div arrw add mul sub\n"
836       << "       dy arrl w add mul dx w 2 div arrw add mul add rlineto\n"
837       << "       dx arrl w add mul neg dy w 2 div arrw add mul sub\n"
838       << "       dy arrl w add mul neg dx w 2 div arrw add mul add rlineto\n"
839       << "       arrw dy dx neg lrl\n"
840       << "       len w sub arrl sub neg dx dy lrl\n"
841       << "       closepath fill } bind def\n";
842    os << "/cshow { 2 index 2 index moveto dup stringwidth pop\n"
843       << "         neg 2 div fosi .35 mul neg rmoveto show pop pop} def\n";
844
845    os << "\ngsave\n";
846    if(_scaleToA4)
847      if(bb.height()>bb.width()) {
848        double sc= std::min((A4HEIGHT-2*A4BORDER)/bb.height(),
849                  (A4WIDTH-2*A4BORDER)/bb.width());
850        os << ((A4WIDTH -2*A4BORDER)-sc*bb.width())/2 + A4BORDER << ' '
851           << ((A4HEIGHT-2*A4BORDER)-sc*bb.height())/2 + A4BORDER
852           << " translate\n"
853           << sc << " dup scale\n"
854           << -bb.left() << ' ' << -bb.bottom() << " translate\n";
855      }
856      else {
857        double sc= std::min((A4HEIGHT-2*A4BORDER)/bb.width(),
858                  (A4WIDTH-2*A4BORDER)/bb.height());
859        os << ((A4WIDTH -2*A4BORDER)-sc*bb.height())/2 + A4BORDER << ' '
860           << ((A4HEIGHT-2*A4BORDER)-sc*bb.width())/2 + A4BORDER
861           << " translate\n"
862           << sc << " dup scale\n90 rotate\n"
863           << -bb.left() << ' ' << -bb.top() << " translate\n";
864        }
865    else if(_scale!=1.0) os << _scale << " dup scale\n";
866
867    if(_showArcs) {
868      os << "%Arcs:\ngsave\n";
869      if(_enableParallel) {
870        std::vector<Arc> el;
871        for(ArcIt e(g);e!=INVALID;++e)
872          if((!_undirected||g.source(e)<g.target(e))&&_arcWidths[e]>0
873             &&g.source(e)!=g.target(e))
874            el.push_back(e);
875        std::sort(el.begin(),el.end(),arcLess(g));
876
877        typename std::vector<Arc>::iterator j;
878        for(typename std::vector<Arc>::iterator i=el.begin();i!=el.end();i=j) {
879          for(j=i+1;j!=el.end()&&isParallel(*i,*j);++j) ;
880
881          double sw=0;
882          for(typename std::vector<Arc>::iterator e=i;e!=j;++e)
883            sw+=_arcWidths[*e]*_arcWidthScale+_parArcDist;
884          sw-=_parArcDist;
885          sw/=-2.0;
886          dim2::Point<double>
887            dvec(mycoords[g.target(*i)]-mycoords[g.source(*i)]);
888          double l=std::sqrt(dvec.normSquare());
889          dim2::Point<double> d(dvec/std::max(l,EPSILON));
890          dim2::Point<double> m;
891//           m=dim2::Point<double>(mycoords[g.target(*i)]+
892//                                 mycoords[g.source(*i)])/2.0;
893
894//            m=dim2::Point<double>(mycoords[g.source(*i)])+
895//             dvec*(double(_nodeSizes[g.source(*i)])/
896//                (_nodeSizes[g.source(*i)]+_nodeSizes[g.target(*i)]));
897
898          m=dim2::Point<double>(mycoords[g.source(*i)])+
899            d*(l+_nodeSizes[g.source(*i)]-_nodeSizes[g.target(*i)])/2.0;
900
901          for(typename std::vector<Arc>::iterator e=i;e!=j;++e) {
902            sw+=_arcWidths[*e]*_arcWidthScale/2.0;
903            dim2::Point<double> mm=m+rot90(d)*sw/.75;
904            if(_drawArrows) {
905              int node_shape;
906              dim2::Point<double> s=mycoords[g.source(*e)];
907              dim2::Point<double> t=mycoords[g.target(*e)];
908              double rn=_nodeSizes[g.target(*e)]*_nodeScale;
909              node_shape=_nodeShapes[g.target(*e)];
910              dim2::Bezier3 bez(s,mm,mm,t);
911              double t1=0,t2=1;
912              for(int ii=0;ii<INTERPOL_PREC;++ii)
913                if(isInsideNode(bez((t1+t2)/2)-t,rn,node_shape)) t2=(t1+t2)/2;
914                else t1=(t1+t2)/2;
915              dim2::Point<double> apoint=bez((t1+t2)/2);
916              rn = _arrowLength+_arcWidths[*e]*_arcWidthScale;
917              rn*=rn;
918              t2=(t1+t2)/2;t1=0;
919              for(int ii=0;ii<INTERPOL_PREC;++ii)
920                if((bez((t1+t2)/2)-apoint).normSquare()>rn) t1=(t1+t2)/2;
921                else t2=(t1+t2)/2;
922              dim2::Point<double> linend=bez((t1+t2)/2);
923              bez=bez.before((t1+t2)/2);
924//               rn=_nodeSizes[g.source(*e)]*_nodeScale;
925//               node_shape=_nodeShapes[g.source(*e)];
926//               t1=0;t2=1;
927//               for(int i=0;i<INTERPOL_PREC;++i)
928//                 if(isInsideNode(bez((t1+t2)/2)-t,rn,node_shape))
929//                   t1=(t1+t2)/2;
930//                 else t2=(t1+t2)/2;
931//               bez=bez.after((t1+t2)/2);
932              os << _arcWidths[*e]*_arcWidthScale << " setlinewidth "
933                 << _arcColors[*e].red() << ' '
934                 << _arcColors[*e].green() << ' '
935                 << _arcColors[*e].blue() << " setrgbcolor newpath\n"
936                 << bez.p1.x << ' ' <<  bez.p1.y << " moveto\n"
937                 << bez.p2.x << ' ' << bez.p2.y << ' '
938                 << bez.p3.x << ' ' << bez.p3.y << ' '
939                 << bez.p4.x << ' ' << bez.p4.y << " curveto stroke\n";
940              dim2::Point<double> dd(rot90(linend-apoint));
941              dd*=(.5*_arcWidths[*e]*_arcWidthScale+_arrowWidth)/
942                std::sqrt(dd.normSquare());
943              os << "newpath " << psOut(apoint) << " moveto "
944                 << psOut(linend+dd) << " lineto "
945                 << psOut(linend-dd) << " lineto closepath fill\n";
946            }
947            else {
948              os << mycoords[g.source(*e)].x << ' '
949                 << mycoords[g.source(*e)].y << ' '
950                 << mm.x << ' ' << mm.y << ' '
951                 << mycoords[g.target(*e)].x << ' '
952                 << mycoords[g.target(*e)].y << ' '
953                 << _arcColors[*e].red() << ' '
954                 << _arcColors[*e].green() << ' '
955                 << _arcColors[*e].blue() << ' '
956                 << _arcWidths[*e]*_arcWidthScale << " lb\n";
957            }
958            sw+=_arcWidths[*e]*_arcWidthScale/2.0+_parArcDist;
959          }
960        }
961      }
962      else for(ArcIt e(g);e!=INVALID;++e)
963        if((!_undirected||g.source(e)<g.target(e))&&_arcWidths[e]>0
964           &&g.source(e)!=g.target(e)) {
965          if(_drawArrows) {
966            dim2::Point<double> d(mycoords[g.target(e)]-mycoords[g.source(e)]);
967            double rn=_nodeSizes[g.target(e)]*_nodeScale;
968            int node_shape=_nodeShapes[g.target(e)];
969            double t1=0,t2=1;
970            for(int i=0;i<INTERPOL_PREC;++i)
971              if(isInsideNode((-(t1+t2)/2)*d,rn,node_shape)) t1=(t1+t2)/2;
972              else t2=(t1+t2)/2;
973            double l=std::sqrt(d.normSquare());
974            d/=l;
975
976            os << l*(1-(t1+t2)/2) << ' '
977               << _arcWidths[e]*_arcWidthScale << ' '
978               << d.x << ' ' << d.y << ' '
979               << mycoords[g.source(e)].x << ' '
980               << mycoords[g.source(e)].y << ' '
981               << _arcColors[e].red() << ' '
982               << _arcColors[e].green() << ' '
983               << _arcColors[e].blue() << " arr\n";
984          }
985          else os << mycoords[g.source(e)].x << ' '
986                  << mycoords[g.source(e)].y << ' '
987                  << mycoords[g.target(e)].x << ' '
988                  << mycoords[g.target(e)].y << ' '
989                  << _arcColors[e].red() << ' '
990                  << _arcColors[e].green() << ' '
991                  << _arcColors[e].blue() << ' '
992                  << _arcWidths[e]*_arcWidthScale << " l\n";
993        }
994      os << "grestore\n";
995    }
996    if(_showNodes) {
997      os << "%Nodes:\ngsave\n";
998      for(NodeIt n(g);n!=INVALID;++n) {
999        os << mycoords[n].x << ' ' << mycoords[n].y << ' '
1000           << _nodeSizes[n]*_nodeScale << ' '
1001           << _nodeColors[n].red() << ' '
1002           << _nodeColors[n].green() << ' '
1003           << _nodeColors[n].blue() << ' ';
1004        switch(_nodeShapes[n]) {
1005        case CIRCLE:
1006          os<< "nc";break;
1007        case SQUARE:
1008          os<< "nsq";break;
1009        case DIAMOND:
1010          os<< "ndi";break;
1011        case MALE:
1012          os<< "nmale";break;
1013        case FEMALE:
1014          os<< "nfemale";break;
1015        }
1016        os<<'\n';
1017      }
1018      os << "grestore\n";
1019    }
1020    if(_showNodeText) {
1021      os << "%Node texts:\ngsave\n";
1022      os << "/fosi " << _nodeTextSize << " def\n";
1023      os << "(Helvetica) findfont fosi scalefont setfont\n";
1024      for(NodeIt n(g);n!=INVALID;++n) {
1025        switch(_nodeTextColorType) {
1026        case DIST_COL:
1027          os << psOut(distantColor(_nodeColors[n])) << " setrgbcolor\n";
1028          break;
1029        case DIST_BW:
1030          os << psOut(distantBW(_nodeColors[n])) << " setrgbcolor\n";
1031          break;
1032        case CUST_COL:
1033          os << psOut(distantColor(_nodeTextColors[n])) << " setrgbcolor\n";
1034          break;
1035        default:
1036          os << "0 0 0 setrgbcolor\n";
1037        }
1038        os << mycoords[n].x << ' ' << mycoords[n].y
1039           << " (" << _nodeTexts[n] << ") cshow\n";
1040      }
1041      os << "grestore\n";
1042    }
1043    if(_showNodePsText) {
1044      os << "%Node PS blocks:\ngsave\n";
1045      for(NodeIt n(g);n!=INVALID;++n)
1046        os << mycoords[n].x << ' ' << mycoords[n].y
1047           << " moveto\n" << _nodePsTexts[n] << "\n";
1048      os << "grestore\n";
1049    }
1050
1051    os << "grestore\nshowpage\n";
1052
1053    //CleanUp:
1054    if(_pleaseRemoveOsStream) {delete &os;}
1055  }
1056
1057  ///\name Aliases
1058  ///These are just some aliases to other parameter setting functions.
1059
1060  ///@{
1061
1062  ///An alias for arcWidths()
1063  template<class X> GraphToEps<ArcWidthsTraits<X> > edgeWidths(const X &x)
1064  {
1065    return arcWidths(x);
1066  }
1067
1068  ///An alias for arcColors()
1069  template<class X> GraphToEps<ArcColorsTraits<X> >
1070  edgeColors(const X &x)
1071  {
1072    return arcColors(x);
1073  }
1074
1075  ///An alias for arcWidthScale()
1076  GraphToEps<T> &edgeWidthScale(double d) {return arcWidthScale(d);}
1077
1078  ///An alias for autoArcWidthScale()
1079  GraphToEps<T> &autoEdgeWidthScale(bool b=true)
1080  {
1081    return autoArcWidthScale(b);
1082  }
1083
1084  ///An alias for absoluteArcWidths()
1085  GraphToEps<T> &absoluteEdgeWidths(bool b=true)
1086  {
1087    return absoluteArcWidths(b);
1088  }
1089
1090  ///An alias for parArcDist()
1091  GraphToEps<T> &parEdgeDist(double d) {return parArcDist(d);}
1092
1093  ///An alias for hideArcs()
1094  GraphToEps<T> &hideEdges(bool b=true) {return hideArcs(b);}
1095
1096  ///@}
1097};
1098
1099template<class T>
1100const int GraphToEps<T>::INTERPOL_PREC = 20;
1101template<class T>
1102const double GraphToEps<T>::A4HEIGHT = 841.8897637795276;
1103template<class T>
1104const double GraphToEps<T>::A4WIDTH  = 595.275590551181;
1105template<class T>
1106const double GraphToEps<T>::A4BORDER = 15;
1107
1108
1109///Generates an EPS file from a graph
1110
1111///\ingroup eps_io
1112///Generates an EPS file from a graph.
1113///\param g Reference to the graph to be printed.
1114///\param os Reference to the output stream.
1115///By default it is <tt>std::cout</tt>.
1116///
1117///This function also has a lot of
1118///\ref named-templ-func-param "named parameters",
1119///they are declared as the members of class \ref GraphToEps. The following
1120///example shows how to use these parameters.
1121///\code
1122/// graphToEps(g,os).scale(10).coords(coords)
1123///              .nodeScale(2).nodeSizes(sizes)
1124///              .arcWidthScale(.4).run();
1125///\endcode
1126///
1127///For more detailed examples see the \ref graph_to_eps_demo.cc demo file.
1128///
1129///\warning Don't forget to put the \ref GraphToEps::run() "run()"
1130///to the end of the parameter list.
1131///\sa GraphToEps
1132///\sa graphToEps(GR &g, const char *file_name)
1133template<class GR>
1134GraphToEps<DefaultGraphToEpsTraits<GR> >
1135graphToEps(GR &g, std::ostream& os=std::cout)
1136{
1137  return
1138    GraphToEps<DefaultGraphToEpsTraits<GR> >(DefaultGraphToEpsTraits<GR>(g,os));
1139}
1140
1141///Generates an EPS file from a graph
1142
1143///\ingroup eps_io
1144///This function does the same as
1145///\ref graphToEps(GR &g,std::ostream& os)
1146///but it writes its output into the file \c file_name
1147///instead of a stream.
1148///\sa graphToEps(GR &g, std::ostream& os)
1149template<class GR>
1150GraphToEps<DefaultGraphToEpsTraits<GR> >
1151graphToEps(GR &g,const char *file_name)
1152{
1153  std::ostream* os = new std::ofstream(file_name);
1154  if (!(*os)) {
1155    delete os;
1156    throw IoError("Cannot write file", file_name);
1157  }
1158  return GraphToEps<DefaultGraphToEpsTraits<GR> >
1159    (DefaultGraphToEpsTraits<GR>(g,*os,true));
1160}
1161
1162///Generates an EPS file from a graph
1163
1164///\ingroup eps_io
1165///This function does the same as
1166///\ref graphToEps(GR &g,std::ostream& os)
1167///but it writes its output into the file \c file_name
1168///instead of a stream.
1169///\sa graphToEps(GR &g, std::ostream& os)
1170template<class GR>
1171GraphToEps<DefaultGraphToEpsTraits<GR> >
1172graphToEps(GR &g,const std::string& file_name)
1173{
1174  std::ostream* os = new std::ofstream(file_name.c_str());
1175  if (!(*os)) {
1176    delete os;
1177    throw IoError("Cannot write file", file_name);
1178  }
1179  return GraphToEps<DefaultGraphToEpsTraits<GR> >
1180    (DefaultGraphToEpsTraits<GR>(g,*os,true));
1181}
1182
1183} //END OF NAMESPACE LEMON
1184
1185#endif // LEMON_GRAPH_TO_EPS_H
Note: See TracBrowser for help on using the repository browser.