Improved Leo to Graphviz Script
After working with the Leo to Graphviz script for a little while I realized that it creates redundant edges if there are cloned nodes. An improved script which eliminates the redundant edges follows:
@color
@language python
@ Create a Graphviz .dot file displaying the hierarchy under a
@ particular node.
@c
import leoGlobals as g
# Create an edge between parent its child, then repeat the process
# for each child.
# parent: Position object for parent node
# accumulator: text string used to build up the result.
def CreateEdge(parent,accumulator):
for p in parent.children_iter():
accumulator.append("\""+parent.headString()+"\" -> \""+p.headString()+"\"\n")
accumulator = CreateEdge(p,accumulator)
return accumulator
# Uniquifying function stolen from
# http://mail.python.org/pipermail/python-list/2004-July/269510.html
def uniq(a):
"Remove duplicate elements from a. a must be sorted."
p=0
for i in xrange(1,len(a)):
if a[i] != a[p]:
p=p+1
a[p]=a[i]
del a[p+1:]
return a
#### Execution starts here
# The headline of the node to parse
root_node_headline = "<FILL IN NODE HEADLINE>"
# The headline of the node which will contain the output of the
# script.
output_node_headline = "<FILL IN NODE HEADLINE>"
g.es("Parsing hierarchy to .dot file...")
# Find the root node of the hierarchy to be parsed.
root_node = g.findReference(root_node_headline,g.top().rootPosition())
# Traverse the hierarchy
accumulator = []
for p in root_node.children_iter():
accumulator = CreateEdge(p,accumulator)
# Sort the accumulator
accumulator.sort()
# Eliminate duplicates
accumulator = uniq(accumulator)
# Join the accumulator
result = "".join(accumulator)
# Prepend Graphviz preamble for a digraph
result = "digraph arts {\n" + result
# Postpend Graphviz postamble for a digraph
result = result + "}"
# Find the output node
output_node = g.findReference(output_node_headline,g.top().rootPosition())
# And write the result to it.
output_node.setBodyStringOrPane(result)
g.es("Done")

0 Comments:
Post a Comment
<< Home