#  Copyright (c) 1997-2004
#  Ewgenij Gawrilow, Michael Joswig (Technische Universitaet Berlin, Germany)
#  http://www.math.tu-berlin.de/polymake,  mailto:polymake@math.tu-berlin.de
#
#  This program is free software; you can redistribute it and/or modify it
#  under the terms of the GNU General Public License as published by the
#  Free Software Foundation; either version 2, or (at your option) any
#  later version: http://www.gnu.org/licenses/gpl.txt.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#-----------------------------------------------------------------------------
#  $Project: polymake $$Id: VisualGraph.pm,v 1.10 2004/10/26 19:00:44 gawrilow Exp $

##############################################################################
#
#  This is an intermediate layer between the concrete graph representation
#  as a polymake property and the graph description in an application-specific
#  format (such as GML for graphlet or JVX for javaview)
#
##############################################################################

package Visual::Graph;

use Struct (
   [ '@ISA' => 'Visual::Object' ],

   # \@list  - graph in polymake format, may have node and/or edge attributes
   [ '$Graph' => 'unify_graph( #% )', 'croak("Graph missing")' ],

   # boolean
   '$Directed',

   # Graph embedding in R^2 or R^3:
   #     [ "x y [z]", ... ]		- coordinates of nodes
   #  or Visual::Embedding object	- if lazy
   [ '$Vertices | Coord' => 'check_points( #% )' ],

   # see PointLabels in Visual::PointSet
   [ '$VertexLabels | NodeLabels' => 'unify_labels( #% )', 'undef' ],

   # the same formats as for PointColor in Visual::PointSet
   # Some viewers (for example, PostScript, Graphlet) can draw node boxes either filled (default)
   # or white with colored border.  The latter is chosen if the color value starts
   # with the keyword "border".
   [ '$VertexColor | NodeColor' => 'unify_decor( #% )', '$Visual::Color::vertices' ],

   # the same formats as for PointStyle in Visual::PointSet
   # recognized styles are:
   #   "thickness N"	node box border width
   #   "hidden"         draw neither node boxes nor the labels
   # other possible style keywords are documented in the viewer packages (for example, Graphlet.pm)
   [ '$VertexStyle | NodeStyle' => 'unify_decor( #% )' ],

   #    "R G B"				the same color for all edges
   # or [ "R G B", ... ]		indexed by source node number
   # or { node => "R G B" }		keyed by source node number
   # or { "node node" => "R G B"  }	keyed by incident node numbers
   # or sub { ... }			edge_iterator -> "R G B"
   [ '$EdgeColor' => '$Visual::Color::graph' ],

   # the same formats as for EdgeColor
   # recognized styles are:
   #   "thickness N"		the edge line width
   # as well as other viewer-specific keywords
   '$EdgeStyle',

   # boolean: when looking for edge color and style, whether to try the reverse edge
   #          if the straight lookup fails
   # default: !Directed
   [ '$EdgeStyleSymmetric' => 'undef' ],

   # boolean: don't show the object at the session start (for interactive viewers)
   '$Hidden',
);

# publicly accessible attributes
declare %decorations=( VertexLabels => enum('hidden'), NodeLabels => enum('hidden') );
@decorations{qw( Name NodeColor NodeStyle VertexColor VertexStyle EdgeColor EdgeStyle Hidden )}=();

##############################################################################
my $strip_node_attr=qr{ ^\s* \( .*? (\{.*\}) \s* \) \s*$ }x;
my $adj_nodes_with_attrs=qr{ \( (\d*) }x;
my $adj_nodes_without_attrs=qr{ \d+ }x;

sub unify_graph {
   my ($name, $G)=@_;

   if (!is_array($G)) {
      croak( "$name must be an array" );
   }

   # get rid of all attributes
   if (@$G && !is_array($G->[0]) && !is_object($G->[0])) {
      my $adj_nodes;
      $G=[ map {
	 my $inc=$_;
	 $inc =~ s/$strip_node_attr/$1/;
	 $adj_nodes ||= $inc =~ /\(/ ? $adj_nodes_with_attrs : $adj_nodes_without_attrs;
	 [ $inc =~ m{$adj_nodes}g ]
      } @$G ];
   }
   $G;
}

##############################################################################
sub unify_edge_decoration {
   my ($self, $get_decor)=@_;

   my $symmetric=$self->EdgeStyleSymmetric;
   $symmetric=!$self->Directed if !defined $symmetric;

   is_array($get_decor)
   ? $symmetric
     ? sub {
          my ($s,$t)=(shift)->incident_nodes;
	  $get_decor->[$s]  ||  $get_decor->[$t]
       }
     : sub {
          my ($s,$t)=(shift)->incident_nodes;
	  $get_decor->[$s]
       }
   : $symmetric
     ? sub {
          my ($s,$t)=(shift)->incident_nodes;
	  $get_decor->{"$s $t"} || $get_decor->{"$t $s"} || $get_decor->{$s} || $get_decor->{$t}
       }
     : sub {
          my ($s,$t)=(shift)->incident_nodes;
	  $get_decor->{"$s $t"} || $get_decor->{$s}
       }
}
##############################################################################
sub new {
   my $self=&_new;
   foreach my $decor (qw( EdgeColor EdgeStyle)) {
      my $get_decor=$self->$decor;
      if (ref($get_decor) && !is_code($get_decor)) {
	 $self->$decor=unify_edge_decoration($self, $get_decor);
      }
   }
   $self;
}
############################################################################
#
#  The rest of the interface are callback functions for the visualization
#  program interface.  The most of the methods are self-explanatory.
#
############################################################################

# () -> integer
sub get_number_nodes {
   my ($self)=@_;
   return scalar(@{$self->Graph});
}

# () -> boolean
sub is_embedded {
   my ($self)=@_;
   return defined($self->Coord);
}

my @edge_iterator=qw( Visual::Graph::undirected_edge_iterator
		      Visual::Graph::directed_edge_iterator
		      Visual::Graph::reverse_edge_iterator );

# (node_index) -> iterator
sub get_incident_edges {
   my ($self, $n)=@_;
   my $iter=$edge_iterator[$self->Directed]->new($n, $self->Graph->[$n]);
   $iter;
}

sub get_edge_label { undef }

sub get_all_edges {
   my ($self)=@_;
   my @edges;
   for (my $edge=$self->edges; $edge; ++$edge) {
      my ($s, $t)=$edge->incident_nodes;
      push @edges, "$s $t";
   }
   @edges;
}

#################################################################################
sub has_edge {
   my ($self, $s, $t)=@_;
   my $g=$self->Graph;
   $s<=$#$g && $t<=$#$g && binsearch($g->[$s], $t);
}

#################################################################################
#
#  edge iterators visit the edges incident to a given node
#
#################################################################################
package Visual::Graph::directed_edge_iterator;

use Struct (
   [ new => '$$' ],
   [ '$from_node' => '#1' ],
   [ '@adjacent' => '#2' ],
   [ '$cur' => '0' ],
);

sub clone { my ($self)=@_; bless [ @$self ], ref($self) }

use overload (
   # move to the next edge
   '++' => sub { my ($self)=@_; ++$self->cur; $self },

   # still edges to visit?
   'bool' => sub { my ($self)=@_; $self->cur <= $#{$self->adjacent} },

   # copy constructor
   '=' => \&clone,
);

sub incident_nodes { # -> (source_node, target_node)
   my ($self)=@_;
   ($self->from_node, $self->adjacent->[$self->cur])
}

#################################################################################
#
#  the same as above, but swaps the source and the target nodes
#
#################################################################################
package Visual::Graph::reverse_edge_iterator;

use Struct [ '@ISA' => 'Visual::Graph::directed_edge_iterator' ];

sub incident_nodes { # -> (target_node, source_node)
   my ($self)=@_;
   ($self->adjacent->[$self->cur], $self->from_node)
}

#################################################################################
#
#  special case for the undirected graphs: avoids duplication of edges
#
#################################################################################
package Visual::Graph::undirected_edge_iterator;

use Struct [ '@ISA' => 'Visual::Graph::directed_edge_iterator' ];

use overload (
   'bool' => sub {
      my ($self)=@_;
      $self->cur <= $#{$self->adjacent}  &&
      $self->adjacent->[$self->cur] <= $self->from_node;
   },
);

#################################################################################
#
#  visiting all edges in the graph
#
#################################################################################
package Visual::Graph::all_edge_iterator;

use Struct (
   [ new => '$' ],
   [ '$graph' => '#1' ],
   '$it',
);

sub init {
   my ($self, $n)=@_;
   $self->it=$edge_iterator[$self->graph->Directed]->new($n, $self->graph->Graph->[$n]);
}

sub valid_position {
   my ($self)=@_;
   my ($n, $last);
   while (! $self->it) {
      $n ||= $self->it->from_node;
      $last ||= $self->graph->get_number_nodes;
      last if ++$n>=$last;
      init($self,$n);
   }
}

sub new {
   my $self=&_new;
   init($self,0);
   valid_position($self);
   $self;
}

use overload (
   # move to the next edge
   '++' => sub { my ($self)=@_; ++$self->it; valid_position($self); $self },

   # still edges to visit?
   'bool' => sub { $_[0]->it },

   # copy constructor
   '=' => \&Visual::Graph::directed_edge_iterator::clone,
);

sub incident_nodes { $_[0]->it->incident_nodes }

sub Visual::Graph::edges {
   new Visual::Graph::all_edge_iterator($_[0]);
}

#################################################################################
package Visual::Lattice;
@ISA=qw( Visual::Graph );

1

# Local Variables:
# c-basic-offset:3
# End:
