Monday, October 22, 2007

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:

@language python
@ Create a Graphviz .dot file displaying the hierarchy under a
@ particular node.

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 

def uniq(a):
        "Remove duplicate elements from a.  a must be sorted."
        for i in xrange(1,len(a)):
            if a[i] != a[p]:
        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>""Parsing hierarchy to .dot file...")

# Find the root node of the hierarchy to be parsed.

root_node = g.findReference(root_node_headline,

# Traverse the hierarchy

accumulator = []
for p in root_node.children_iter():
    accumulator = CreateEdge(p,accumulator)

# Sort the accumulator


# 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,

# And write the result to it.



Post a Comment

Links to this post:

Create a Link

<< Home

Blog Information Profile for gg00