Guest User

Julia type graph generation v2

a guest
Sep 30th, 2013
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.66 KB | None | 0 0
  1. #------------------------------------------------------------------------------
  2. # Julia Type Graphs
  3. #------------------------------------------------------------------------------
  4.  
  5. ## A short julia program that generates the graph of all subtypes
  6. ## of a given type, in png format by default. Uses graphviz.
  7.  
  8. ## Examples: makegraph(Number, "result.dot")
  9. ## => returns the name of the png file containing the Number subgraph.
  10. ## makegraph(Any, "alltypes.dot", "svg")
  11. ## => returns the name of the svg file containing all the types.
  12.  
  13. ## Results:
  14. ## https://imgur.com/a/CkoOA#0
  15. ## https://imgur.com/U5vTDNp
  16.  
  17. ## Applies recursively a function fn to typ and its subtypes.
  18. ## The collection of all encountered types are returned.
  19. ## Examples: length(typeit((x,y)-> nothing, Any))
  20. ## typeit((x,y)-> "$x -> $y", Any)
  21. ## length(typeit((x,y)-> println("$x -> $y"), Number))
  22. function typeit(fn, typ)
  23. let seen = Dict{Type,Bool}()
  24. apply = (fn, tp) -> if ~get(seen,tp,false)
  25. seen[tp] = true
  26. for child in subtypes(tp)
  27. fn(tp,child)
  28. apply(fn, child)
  29. end
  30. end
  31. apply(fn, typ)
  32. collect(keys(seen))
  33. end
  34. end
  35.  
  36. ## Graphviz doesn't like non alphanumeric characters, so I replace them with _.
  37. ## It does not like the type Graph either. So I make a label for this type.
  38. function edge (typ1, typ2)
  39. let convert = typ -> map(x-> if isalnum(x) x else '_' end, string(typ))
  40. c1 = convert(typ1)
  41. c2 = convert(typ2)
  42. if c2 == "Graph" ; c2 = "G;\nG [label=\"Graph\"]" ; end
  43. "$(c1) -> $(c2);\n"
  44. end
  45. end
  46.  
  47. graphviz_formats = ["png","gif","svg","jpg","svgz","pcl", "mif",
  48. "pcl", "dia", "ps","fig", "imap","cmapx"]
  49.  
  50. ## Produces two files named file and file.png. file is in graphviz dot format.
  51. ## The png file contains the graph of the subtypes of typ.
  52. ## The third argument is the output file format, png by default.
  53. function makegraph(typ, file, format=png)
  54. if !contains(graphviz_formats, format)
  55. println("Warning: the output format may not be supported by graphviz.",
  56. "Here are the default formats: $(join(graphviz_formats, " "))")
  57. end
  58. fh = open(file, "w")
  59. write(fh, "digraph{\n") # oriented graph
  60. write(fh, "rankdir=LR\n") # layout of the graph from left to right
  61. typeit((x,y)-> write(fh, edge(x,y)), typ)
  62. write(fh,"}")
  63. close(fh)
  64. run(`dot -T$(format) -O $file`) # graphviz needed here.
  65. print("$file.$format")
  66. end
Advertisement
Add Comment
Please, Sign In to add comment