Skip to content

Instantly share code, notes, and snippets.

@ckhung
Created December 13, 2015 12:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ckhung/960478cd035fd9cda118 to your computer and use it in GitHub Desktop.
Save ckhung/960478cd035fd9cda118 to your computer and use it in GitHub Desktop.
generate a random tree in .dot format (for graphviz to process)
#!/usr/bin/python
import argparse, numpy as np
def gen_tree(depth, id, branch):
label = id if args.label is None else args.label
print ' '*depth + id + '[label="' + label + '"];'
if depth >= args.depth:
return
nchild = np.random.poisson(branch)
edge_cmd = ' '*depth + id + '->{'
for i in range(0, nchild):
cid = id+chr(65+i)
edge_cmd += ' ' + cid
gen_tree(depth+1, cid, branch*args.decay)
print edge_cmd + ' }'
parser = argparse.ArgumentParser(description='generate a tree in .dot format (for graphviz)',formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-d', '--depth', type=int, default='5',
help='max depth')
parser.add_argument('-b', '--branch', type=float, default=3.0,
help='expected number of branches for 1st level')
parser.add_argument('-y', '--decay', type=float, default=0.6,
help='branch decay factor')
parser.add_argument('-R', '--root-label', type=str, default='X',
help='node label')
parser.add_argument('-L', '--label', type=str,
help='node label')
args = parser.parse_args()
print '''
// twopi -Tsvg xxx.dot -o xxx.svg
digraph "" {
overlap = scale;
'''
gen_tree(1, args.root_label, args.branch)
print '}'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment