Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #------------------------------------------------------------------------------
- # Julia Type Graphs
- #------------------------------------------------------------------------------
- ## A short julia program that generates the graph of all subtypes
- ## of a given type, in png format by default. Uses graphviz.
- ## Examples: makegraph(Number, "result.dot")
- ## => returns the name of the png file containing the Number subgraph.
- ## makegraph(Any, "alltypes.dot", "svg")
- ## => returns the name of the svg file containing all the types.
- ## Results:
- ## https://imgur.com/a/CkoOA#0
- ## https://imgur.com/U5vTDNp
- ## Applies recursively a function fn to typ and its subtypes.
- ## The collection of all encountered types are returned.
- ## Examples: length(typeit((x,y)-> nothing, Any))
- ## typeit((x,y)-> "$x -> $y", Any)
- ## length(typeit((x,y)-> println("$x -> $y"), Number))
- function typeit(fn, typ)
- let seen = Dict{Type,Bool}()
- apply = (fn, tp) -> if ~get(seen,tp,false)
- seen[tp] = true
- for child in subtypes(tp)
- fn(tp,child)
- apply(fn, child)
- end
- end
- apply(fn, typ)
- collect(keys(seen))
- end
- end
- ## Graphviz doesn't like non alphanumeric characters, so I replace them with _.
- ## It does not like the type Graph either. So I make a label for this type.
- function edge (typ1, typ2)
- let convert = typ -> map(x-> if isalnum(x) x else '_' end, string(typ))
- c1 = convert(typ1)
- c2 = convert(typ2)
- if c2 == "Graph" ; c2 = "G;\nG [label=\"Graph\"]" ; end
- "$(c1) -> $(c2);\n"
- end
- end
- graphviz_formats = ["png","gif","svg","jpg","svgz","pcl", "mif",
- "pcl", "dia", "ps","fig", "imap","cmapx"]
- ## Produces two files named file and file.png. file is in graphviz dot format.
- ## The png file contains the graph of the subtypes of typ.
- ## The third argument is the output file format, png by default.
- function makegraph(typ, file, format=png)
- if !contains(graphviz_formats, format)
- println("Warning: the output format may not be supported by graphviz.",
- "Here are the default formats: $(join(graphviz_formats, " "))")
- end
- fh = open(file, "w")
- write(fh, "digraph{\n") # oriented graph
- write(fh, "rankdir=LR\n") # layout of the graph from left to right
- typeit((x,y)-> write(fh, edge(x,y)), typ)
- write(fh,"}")
- close(fh)
- run(`dot -T$(format) -O $file`) # graphviz needed here.
- print("$file.$format")
- end
Advertisement
Add Comment
Please, Sign In to add comment