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