i2mint / meshed

Link functions up into callable objects
https://i2mint.github.io/meshed/
MIT License
4 stars 3 forks source link

`DAG.from_dot_digraph` #46

Open thorwhalen opened 1 year ago

thorwhalen commented 1 year ago

We can make a dot digraph from a DAG which is very useful to view it.

We also have some convenient ways to make a DAG, such as the code_to_dag function.

Yet I still find myself sometimes building a graph using the dot language (or rather a mini-dot language (I use from qo import dgdisp)). This may indicate the utility of building a DAG from a dot string.

I tried to write a function that takes a graphviz.Digraph instance and returns the edges of the graph as pairs of node IDs, so that I could then use this to make my DAG (using a similar approach as code_to_dag). But I failed. It seems like those graphviz objects are for writing, not reading -- at least not reading into some python-ready object.

I then decided to go through networkx, which has a lot of conversion tools. This code looked promising.

My slightly modified version:

import networkx as nx

G = nx.complete_graph(5)
A = nx.nx_agraph.to_agraph(G)  # convert to a graphviz graph
X1 = nx.nx_agraph.from_agraph(A)  # convert back to networkx (but as Graph)
X2 = nx.Graph(A)  # fancy way to do conversion
G1 = nx.Graph(X1)  # now make it a Graph

A.write("k5.dot")  # write to dot file
X3 = nx.nx_agraph.read_dot("k5.dot")  # read from dotfile

# You can also create .png directly with the AGraph.draw method
A.draw("k5.png", prog="neato")

# This is what I added, to be able to see the graph:
from IPython.display import Image
Image('k5.png')
thorwhalen commented 1 year ago

Note: I had problems running [the code mentioned above]. I'm told I need pygraphviz, but when I try to pip install I get:

(...)

  error: subprocess-exited-with-error

  × Running setup.py install for pygraphviz did not run successfully.
  │ exit code: 1
  ╰─> [11 lines of output]

(...)

The most voted solution of https://stackoverflow.com/questions/69970147/how-do-i-resolve-the-pygraphviz-error-on-mac-os didn't work for me, but the second did:

https://stackoverflow.com/questions/69970147/how-do-i-resolve-the-pygraphviz-error-on-mac-os

python -m pip install \
    --global-option=build_ext \
    --global-option="-I$(brew --prefix graphviz)/include/" \
    --global-option="-L$(brew --prefix graphviz)/lib/" \
    pygraphviz
sylvainbonnot commented 1 year ago

There is also: pydot It can parse and dump into the dot language and send to networkxx.