Graph::Easy(3)

NAME
Graph::Easy - Convert or render graphs (as ASCII, HTML, SVG or via Graphviz)

SYNOPSIS
        use Graph::Easy;

        my $graph = Graph::Easy->new();

        # make a fresh copy of the graph
        my $new_graph = $graph->copy();

        $graph->add_edge ('Bonn', 'Berlin');

        # will not add it, since it already exists
        $graph->add_edge_once ('Bonn', 'Berlin');

        print $graph->as_ascii( );              # prints:

        # +------+     +--------+
        # | Bonn | --> | Berlin |
        # +------+     +--------+

        #####################################################
        # alternatively, let Graph::Easy parse some text:

        my $graph = Graph::Easy->new( '[Bonn] -> [Berlin]' );

        #####################################################
        # slightly more verbose way:

        my $graph = Graph::Easy->new();

        my $bonn = $graph->add_node('Bonn');
        $bonn->set_attribute('border', 'solid 1px black');

        my $berlin = $graph->add_node('Berlin');

        $graph->add_edge ($bonn, $berlin);

        print $graph->as_ascii( );

        # You can use plain scalars as node names and for the edge label:
        $graph->add_edge ('Berlin', 'Frankfurt', 'via train');

        # adding edges with attributes:

        my $edge = Graph::Easy::Edge->new();
        $edge->set_attributes( {
                label => 'train',
                style => 'dotted',
                color => 'red',
        } );

        # now with the optional edge object
        $graph->add_edge ($bonn, $berlin, $edge);

        # raw HTML section
        print $graph->as_html( );

        # complete HTML page (with CSS)
        print $graph->as_html_file( );

        # Other possibilities:

        # SVG (possible after you installed Graph::Easy::As_svg):
        print $graph->as_svg( );

        # Graphviz:
        my $graphviz = $graph->as_graphviz();
        open $DOT, '|dot -Tpng -o graph.png' or die ("Cannot open pipe to dot: $!");
        print $DOT $graphviz;
        close $DOT;

        # Please see also the command line utility 'graph-easy'

DESCRIPTION
"Graph::Easy" lets you generate graphs consisting of various shaped nodes connected by edges (with optional labels).

It can read and write graphs in a variety of formats, as well as render them via its own grid-based layouter.

Since the layouter works on a grid (manhattan layout), the output is most useful for flow charts, network diagrams, or hierarchy trees.

  Input
Apart from driving the module with Perl code, you can also use "Graph::Easy::Parser" to parse graph descriptions like:

        [ Bonn ]      --> [ Berlin ]
        [ Frankfurt ] <=> [ Dresden ]
        [ Bonn ]      --  [ Frankfurt ]

See the "EXAMPLES" section below for how this might be rendered.

  Creating graphs
First, create a graph object:

        my $graph = Graph::Easy->new();

Then add a node to it:

        my $node = $graph->add_node('Koblenz');

Don't worry, adding the node again will do nothing:

        $node = $graph->add_node('Koblenz');

You can get back a node by its name with "node()":

        $node = $graph->node('Koblenz');

You can either add another node:

        my $second = $graph->node('Frankfurt');

Or add an edge straight-away:

        my ($first,$second,$edge) = $graph->add_edge('Mainz','Ulm');

Adding the edge the second time creates another edge from 'Mainz' to 'Ulm':

        my $other_edge;
         ($first,$second,$other_edge) = $graph->add_edge('Mainz','Ulm');

This can be avoided by using "add_edge_once()":

        my $edge = $graph->add_edge_once('Mainz','Ulm');
        if (defined $edge)
          {
          # the first time the edge was added, do something with it
          $edge->set_attribute('color','blue');
          }

You can set attributes on nodes and edges:

        $node->attribute('fill', 'yellow');
        $edge->attribute('label', 'train');

It is possible to add an edge with a label:

        $graph->add_edge('Cottbus', 'Berlin', 'my label');

You can also add self-loops:

        $graph->add_edge('Bremen','Bremen');

Adding multiple nodes is easy:

        my ($bonn,$rom) = Graph::Easy->add_nodes('Bonn','Rom');

You can also have subgraphs (these are called groups):

        my ($group) = Graph::Easy->add_group('Cities');

Only nodes can be part of a group, edges are automatically considered to be in the group if they lead from one node inside the group to another node in the same group. There are multiple ways to add one or more nodes into a group:

        $group->add_member($bonn);
        $group->add_node($rom);
        $group->add_nodes($rom,$bonn);

For more options please see the online manual: <http://bloodgate.com/perl/graph/manual/> .

  Output
The output can be done in various styles:

ASCII ART
    Uses things like "+", "-" "<" and "|" to render the boxes.

BOXART
    Uses Unicode box art drawing elements to output the graph.

HTML
    HTML tables with CSS making everything "pretty".

SVG Creates a Scalable Vector Graphics output.

Graphviz
    Creates graphviz code that can be feed to 'dot', 'neato' or similar programs.

GraphML
    Creates a textual description of the graph in the GraphML format.

GDL/VCG
    Creates a textual description of the graph in the VCG or GDL (Graph Description Language) format.

EXAMPLES
The following examples are given in the simple text format that is understood by Graph::Easy::Parser.

You can also see many more examples at:

<http://bloodgate.com/perl/graph/>

  One node
The most simple graph (apart from the empty one :) is a graph consisting of only one node:

        [ Dresden ]

  Two nodes
A simple graph consisting of two nodes, linked together by a directed edge:

        [ Bonn ] -> [ Berlin ]

  Three nodes
A graph consisting of three nodes, and both are linked from the first:

        [ Bonn ] -> [ Berlin ]
        [ Bonn ] -> [ Hamburg ]

  Three nodes in a chain
A graph consisting of three nodes, showing that you can chain connections together:

        [ Bonn ] -> [ Berlin ] -> [ Hamburg ]

  Two not connected graphs
A graph consisting of two separate parts, both of them not connected to each other:

        [ Bonn ] -> [ Berlin ]
        [ Freiburg ] -> [ Hamburg ]

  Three nodes, interlinked
A graph consisting of three nodes, and two of the are connected from the first node:

        [ Bonn ] -> [ Berlin ]
        [ Berlin ] -> [ Hamburg ]
        [ Bonn ] -> [ Hamburg ]

  Different edge styles
A graph consisting of a couple of nodes, linked with the different possible edge styles.

        [ Bonn ] <-> [ Berlin ]         # bidirectional
        [ Berlin ] ==> [ Rostock ]      # double
        [ Hamburg ] ..> [ Altona ]      # dotted
        [ Dresden ] - > [ Bautzen ]     # dashed
        [ Leipzig ] ~~> [ Kirchhain ]   # wave
        [ Hof ] .-> [ Chemnitz ]        # dot-dash
        [ Magdeburg ] <=> [ Ulm ]       # bidrectional, double etc
        [ Magdeburg ] -- [ Ulm ]        # arrow-less edge

More examples at: <http://bloodgate.com/perl/graph/>

ANIMATION SUPPORT
Note: Animations are not yet implemented!

It is possible to add animations to a graph. This is done by adding steps via the pseudo-class "step":

        step.0 {
          target: Bonn;         # find object with id=Bonn, or
                                # if this fails, the node named
                                # "Bonn".
          animate: fill:        # animate this attribute
          from: yellow;         # start value (0% of duration)
          via: red;             # at 50% of the duration
          to: yellow;           # and 100% of duration
          wait: 0;              # after triggering, wait so many seconds
          duration: 5;          # entire time to go from "from" to "to"
          trigger: onload;      # when to trigger this animation
          repeat: 2;            # how often to repeat ("2" means two times)
                                # also "infinite", then "next" will be ignored
          next: 1;              # which step to take after repeat is up
        }
        step.1 {
          from: white;          # set to white
          to: white;
          duration: 0.1;        # 100ms
          next: 0;              # go back to step.0
        }

Here two steps are created, 0 and 1 and the animation will be going like this:

                               0.1s
                             +-------------------------------+
                             v                               |
        +--------+  0s   +--------+  5s   +--------+  5s   +--------+
        | onload | ----> | step.0 | ----> | step.0 | ----> | step.1 |
        +--------+       +--------+       +--------+       +--------+

You can generate a a graph with the animation flow via "animation_as_graph()".

  Output
Currently no output formats supports animations yet.

METHODS
"Graph::Easy" supports the following methods:

  new()
        use Graph::Easy;

        my $graph = Graph::Easy->new( );

Creates a new, empty "Graph::Easy" object.

Takes optional a hash reference with a list of options. The following are valid options:

        debug                   if true, enables debug output
        timeout                 timeout (in seconds) for the layouter
        fatal_errors            wrong attributes are fatal errors, default: true
        strict                  test attribute names for being valid, default: true
        undirected              create an undirected graph, default: false

  copy()
    my $copy = $graph->copy( );

Create a copy of this graph and return it as a new Graph::Easy object.

  error()
        my $error = $graph->error();

Returns the last error or '' for none. Optionally, takes an error message to be set.

        $graph->error( 'Expected Foo, but found Bar.' );

See warn() on how to catch error messages. See also non_fatal_errors() on how to turn errors into warnings.

  warn()
        my $warning = $graph->warn();

Returns the last warning or '' for none. Optionally, takes a warning message to be output to STDERR:

        $graph->warn( 'Expected Foo, but found Bar.' );

If you want to catch warnings from the layouter, enable catching of warnings or errors:

        $graph->catch_messages(1);

        # Or individually:
        # $graph->catch_warnings(1);
        # $graph->catch_errors(1);

        # something which warns or throws an error:
        ...

        if ($graph->error())
          {
          my @errors = $graph->errors();
          }
        if ($graph->warning())
          {
          my @warnings = $graph->warnings();
          }

See Graph::Easy::Base for more details on error/warning message capture.

  add_edge()
        my ($first, $second, $edge) = $graph->add_edge( 'node 1', 'node 2');

  add_edge()
        my ($first, $second, $edge) = $graph->add_edge( 'node 1', 'node 2');
        my $edge = $graph->add_edge( $x, $y, $edge);
        $graph->add_edge( $x, $y);

Add an edge between nodes X and Y. The optional edge object defines the style of the edge, if not present, a default object will be used.

When called in scalar context, will return $edge. In array/list context it will return the two nodes and the edge object.

$x and $y should be either plain scalars with the names of the nodes, or objects of Graph::Easy::Node, while the optional $edge should be Graph::Easy::Edge.

Note: "Graph::Easy" graphs are multi-edged, and adding the same edge twice will result in two edges going from $x to $y! See "add_edge_once()" on how to avoid that.

You can also use "edge()" to check whether an edge from X to Y already exists in the graph.

  add_edge_once()
        my ($first, $second, $edge) = $graph->add_edge_once( 'node 1', 'node 2');
        my $edge = $graph->add_edge_once( $x, $y, $edge);
        $graph->add_edge_once( $x, $y);

        if (defined $edge)
          {
          # got added once, so do something with it
          $edge->set_attribute('label','unique');
          }

Adds an edge between nodes X and Y, unless there exists already an edge between these two nodes. See "add_edge()".

Returns undef when an edge between X and Y already exists.

When called in scalar context, will return $edge. In array/list context it will return the two nodes and the edge object.

  flip_edges()
        my $graph = Graph::Easy->new();
        $graph->add_edge('Bonn','Berlin');
        $graph->add_edge('Berlin','Bonn');

        print $graph->as_ascii();

        #   +--------------+
        #   v              |
        # +--------+     +------+
        # | Berlin | --> | Bonn |
        # +--------+     +------+

        $graph->flip_edges('Bonn', 'Berlin');

        print $graph->as_ascii();

        #   +--------------+
        #   |              v
        # +--------+     +------+
        # | Berlin | --> | Bonn |
        # +--------+     +------+

Turn around (transpose) all edges that are going from the first node to the second node.

  add_node()
        my $node = $graph->add_node( 'Node 1' );
        # or if you already have a Graph::Easy::Node object:
        $graph->add_node( $x );

Add a single node X to the graph. $x should be either a "Graph::Easy::Node" object, or a unique name for the node. Will do nothing if the node already exists in the graph.

It returns an Graph::Easy::Node object.

  add_anon_node()
        my $anon_node = $graph->add_anon_node( );

Creates a single, anonymous node and adds it to the graph, returning the "Graph::Easy::Node::Anon" object.

The created node is equal to one created via " [ ] " in the Graph::Easy text description.

  add_nodes()
        my @nodes = $graph->add_nodes( 'Node 1', 'Node 2' );

Add all the given nodes to the graph. The arguments should be either a "Graph::Easy::Node" object, or a unique name for the node. Will do nothing if the node already exists in the graph.

It returns a list of Graph::Easy::Node objects.

  rename_node()
        $node = $graph->rename_node($node, $new_name);

Changes the name of a node. If the passed node is not part of this graph or just a string, it will be added with the new name to this graph.

If the node was part of another graph, it will be deleted there and added to this graph with the new name, effectively moving the node from the old to the new graph and renaming it at the same time.

  del_node()
        $graph->del_node('Node name');
        $graph->del_node($node);

Delete the node with the given name from the graph.

  del_edge()
        $graph->del_edge($edge);

Delete the given edge object from the graph. You can use "edge()" to find an edge from Node A to B:

        $graph->del_edge( $graph->edge('A','B') );

  merge_nodes()
        $graph->merge_nodes( $first_node, $second_node );
        $graph->merge_nodes( $first_node, $second_node, $joiner );

Merge two nodes. Will delete all connections between the two nodes, then move over any connection to/from the second node to the first, then delete the second node from the graph.

Any attributes on the second node will be lost.

If present, the optional $joiner argument will be used to join the label of the second node to the label of the first node. If not present, the label of the second node will be dropped along with all the other attributes:

        my $graph = Graph::Easy->new('[A]->[B]->[C]->[D]');

        # this produces "[A]->[C]->[D]"
        $graph->merge_nodes( 'A', 'B' );

        # this produces "[A C]->[D]"
        $graph->merge_nodes( 'A', 'C', ' ' );

        # this produces "[A C \n D]", note single quotes on the third argument!
        $graph->merge_nodes( 'A', 'C', ' \n ' );

  get_attribute()
        my $value = $graph->get_attribute( $class, $name );

Return the value of attribute $name from class $class.

Example:

        my $color = $graph->attribute( 'node', 'color' );

You can also call all the various attribute related methods on members of the graph directly, for instance:

        $node->get_attribute('label');
        $edge->get_attribute('color');
        $group->get_attribute('fill');

  attribute()
        my $value = $graph->attribute( $class, $name );

Is an alias for get_attribute.

  color_attribute()
        # returns f.i. #ff0000
        my $color = $graph->get_color_attribute( 'node', 'color' );

Just like get_attribute(), but only for colors, and returns them as hex, using the current colorscheme.

  get_color_attribute()
Is an alias for color_attribute().

  get_attributes()
        my $att = $object->get_attributes();

Return all effective attributes on this object (graph/node/group/edge) as an anonymous hash ref. This respects inheritance and default values.

Note that this does not include custom attributes.

See also get_custom_attributes and raw_attributes().

  get_custom_attributes()
        my $att = $object->get_custom_attributes();

Return all the custom attributes on this object (graph/node/group/edge) as an anonymous hash ref.

  custom_attributes()
        my $att = $object->custom_attributes();

"custom_attributes()" is an alias for get_custom_attributes.

  raw_attributes()
        my $att = $object->raw_attributes();

Return all set attributes on this object (graph, node, group or edge) as an anonymous hash ref. Thus you get all the locally active attributes for this object.

Inheritance is respected, e.g. attributes that have the value "inherit" and are inheritable, will be inherited from the base class.

But default values for unset attributes are skipped. Here is an example:

        node { color: red; }

        [ A ] { class: foo; color: inherit; }

This will return:

        { class => foo, color => red }

As you can see, attributes like "background" etc. are not included, while the color value was inherited properly.

See also get_attributes().

  default_attribute()
        my $def = $graph->default_attribute($class, 'fill');

Returns the default value for the given attribute in the class of the object.

The default attribute is the value that will be used if the attribute on the object itself, as well as the attribute on the class is unset.

To find out what attribute is on the class, use the three-arg form of attribute on the graph:

        my $g = Graph::Easy->new();
        my $node = $g->add_node('Berlin');

        print $node->attribute('fill'), "\n";           # print "white"
        print $node->default_attribute('fill'), "\n";   # print "white"
        print $g->attribute('node','fill'), "\n";       # print "white"

        $g->set_attribute('node','fill','red');         # class is "red"
        $node->set_attribute('fill','green');           # this object is "green"

        print $node->attribute('fill'), "\n";           # print "green"
        print $node->default_attribute('fill'), "\n";   # print "white"
        print $g->attribute('node','fill'), "\n";       # print "red"

See also raw_attribute().

  raw_attribute()
        my $value = $object->raw_attribute( $name );

Return the value of attribute $name from the object it this method is called on (graph, node, edge, group etc.). If the attribute is not set on the object itself, returns undef.

This method respects inheritance, so an attribute value of 'inherit' on an object will make the method return the inherited value:

        my $g = Graph::Easy->new();
        my $n = $g->add_node('A');

        $g->set_attribute('color','red');

        print $n->raw_attribute('color');               # undef
        $n->set_attribute('color','inherit');
        print $n->raw_attribute('color');               # 'red'

See also attribute().

  raw_color_attribute()
        # returns f.i. #ff0000
        my $color = $graph->raw_color_attribute('color' );

Just like raw_attribute(), but only for colors, and returns them as hex, using the current colorscheme.

If the attribute is not set on the object, returns "undef".

  raw_attributes()
        my $att = $object->raw_attributes();

Returns a hash with all the raw attributes of that object. Attributes that are no set on the object itself, but on the class this object belongs to are not included.

This method respects inheritance, so an attribute value of 'inherit' on an object will make the method return the inherited value.

  set_attribute()
        # Set the attribute on the given class.
        $graph->set_attribute( $class, $name, $val );

        # Set the attribute on the graph itself. This is synonymous
        # to using 'graph' as class in the form above.
        $graph->set_attribute( $name, $val );

Sets a given attribute named $name to the new value $val in the class specified in $class.

Example:

        $graph->set_attribute( 'graph', 'gid', '123' );

The class can be one of "graph", "edge", "node" or "group". The last three can also have subclasses like in "node.subclassname".

You can also call the various attribute related methods on members of the graph directly, for instance:

        $node->set_attribute('label', 'my node');
        $edge->set_attribute('color', 'red');
        $group->set_attribute('fill', 'green');

  set_attributes()
        $graph->set_attributes( $class, $att );

Given a class name in $class and a hash of mappings between attribute names and values in $att, will set all these attributes.

The class can be one of "graph", "edge", "node" or "group". The last three can also have subclasses like in "node.subclassname".

Example:

        $graph->set_attributes( 'node', { color => 'red', background => 'none' } );

  del_attribute()
        $graph->del_attribute('border');

Delete the attribute with the given name from the object.

You can also call the various attribute related methods on members of the graph directly, for instance:

        $node->del_attribute('label');
        $edge->del_attribute('color');
        $group->del_attribute('fill');

  unquote_attribute()
        # returns '"Hello World!"'
        my $value = $self->unquote_attribute('node','label','"Hello World!"');
        # returns 'red'
        my $color = $self->unquote_attribute('node','color','"red"');

Return the attribute unquoted except for labels and titles, that is it removes double quotes at the start and the end of the string, unless these are escaped with a backslash.

  border_attribute()
        my $border = $graph->border_attribute();

Return the combined border attribute like "1px solid red" from the border(style|color|width) attributes.

  split_border_attributes()
        my ($style,$width,$color) = $graph->split_border_attribute($border);

Split the border attribute (like "1px solid red") into the three different parts.

  quoted_comment()
        my $cmt = $node->comment();

Comment of this object, quoted suitable as to be embedded into HTML/SVG. Returns the empty string if this object doesn't have a comment set.

  flow()
        my $flow = $graph->flow();

Returns the flow of the graph, as absolute number in degress.

  source_nodes()
        my @roots = $graph->source_nodes();

Returns all nodes that have only outgoing edges, e.g. are the root of a tree, in no particular order.

Isolated nodes (no edges at all) will not be included, see predecessorless_nodes() to get these, too.

In scalar context, returns the number of source nodes.

  predecessorless_nodes()
        my @roots = $graph->predecessorless_nodes();

Returns all nodes that have no incoming edges, regardless of whether they have outgoing edges or not, in no particular order.

Isolated nodes (no edges at all) will be included in the list.

See also source_nodes().

In scalar context, returns the number of predecessorless nodes.

  root_node()
        my $root = $graph->root_node();

Return the root node as Graph::Easy::Node object, if it was set with the 'root' attribute.

  timeout()
        print $graph->timeout(), " seconds timeout for layouts.\n";
        $graph->timeout(12);

Get/set the timeout for layouts in seconds. If the layout process did not finish after that time, it will be stopped and a warning will be printed.

The default timeout is 5 seconds.

  strict()
        print "Graph has strict checking\n" if $graph->strict();
        $graph->strict(undef);          # disable strict attribute checks

Get/set the strict option. When set to a true value, all attribute names and values will be strictly checked and unknown/invalid one will be rejected.

This option is on by default.

  type()
        print "Graph is " . $graph->type() . "\n";

Returns the type of the graph as string, either "directed" or "undirected".

  layout()
        $graph->layout();
        $graph->layout( type => 'force', timeout => 60 );

Creates the internal structures to layout the graph.

This method will be called automatically when you call any of the "as_FOO" methods or "output()" as described below.

The options are:

        type            the type of the layout, possible values:
                        'force'         - force based layouter
                        'adhoc'         - the default layouter
        timeout         timeout in seconds

See also: timeout().

  output_format()
        $graph->output_format('html');

Set the outputformat. One of 'html', 'ascii', 'graphviz', 'svg' or 'txt'. See also output().

  output()
        my $out = $graph->output();

Output the graph in the format set by "output_format()".

  as_ascii()
        print $graph->as_ascii();

Return the graph layout in ASCII art, in utf-8.

  as_ascii_file()
        print $graph->as_ascii_file();

Is an alias for as_ascii.

  as_ascii_html()
        print $graph->as_ascii_html();

Return the graph layout in ASCII art, suitable to be embedded into an HTML page. Basically it wraps the output from as_ascii() into "<pre> </pre>" and inserts real HTML links. The returned string is in utf-8.

  as_boxart()
        print $graph->as_box();

Return the graph layout as box drawing using Unicode characters (in utf-8, as always).

  as_boxart_file()
        print $graph->as_boxart_file();

Is an alias for "as_box".

  as_boxart_html()
        print $graph->as_boxart_html();

Return the graph layout as box drawing using Unicode characters, as chunk that can be embedded into an HTML page.

Basically it wraps the output from as_boxart() into "<pre> </pre>" and inserts real HTML links. The returned string is in utf-8.

  as_boxart_html_file()
        print $graph->as_boxart_html_file();

Return the graph layout as box drawing using Unicode characters, as a full HTML page complete with header and footer.

  as_html()
        print $graph->as_html();

Return the graph layout as HTML section. See css() to get the CSS section to go with that HTML code. If you want a complete HTML page then use as_html_file().

  as_html_page()
        print $graph->as_html_page();

Is an alias for "as_html_file".

  as_html_file()
        print $graph->as_html_file();

Return the graph layout as HTML complete with headers, CSS section and footer. Can be viewed in the browser of your choice.

  add_group()
        my $group = $graph->add_group('Group name');

Add a group to the graph and return it as Graph::Easy::Group object.

  group()
        my $group = $graph->group('Name');

Returns the group with the name "Name" as Graph::Easy::Group object.

  rename_group()
        $group = $graph->rename_group($group, $new_name);

Changes the name of the given group. If the passed group is not part of this graph or just a string, it will be added with the new name to this graph.

If the group was part of another graph, it will be deleted there and added to this graph with the new name, effectively moving the group from the old to the new graph and renaming it at the same time.

  groups()
        my @groups = $graph->groups();

Returns the groups of the graph as Graph::Easy::Group objects, in arbitrary order.

  groups_within()
        # equivalent to $graph->groups():
        my @groups = $graph->groups_within();           # all
        my @toplevel_groups = $graph->groups_within(0); # level 0 only

Return the groups that are inside this graph, up to the specified level, in arbitrary order.

The default level is -1, indicating no bounds and thus all contained groups are returned.

A level of 0 means only the direct children, and hence only the toplevel groups will be returned. A level 1 means the toplevel groups and their toplevel children, and so on.

  anon_groups()
        my $anon_groups = $graph->anon_groups();

In scalar context, returns the number of anon groups (aka Graph::Easy::Group::Anon) the graph has.

In list context, returns all anon groups as objects, in arbitrary order.

  del_group()
        $graph->del_group($name);

Delete the group with the given name.

  edges(), edges_within()
        my @edges = $graph->edges();

Returns the edges of the graph as Graph::Easy::Edge objects, in arbitrary order.

edges_within() is an alias for "edges()".

  is_simple_graph(), is_simple()
        if ($graph->is_simple())
          {
          }

Returns true if the graph does not have multiedges, e.g. if it does not have more than one edge going from any node to any other node or group.

Since this method has to look at all edges, it is costly in terms of both CPU and memory.

  is_directed()
        if ($graph->is_directed())
          {
          }

Returns true if the graph is directed.

  is_undirected()
        if ($graph->is_undirected())
          {
          }

Returns true if the graph is undirected.

  parent()
        my $parent = $graph->parent();

Returns the parent graph, for graphs this is undef.

  label()
        my $label = $graph->label();

Returns the label of the graph.

  title()
        my $title = $graph->title();

Returns the (mouseover) title of the graph.

  link()
        my $link = $graph->link();

Return a potential link (for the graphs label), build from the attributes "linkbase" and "link" (or autolink). Returns '' if there is no link.

  as_graphviz()
        print $graph->as_graphviz();

Return the graph as graphviz code, suitable to be feed to a program like "dot" etc.

  as_graphviz_file()
        print $graph->as_graphviz_file();

Is an alias for as_graphviz().

  angle()
        my $degrees = Graph::Easy->angle( 'south' );
        my $degrees = Graph::Easy->angle( 120 );

Check an angle for being valid and return a value between -359 and 359 degrees. The special values "south", "north", "west", "east", "up" and "down" are also valid and converted to degrees.

  nodes()
        my $nodes = $graph->nodes();

In scalar context, returns the number of nodes/vertices the graph has.

In list context, returns all nodes as objects, in arbitrary order.

  anon_nodes()
        my $anon_nodes = $graph->anon_nodes();

In scalar context, returns the number of anon nodes (aka Graph::Easy::Node::Anon) the graph has.

In list context, returns all anon nodes as objects, in arbitrary order.

  html_page_header()
        my $header = $graph->html_page_header();
        my $header = $graph->html_page_header($css);

Return the header of an HTML page. Used together with html_page_footer by as_html_page to construct a complete HTML page.

Takes an optional parameter with the CSS styles to be inserted into the header. If $css is not defined, embedds the result of "$self->css()".

  html_page_footer()
        my $footer = $graph->html_page_footer();

Return the footer of an HTML page. Used together with html_page_header by as_html_page to construct a complete HTML page.

  css()
        my $css = $graph->css();

Return CSS code for that graph. See as_html().

  as_txt()
        print $graph->as_txt();

Return the graph as a normalized textual representation, that can be parsed with Graph::Easy::Parser back to the same graph.

This does not call layout() since the actual text representation is just a dump of the graph.

  as_txt_file()
        print $graph->as_txt_file();

Is an alias for as_txt().

  as_svg()
        print $graph->as_svg();

Return the graph as SVG (Scalable Vector Graphics), which can be embedded into HTML pages. You need to install Graph::Easy::As_svg first to make this work.

See also as_svg_file().

Note: You need Graph::Easy::As_svg installed for this to work!

  as_svg_file()
        print $graph->as_svg_file();

Returns SVG just like "as_svg()", but this time as standalone SVG, suitable for storing it in a file and referencing it externally.

After calling "as_svg_file()" or "as_svg()", you can retrieve some SVG information, notable "width" and "height" via "svg_information".

Note: You need Graph::Easy::As_svg installed for this to work!

  svg_information()
        my $info = $graph->svg_information();

        print "Size: $info->{width}, $info->{height}\n";

Return information about the graph created by the last "as_svg()" or "as_svg_file()" call.

The following fields are set:

        width           width of the SVG in pixels
        height          height of the SVG in pixels

Note: You need Graph::Easy::As_svg installed for this to work!

  as_vcg()
        print $graph->as_vcg();

Return the graph as VCG text. VCG is a subset of GDL (Graph Description Language).

This does not call layout() since the actual text representation is just a dump of the graph.

  as_vcg_file()
        print $graph->as_vcg_file();

Is an alias for as_vcg().

  as_gdl()
        print $graph->as_gdl();

Return the graph as GDL (Graph Description Language) text. GDL is a superset of VCG.

This does not call layout() since the actual text representation is just a dump of the graph.

  as_gdl_file()
        print $graph->as_gdl_file();

Is an alias for as_gdl().

  as_graphml()
        print $graph->as_graphml();

Return the graph as a GraphML representation.

This does not call layout() since the actual text representation is just a dump of the graph.

The output contains only the set attributes, e.g. default attribute values are not specifically mentioned. The attribute names and values are the in the format that "Graph::Easy" defines.

  as_graphml_file()
        print $graph->as_graphml_file();

Is an alias for as_graphml().

  sorted_nodes()
        my $nodes =
         $graph->sorted_nodes( );               # default sort on 'id'
        my $nodes =
         $graph->sorted_nodes( 'name' );        # sort on 'name'
        my $nodes =
         $graph->sorted_nodes( 'layer', 'id' ); # sort on 'layer', then on 'id'

In scalar context, returns the number of nodes/vertices the graph has. In list context returns a list of all the node objects (as reference), sorted by their attribute(s) given as arguments. The default is 'id', e.g. their internal ID number, which amounts more or less to the order they have been inserted.

This routine will sort the nodes by their group first, so the requested sort order will be only valid if there are no groups or inside each group.

  as_debug()
        print $graph->as_debug();

Return debugging information like version numbers of used modules, and a textual representation of the graph.

This does not call layout() since the actual text representation is more a dump of the graph, than a certain layout.

  node()
        my $node = $graph->node('node name');

Return node by unique name (case sensitive). Returns undef if the node does not exist in the graph.

  edge()
        my $edge = $graph->edge( $x, $y );

Returns the edge objects between nodes $x and $y. Both $x and $y can be either scalars with names or "Graph::Easy::Node" objects.

Returns undef if the edge does not yet exist.

In list context it will return all edges from $x to $y, in scalar context it will return only one (arbitrary) edge.

  id()
        my $graph_id = $graph->id();
        $graph->id('123');

Returns the id of the graph. You can also set a new ID with this routine. The default is ''.

The graph's ID is used to generate unique CSS classes for each graph, in the case you want to have more than one graph in an HTML page.

  seed()
        my $seed = $graph->seed();
        $graph->seed(2);

Get/set the random seed for the graph object. See randomize() for a method to set a random seed.

The seed is used to create random numbers for the layouter. For the same graph, the same seed will always lead to the same layout.

  randomize()
        $graph->randomize();

Set a random seed for the graph object. See seed().

  debug()
        my $debug = $graph->debug();    # get
        $graph->debug(1);               # enable
        $graph->debug(0);               # disable

Enable, disable or read out the debug status. When the debug status is true, additional debug messages will be printed on STDERR.

  score()
        my $score = $graph->score();

Returns the score of the graph, or undef if layout() has not yet been called.

Higher scores are better, although you cannot compare scores for different graphs. The score should only be used to compare different layouts of the same graph against each other:

        my $max = undef;

        $graph->randomize();
        my $seed = $graph->seed();

        $graph->layout();
        $max = $graph->score();

        for (1..10)
          {
          $graph->randomize();                  # select random seed
          $graph->layout();                     # layout with that seed
          if ($graph->score() > $max)
            {
            $max = $graph->score();             # store the new max store
            $seed = $graph->seed();             # and it's seed
            }
          }

        # redo the best layout
        if ($seed ne $graph->seed())
          {
          $graph->seed($seed);
          $graph->layout();
          }
        # output graph:
        print $graph->as_ascii();               # or as_html() etc

  valid_attribute()
        my $graph = Graph::Easy->new();
        my $new_value =
          $graph->valid_attribute( $name, $value, $class );

        if (ref($new_value) eq 'ARRAY' && @$new_value == 0)
          {
          # throw error
          die ("'$name' is not a valid attribute name for '$class'")
                if $self->{_warn_on_unused_attributes};
          }
        elsif (!defined $new_value)
          {
          # throw error
          die ("'$value' is no valid '$name' for '$class'");
          }

Deprecated, please use validate_attribute().

Check that a "$name,$value" pair is a valid attribute in class $class, and returns a new value.

It returns an array ref if the attribute name is invalid, and undef if the value is invalid.

The return value can differ from the passed in value, f.i.:

        print $graph->valid_attribute( 'color', 'red' );

This would print '#ff0000';

  validate_attribute()
        my $graph = Graph::Easy->new();
        my ($rc,$new_name, $new_value) =
          $graph->validate_attribute( $name, $value, $class );

Checks a given attribute name and value (or values, in case of a value like "red|green") for being valid. It returns a new attribute name (in case of "font-color" => "fontcolor") and either a single new attribute, or a list of attribute values as array ref.

If $rc is defined, it is the error number:

        1                       unknown attribute name
        2                       invalid attribute value
        4                       found multiple attributes, but these arent
                                allowed at this place

  color_as_hex()
        my $hexred   = Graph::Easy->color_as_hex( 'red' );
        my $hexblue  = Graph::Easy->color_as_hex( '#0000ff' );
        my $hexcyan  = Graph::Easy->color_as_hex( '#f0f' );
        my $hexgreen = Graph::Easy->color_as_hex( 'rgb(0,255,0)' );

Takes a valid color name or definition (hex, short hex, or RGB) and returns the color in hex like "#ff00ff".

  color_value($color_name, $color_scheme)
        my $color = Graph::Easy->color_name( 'red' );   # #ff0000
        print Graph::Easy->color_name( '#ff0000' );     # #ff0000

        print Graph::Easy->color_name( 'snow', 'x11' );

Given a color name, returns the color in hex. See color_name for a list of possible values for the optional $color_scheme parameter.

  color_name($color_value, $color_scheme)
        my $color = Graph::Easy->color_name( 'red' );   # red
        print Graph::Easy->color_name( '#ff0000' );     # red

        print Graph::Easy->color_name( 'snow', 'x11' );

Takes a hex color value and returns the name of the color.

The optional parameter is the color scheme, where the following values are possible:

 w3c                    (the default)
 x11                    (what graphviz uses as default)

Plus the following ColorBrewer schemes are supported, see the online manual for examples and their usage:

 accent3 accent4 accent5 accent6 accent7 accent8

 blues3 blues4 blues5 blues6 blues7 blues8 blues9

 brbg3 brbg4 brbg5 brbg6 brbg7 brbg8 brbg9 brbg10 brbg11

 bugn3 bugn4 bugn5 bugn6 bugn7 bugn8 bugn9 bupu3 bupu4 bupu5 bupu6 bupu7
 bupu8 bupu9

 dark23 dark24 dark25 dark26 dark27 dark28

 gnbu3 gnbu4 gnbu5 gnbu6 gnbu7 gnbu8 gnbu9

 greens3 greens4 greens5 greens6 greens7 greens8 greens9

 greys3 greys4 greys5 greys6 greys7 greys8 greys9

 oranges3 oranges4 oranges5 oranges6 oranges7 oranges8 oranges9

 orrd3 orrd4 orrd5 orrd6 orrd7 orrd8 orrd9

 paired3 paired4 paired5 paired6 paired7 paired8 paired9 paired10 paired11
 paired12

 pastel13 pastel14 pastel15 pastel16 pastel17 pastel18 pastel19

 pastel23 pastel24 pastel25 pastel26 pastel27 pastel28

 piyg3 piyg4 piyg5 piyg6 piyg7 piyg8 piyg9 piyg10 piyg11

 prgn3 prgn4 prgn5 prgn6 prgn7 prgn8 prgn9 prgn10 prgn11

 pubu3 pubu4 pubu5 pubu6 pubu7 pubu8 pubu9

 pubugn3 pubugn4 pubugn5 pubugn6 pubugn7 pubugn8 pubugn9

 puor3 puor4 puor5 puor6 puor7 puor8 puor9 puor10 puor11

 purd3 purd4 purd5 purd6 purd7 purd8 purd9

 purples3 purples4 purples5 purples6 purples7 purples8 purples9

 rdbu3 rdbu4 rdbu5 rdbu6 rdbu7 rdbu8 rdbu9 rdbu10 rdbu11

 rdgy3 rdgy4 rdgy5 rdgy6 rdgy7 rdgy8 rdgy9

 rdpu3 rdpu4 rdpu5 rdpu6 rdpu7 rdpu8 rdpu9 rdgy10 rdgy11

 rdylbu3 rdylbu4 rdylbu5 rdylbu6 rdylbu7 rdylbu8 rdylbu9 rdylbu10 rdylbu11

 rdylgn3 rdylgn4 rdylgn5 rdylgn6 rdylgn7 rdylgn8 rdylgn9 rdylgn10 rdylgn11

 reds3 reds4 reds5 reds6 reds7 reds8 reds9

 set13 set14 set15 set16 set17 set18 set19

 set23 set24 set25 set26 set27 set28

 set33 set34 set35 set36 set37 set38 set39 set310 set311 set312

 spectral3 spectral4 spectral5 spectral6 spectral7 spectral8 spectral9
 spectral10 spectral11

 ylgn3 ylgn4 ylgn5 ylgn6 ylgn7 ylgn8 ylgn9

 ylgnbu3 ylgnbu4 ylgnbu5 ylgnbu6 ylgnbu7 ylgnbu8 ylgnbu9

 ylorbr3 ylorbr4 ylorbr5 ylorbr6 ylorbr7 ylorbr8 ylorbr9

 ylorrd3 ylorrd4 ylorrd5 ylorrd6 ylorrd7 ylorrd8 ylorrd9

  color_names()
        my $names = Graph::Easy->color_names();

Return a hash with name => value mapping for all known colors.

  text_style()
        if ($graph->text_style('bold, italic'))
          {
          ...
          }

Checks the given style list for being valid.

  text_styles()
        my $styles = $graph->text_styles();     # or $edge->text_styles() etc.

        if ($styles->{'italic'})
          {
          print 'is italic\n';
          }

Return a hash with the given text-style properties, aka 'underline', 'bold' etc.

  text_styles_as_css()
        my $styles = $graph->text_styles_as_css();      # or $edge->...() etc.

Return the text styles as a chunk of CSS styling that can be embedded into a " style="" " parameter.

  use_class()
        $graph->use_class('node', 'Graph::Easy::MyNode');

Override the class to be used to constructs objects when calling "add_edge()", "add_group()" or "add_node()".

The first parameter can be one of the following:

        node
        edge
        group

Please see the documentation about "use_class()" in "Graph::Easy::Parser" for examples and details.

  animation_as_graph()
        my $graph_2 = $graph->animation_as_graph();
        print $graph_2->as_ascii();

Returns the animation of $graph as a graph describing the flow of the animation. Useful for debugging animation flows.

  add_cycle()
        $graph->add_cycle('A','B','C');         # A -> B -> C -> A

Compatibility method for Graph, adds the edges between each node and back from the last node to the first. Returns the graph.

  add_path()
        $graph->add_path('A','B','C');          # A -> B -> C

Compatibility method for Graph, adds the edges between each node. Returns the graph.

  add_vertex()
        $graph->add_vertex('A');

Compatibility method for Graph, adds the node and returns the graph.

  add_vertices()
        $graph->add_vertices('A','B');

Compatibility method for Graph, adds these nodes and returns the graph.

  has_edge()
        $graph->has_edge('A','B');

Compatibility method for Graph, returns true if at least one edge between A and B exists.

  vertices()
Compatibility method for Graph, returns in scalar context the number of nodes this graph has, in list context a (arbitrarily sorted) list of node objects.

  set_vertex_attribute()
        $graph->set_vertex_attribute( 'A', 'fill', '#deadff' );

Compatibility method for Graph, set the named vertex attribute.

Please note that this routine will only accept Graph::Easy attribute names and values. If you want to attach custom attributes, you need to start their name with 'x-':

        $graph->set_vertex_attribute( 'A', 'x-foo', 'bar' );

  get_vertex_attribute()
        my $fill = $graph->get_vertex_attribute( 'A', 'fill' );

Compatibility method for Graph, get the named vertex attribute.

Please note that this routine will only accept Graph::Easy attribute names. See set_vertex_attribute().

EXPORT
Exports nothing.

SEE ALSO
Graph, Graph::Convert, Graph::Easy::As_svg, Graph::Easy::Manual and Graph::Easy::Parser.

  Related Projects
Graph::Layout::Aesthetic, Graph and Text::Flowchart.

There is also an very old, unrelated project from ca. 1995, which does something similar. See <http://rw4.cs.uni-sb.de/users/sander/html/gsvcg1.html>.

Testcases and more examples under:

<http://bloodgate.com/perl/graph/>.

LIMITATIONS
This module is now quite complete, but there are still some limitations. Hopefully further development will lift these.

  Scoring
Scoring is not yet implemented, each generated graph will be the same regardless of the random seed.

  Layouter
The layouter can not yet handle links between groups (or between a group and a node, or vice versa). These links will thus only appear in as_graphviz() or as_txt() output.

  Paths

No optimizations
    In complex graphs, non-optimal layout part like this one might appear:

            +------+     +--------+
            | Bonn | --> | Berlin | --> ...
            +------+     +--------+
                           ^
                           |
                           |
            +---------+    |
            | Kassel  | ---+
            +---------+

    A second-stage optimizer that simplifies these layouts is not yet implemented.

    In addition the general placement/processing strategy as well as the local strategy might be improved.

attributes
    The following attributes are currently ignored by the layouter:

            undirected graphs
            autosplit/autojoin for edges
            tail/head label/title/link for edges

groups
    The layouter is not fully recursive yet, so groups do not properly nest.

    In addition, links to/from groups are missing, too.

  Output formats
Some output formats are not yet complete in their implementation. Please see the online manual at <http://bloodgate.com/perl/graph/manual> under "Output" for details.

LICENSE
This library is free software; you can redistribute it and/or modify it under the terms of the GPL 2.0 or a later version.

See the LICENSE file for a copy of the GPL.

This product includes color specifications and designs developed by Cynthia Brewer (http://colorbrewer.org/). See the LICENSE file for the full license text that applies to these color schemes.

NAME CHANGE
The package was formerly known as "Graph::Simple". The name was changed for two reasons:

•   In graph theory, a "simple" graph is a special type of graph. This software, however, supports more than simple graphs.

•   Creating graphs should be easy even when the graphs are quite complex.

AUTHOR
Copyright (C) 2004 - 2008 by Tels <http://bloodgate.com>