Graph::Easy(3pm)

πŸ“¦
version 0.76 Β· 4 versions
, in debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking

πŸ’– Graph::Easy πŸ’–

okay bestie, sit down, hydrate, because this is the Graph::Easy manual page (that's Graph::Easy(3pm) if you're being formal, from the User Contributed Perl Documentation section) and it is long. Like, five-parts long. This is part one. We're doing this together. 🫢

✨ NAME ✨

Graph::Easy β€” Convert or render graphs (as ASCII, HTML, SVG or via Graphviz). That's the whole vibe. Graphs. Everywhere. πŸ’…


🌈 SYNOPSIS 🌈

okay so here's the little taste test, literally copy-paste this energy:

        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'

yes bestie, that's all of it, we're not skipping a single line in this house πŸ‘‘


🌸 DESCRIPTION 🌸

So "Graph::Easy" lets you generate graphs made out of all sorts of cute shaped nodes, connected by edges (with optional labels, because we love a labeled edge).

It can read and write graphs in a whole bunch of formats, and it can also render them using its very own grid-based layouter. Iconic behaviour, honestly.

Because the layouter works on a grid (manhattan layout, iykyk), the output is most useful for flow charts, network diagrams, or hierarchy trees. That's the niche and it ate. πŸ”₯

πŸ¦‹ Input

Besides driving the module with Perl code (yes, you, writing Perl, slay), you can also use "Graph::Easy::Parser" to parse graph descriptions like this:

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

Peep the "EXAMPLES" section below to see how that might render. πŸ‘€

πŸŽ€ Creating graphs

First things first, you make a graph object:

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

Then you add a node to it:

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

And don't stress β€” adding the node again does absolutely nothing. No duplicates, no drama:

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

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

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

You can either add another node:

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

Or just add an edge straight-away:

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

But heads up bestie β€” adding the edge a second time creates another edge from 'Mainz' to 'Ulm'. Not a duplicate-check situation:

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

You dodge that whole situation 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');

And yes, it is possible to add an edge with a label:

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

You can also add self-loops. A node pointing at itself. Main character energy, truly:

        $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, okay? 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. That's just how it is. 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. (So you're reading the input language, not the output. Just so we're clear.)

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! So like… look but don't touch, bestie. 😭

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. (Right? Right. We said what we said.)


πŸ’… METHODS πŸ’…

"Graph::Easy" supports the following methods:

πŸ‘‘ new()

        use Graph::Easy;

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

Creates a new, empty "Graph::Easy" object. Fresh out the box, no notes. ✨

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. Dupe it. Clone it. Give it a twin. 🫢

πŸ‘‘ 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. (Errors getting a lil glow-up, honestly.)

πŸ‘‘ 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() (again, bestie, bc the page lists it twice) πŸ’–

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

ok so this one adds an edge between nodes X and Y ✨ The optional edge object is what defines the style of that edge β€” and if you don't hand one over, a default object just shows up and does the job. no biggie.

When you call it in scalar context, you get $edge back. In array/list context it hands you the two nodes and the edge object. πŸŽ€

$x and $y should be either plain scalars holding the node names, or actual Graph::Easy::Node objects β€” while the optional $edge should be a Graph::Easy::Edge. πŸ¦‹

Note: Graph::Easy graphs are multi-edged, so adding the same edge twice gives you literally two edges going from $x to $y! Not a bug, it's a feature, it's giving ✨double trouble✨. If you wanna avoid that, go look at add_edge_once().

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's already an edge chilling between those two nodes. Basically add_edge() but with boundaries. 🚧

Returns undef when an edge between X and Y already exists. (so check that defined, bestie)

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 the edges going from the first node to the second node. ✨ It's giving glow-up, it's giving the arrow said sike. πŸŽ€


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 β€” no duplicates here, we don't do that.

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. iykyk 🫢


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. (same energy as add_node(), just in bulk πŸ’…)

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 node you passed isn't part of this graph, or is just a plain string, it gets added to this graph under the new name.

If the node was part of another graph, it gets deleted there and added here with the new name β€” so basically it moves the node from the old graph to the new graph and renames it at the same time. iconic multi-tasking behavior, honestly. πŸ‘‘


del_node() πŸ’€

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

Delete the node with the given name from the graph. gone. poof. not me deleting nodes at 2am πŸ™ˆ


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. Here's the whole ritual: it 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. fr fr, they're gone.

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 it's not present, the label of the second node gets dropped right 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 ' );

not the single quotes on that third argument β€” they're load-bearing, bestie, don't touch them! 🫢


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. same vibe, different name, we love a shortcut. πŸ’…


color_attribute() 🎨

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

Just like get_attribute(), but only for colors, and it 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() (the first one) πŸ“

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

Return all set attributes on this object (graph, node, group or edge) as an anonymous hash ref. So 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's 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. (so it's the last line of defense, the safety net, the if all else fails πŸ’…)

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 this method is called on (graph, node, edge, group etc.). If the attribute is not set on the object itself, it 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 it returns them as hex, using the current colorscheme. 🌈

If the attribute is not set on the object, it returns "undef". πŸ’€


raw_attributes() (the second one, yes it appears twice) πŸ“

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

Returns a hash with all the raw attributes of that object. Attributes that are not 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 );

okay so bestie, you pass in a class name as $class and a hash of attribute-name β†’ value mappings as $att, and it just... sets all of them for you. one call, many attributes, we love efficiency. ✨

The class can be one of "graph", "edge", "node" or "group". And the last three can also have subclasses, written like "node.subclassname". so fancy. πŸ’–

Example, because examples ate:

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

del_attribute() πŸ—‘οΈ

               $graph->del_attribute('border');

Delete the attribute with the given name from the object. gone. not invited to the party anymore. πŸ’€

You can also call the various attribute-related methods on members of the graph directly, like so:

               $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. so basically it removes double quotes at the start and the end of the string, unless those quotes are escaped with a backslash. iykyk, labels get to keep their drama. πŸ’…

border_attribute() πŸ¦‹

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

Return the combined border attribute like "1px solid red" β€” built from the border(style|color|width) attributes. yes queen, it assembles it for you. ✨

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. reverse uno card, slay. πŸ”₯

quoted_comment() πŸ’¬

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

Comment of this object, quoted suitably so it can be embedded into HTML/SVG. Returns the empty string if this object doesn't have a comment set. no comment? no content. periodt. 🌸

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 β€” like, the root of a tree, main character energy β€” 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. she's inclusive like that. πŸ’–

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 a 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. like, wrap it up bestie, we're on a schedule. 😭

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 ones will be rejected. no chaos allowed, we're keeping it clean. πŸ’…

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. lowkey the whole glow-up moment. ✨

This method will be called automatically when you call any of the "as_FOO" methods or "output()" as described below. so you don't even have to think about it, she handles it. 🫢

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. retro but make it cute. πŸ’–

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). the way this one serves looks. 😍

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 a 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. the whole package. iconic. ✨

as_html() πŸ’»

               print $graph->as_html();

Return the graph layout as an 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. go ahead, open it in all of them, you deserve it. πŸ’…

add_group() βž•

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

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

group() πŸ”

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

Returns the group with the name "Name" as a 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 is just a string, it will be added with the new name to this graph. she's flexible like that. πŸ’–

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. glow-up and relocation in one step, we love a multitasker. ✨

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. everything, everywhere, all at once. 🌈

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. nesting dolls energy, fr fr. πŸͺ†

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. bye bestie. πŸ’€

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. simple, clean, unproblematic. ✨

Since this method has to look at all edges, it is costly in terms of both CPU and memory. so like, use it wisely bestie, it's giving expensive. 😭

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. no parent? she's the parent. πŸ‘‘

label() 🏷️

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

Returns the label of the graph.

title() πŸ’¬

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

Returns the (mouseover) title of the graph.

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

Return a potential link (for the graph's 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. compass girlies stay winning. πŸ§­πŸ’…

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()".

               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();

Returns the CSS code for that graph. Go peek at as_html() for the full tea. πŸ’…

as_txt()

print $graph->as_txt();

Hands you the graph as a normalized textual representation β€” the kind that Graph::Easy::Parser can munch right back up and rebuild into the exact same graph. round trip slay πŸ”βœ¨

Bestie, important: this does not call layout(), because the text representation is literally just a dump of the graph, not a laid-out version. no cap.

as_txt_file()

print $graph->as_txt_file();

It's an alias for as_txt(). same energy, different name 🫢

as_svg()

print $graph->as_svg();

Returns the graph as SVG (Scalable Vector Graphics) β€” perfect for embedding into HTML pages. You do need to install Graph::Easy::As_svg first for this to work tho.

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(), except this time it's standalone SVG β€” the kind you'd store in a file and reference externally. main character file energy πŸ‘‘βœ¨

After calling as_svg_file() or as_svg(), you can grab some SVG information, notably 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";

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

These fields get 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();

Returns the graph as VCG text. VCG is a subset of GDL (Graph Description Language). πŸŽ€

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

as_vcg_file()

print $graph->as_vcg_file();

It's an alias for as_vcg(). 🫢

as_gdl()

print $graph->as_gdl();

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

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

as_gdl_file()

print $graph->as_gdl_file();

It's an alias for as_gdl(). 🫢

as_graphml()

print $graph->as_graphml();

Returns the graph as a GraphML representation. πŸ¦‹

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

The output contains only the set attributes β€” like, 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();

It's 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, this returns the number of nodes/vertices the graph has. In list context it returns a list of all the node objects (as references), sorted by their attribute(s) given as arguments. Default is 'id', aka their internal ID number, which amounts more or less to the order they've been inserted. πŸ’…

Heads up: this routine sorts the nodes by their group first, so your requested sort order is only valid if there are no groups, or inside each group. iykyk 🧚

as_debug()

print $graph->as_debug();

Returns debugging information β€” stuff like version numbers of used modules, plus a textual representation of the graph. πŸ”

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

node()

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

Returns a node by its unique name (case sensitive). Returns undef if that node doesn't 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 doesn't exist yet.

In list context it returns all edges from $x to $y; in scalar context it returns just 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 β€” for when you want more than one graph on an HTML page. obsessed.

seed()

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

Get/set the random seed for the graph object. See randomize() for a method that sets 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. deterministic queen πŸ‘‘

randomize()

$graph->randomize();

Sets 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, extra debug messages get printed on STDERR. πŸ”πŸ’¬

score()

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

Returns the score of the graph, or undef if layout() hasn't been called yet.

Higher scores are better, but ngl you cannot compare scores for different graphs. The score should only ever 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(). πŸ’€

Checks 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 value you passed in, 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 the case of a value like "red|green") for being valid. It returns a new attribute name (in the case of "font-color" => "fontcolor") and either a single new attribute, or a list of attribute values as an array ref. ✨

If $rc is defined, it's 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();

Hands you back a hash where name maps to value for every single known color. All of them. The whole palette bestie πŸ’–

text_style() ✨

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

Vibe-checks your style list to see if it's valid or not. That's the whole job, and she does it flawlessly πŸ’…

text_styles() πŸŽ€

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

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

Returns a hash of the text-style properties you've got going on β€” think 'underline', 'bold', all of it. Slay.

text_styles_as_css() 🌈

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

Gives you your text styles as a lil chunk of CSS that you can drop straight into a style="" parameter. It's giving stylist energy πŸ’…

use_class() πŸ‘‘

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

Overrides which class gets used to construct objects when you call add_edge(), add_group() or add_node(). Main character move.

The first parameter can be one of these:

node
edge
group

Peep the docs about use_class() in Graph::Easy::Parser for examples and the full deets, bestie 🫢

animation_as_graph() 🎬

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

Returns the animation of $graph as a graph that describes the flow of the animation. So useful for debugging animation flows, fr fr πŸ”₯

add_cycle() πŸ”

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

A compatibility method for Graph β€” it adds the edges between each node and then loops back from the last node to the first one. Returns the graph. Iconic circular behavior ✨

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. Simple as that πŸ’œ

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 there's at least one edge between A and B. No cap.

vertices() πŸ¦‹

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

set_vertex_attribute() πŸ–ŒοΈ

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

Compatibility method for Graph β€” sets the named vertex attribute.

Heads up bestie: this routine will only accept Graph::Easy attribute names and values. If you wanna attach custom attributes, you gotta 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 β€” gets the named vertex attribute.

Again: this routine will only accept Graph::Easy attribute names. See set_vertex_attribute().

✨ EXPORT ✨

Exports nothing. Zero. Nada. Nothing to see here, move along πŸ’€


πŸ‘€ SEE ALSO πŸ‘€

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

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

There's also a very old, unrelated project from like ca. 1995 that does something similar. Go peep:

<http://rw4.cs.uni-sb.de/users/sander/html/gsvcg1.html>.

Testcases and more examples live right here:

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


🚧 LIMITATIONS 🚧

This module is now quite complete, but bestie… there are still some limitations. Hopefully further development will lift these. Fingers crossed 🀞

πŸ“Š Scoring πŸ“Š

Scoring is not yet implemented β€” every generated graph will be the same regardless of the random seed. Yeah. Same graph every time.

🧩 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 show up in as_graphviz() or as_txt() output.

πŸ›€οΈ Paths πŸ›€οΈ

No optimizations

In complex graphs, non-optimal layout parts like this one might appear:

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

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

On top of that, 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.

And on top of that? 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 the deets.


πŸ“œ 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. Yes, the colors have their own licensing moment πŸ’–


πŸ’« NAME CHANGE πŸ’«

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

  • In graph theory, a "simple" graph is a special type of graph. This software, however, supports more than simple graphs. So… yeah, the name was lowkey a lie.
  • Creating graphs should be easy even when the graphs are quite complex.

Rebrand era πŸ‘‘


πŸ‘‘ AUTHOR πŸ‘‘

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


And that's the whole page bestie, we ate πŸ“ This was Graph::Easy(3pm) from perl v5.36.0, dated 2022-11-20. Go forth and graph slay πŸ’…βœ¨πŸ¦‹