Ocamlgraph visualization

Anne ocaml ocamlgraph graphe dot

I often use ocamlgraph to build graphs, and the Graphviz.Dot to export them in dot format to be able to see them. This page summarize how to do.

Graph Information

It is interesting to notice that a previously built ocamlgraph is not mandatory. All that is needed is something that provides:

module G : sig
  type t
  module V: sig
    type t
  module E: sig
    type t

  val iter_vertex : (V.t -> unit) -> t -> unit
  val iter_edges_e : (E.t -> unit) -> t -> unit

If you already have an ocamlgraph graph, it is already provided in it, but you can imagine providing this signature for any data structures of your own.

Customize the graph

Beside the types of the elements and the functions to traverse the graph, some functions must be provides about the design of the graph. We build a new module GPrinter similar to:

module GPrinter = struct
  include G

  (* ... <implementation of the functions described below> ...*)

Naming the nodes

The only mandatory feature is to give a name to the nodes:

val vertex_name : V.t -> string

The name here is used to internally identify the node and, even if it is the default, it doesn’t have to be the same than the text printed on it which is the ```Label`` attribute. Be careful that it should respect the usual constrains about identifiers.


An optional feature is to group some nodes in subgraphs. The function should return None is this is not needed.

val get_subgraph : V.t -> Graphviz.DotAttributes.subgraph option

Otherwise it has to return Some sg with sg having the type:

type subgraph = {
   sg_name : string;
   sg_attributes : Graphviz.DotAttributes.vertex list;
   sg_parent : string option;

Like the vertex_name, the sg_name is an identifier of the subgraph. Notice that is means that two subgraphs with the same name must have the same attributes, since they are the same.

The subgraphs have the same kind of attributes than the vertex.

Other attributes

The other functions should provide lists of attributes that can be left empty for a very simple design:

val graph_attributes : t -> Graphviz.DotAttributes.graph list

val default_vertex_attributes : t -> Graphviz.DotAttributes.vertex list
val vertex_attributes : V.t -> Graphviz.DotAttributes.vertex list

val default_edge_attributes : t -> Graphviz.DotAttributes.edge list
val edge_attributes : E.t -> Graphviz.DotAttributes.edge list

Export the Graph

Exporting the graph is then as simple as:

module DotExport = Graph.Graphviz.Dot(GPrinter)

let export_graph g filename
  let file = open_out filename in
  DotExport.output_graph file graph;
  close_out file

Notice that you may want to filter the graph before exporting it.


Voir aussi :