Meda
Meda

Reputation: 31

How to create a dot file

I have a program that generate a random graph (DAG), How can I extract the output graph and convert in file dot format In order to visualize it in GraphViz? Or there's another way to do it? Here's the code ( I have omitted all the dependencies) and a simple generated output

public class DigraphGenerator {
    private static final class Edge implements Comparable<Edge> {
        private final int v;
        private final int w;

        private Edge(int v, int w) {
            this.v = v;
            this.w = w;
        }

        public int compareTo(Edge that) {
            if (this.v < that.v) return -1;
            if (this.v > that.v) return +1;
            if (this.w < that.w) return -1;
            if (this.w > that.w) return +1;
            return 0;
        }
    }

    private DigraphGenerator() { }

    public static Digraph dag(int V, int E) {
        if (E > (long) V*(V-1) / 2) throw new IllegalArgumentException("Too many edges");
        if (E < 0)                  throw new IllegalArgumentException("Too few edges");
        Digraph G = new Digraph(V);
        SET<Edge> set = new SET<Edge>();
        int[] vertices = new int[V];
        for (int i = 0; i < V; i++)
            vertices[i] = i;
        StdRandom.shuffle(vertices);
        while (G.E() < E) {
            int v = StdRandom.uniform(V);
            int w = StdRandom.uniform(V);
            Edge e = new Edge(v, w);
            if ((v < w) && !set.contains(e)) {
                set.add(e);
                G.addEdge(vertices[v], vertices[w]);
            }
        }
        return G;
    }

    public static void main(String[] args) {
        int V = Integer.parseInt(args[0]);
        int E = Integer.parseInt(args[1]);

        StdOut.println("DAG");
        StdOut.println(dag(V, E));
        StdOut.println();
    }

}

Examples of output:

DAG 12 vertices, 10 edges 0: 2 1 1: 2: 3: 4: 8 5: 9 6: 7: 8 4 8: 9: 8 10: 5 11: 5 6

DAG 12 vertices, 10 edges 0: 8 1: 8 2: 5 3: 4: 5 5: 6: 7 9 8 7: 8: 9: 10: 11: 5 7 3

Upvotes: 2

Views: 5378

Answers (1)

nidi nidi
nidi nidi

Reputation: 89

Something like this should work:

void writeDot(Digraph d){
  try(BufferedWriter out=new BufferedWriter(new OutputStreamWriter(new FileOutputStream("g.dot")))){
    out.write("digraph {"); 
    out.newLine();
    for(Edge e:d.getEdges()){
      out.write(e.v+" -> "+e.w);
      out.newLine();
    }
    out.write("}");
  }
}

Or you can have a look at https://github.com/nidi3/graphviz-java which takes care of generating dot files and calling graphviz and produces directly png images.

Upvotes: 1

Related Questions