Importing DOT file with vertex attributes using JGrapht 1.5.2

92 Views Asked by At

I would like to import a dotfile such as this one:

digraph test {
  "T0" [X=1, Y=Hello];
  "T1" [X=2, Y=Bye];
  "T0" -> "T1";
}

In a Java program using JGrapht (or any other graph library, really...) That's what I've got so far from here:

Graph<String, DefaultEdge> DAG = new SimpleDirectedGraph<>(DefaultEdge.class);

DOTImporter<String, DefaultEdge> dotImporter = new DOTImporter<>();
dotImporter.setVertexFactory(label -> label);
dotImporter.importGraph(DAG, /* InputStream here */);

Clearly I need to replace String type and the vertex factory with something else, but how to I tell JGrapht to retain the X and Y attributes? Thanks for your help

1

There are 1 best solutions below

0
On

I managed to successfully parse my dotfile by following this. It is very ugly and cumbersome.

Graph<String, DefaultEdge> DAG = new SimpleDirectedGraph<>(DefaultEdge.class);

DOTImporter<String, DefaultEdge> dotImporter = new DOTImporter<>();
dotImporter.setVertexFactory(label -> label);

Map<String, Map<String, Attribute>> attrs = new HashMap<>();
dotImporter.addVertexAttributeConsumer((p, a) -> {
Map<String, Attribute> map = attrs.computeIfAbsent(p.getFirst(), k -> new HashMap<>());
    map.put(p.getSecond(), a);
});

dotImporter.importGraph(DAG, /* InputStream here */);

for (String v : DAG.vertexSet()) {
    System.out.println(v+" "+attrs.get(v));
}