Welcome, guest | Sign In | My Account | Store | Cart

This little application generates Mandelbrot/Frame's fractal trees in Python (see http://www.math.union.edu/research/fractaltrees/). Given an iteration depth, a trunk length, and a branching angle, this algorithm generates the corresponding tree. PIL is used to draw the tree.

Python, 51 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/usr/bin/env python
"""\
 Mandelbrot and Frame's (Binary) Fractal Trees.
 See http://www.math.union.edu/research/fractaltrees/
"""

import os
from math import sin,cos,pi

def ftree(iter,origin,t,r,theta,dtheta):
    """\
    def ftree(iter,origin,t,r,theta,dtheta):

    Extend the fractal tree one iteration.
    iter:     The iteration number (we stop when iter == 0)
    origin:   The x,y coordinates of the start of this branch
    t:        The current trunk length
    r:        The amount to contract the trunk each iteration
    theta:    The current orientation
    dtheta:   The angle of the branch
    """
    if iter == 0: return []
    x0,y0 = origin
    x,y = x0+t*cos(theta),y0+t*sin(theta)
    lines = [((x0,y0),(x,y))]
    lines.extend(ftree(iter-1,(x,y),t*r,r,theta+dtheta,dtheta))
    lines.extend(ftree(iter-1,(x,y),t*r,r,theta-dtheta,dtheta))
    return lines

def pil_render_lines(lines,height=300,width=300,fname="bs.png"):
    import Image,ImageDraw
    img = Image.new("RGB",(width,height),(255,255,255))
    draw = ImageDraw.Draw(img)
    for line in lines: draw.line(line,(0,0,0))
    img.save(fname,"PNG")
    #os.system("display %s" % fname) # use ImageMagick to display
    return

def main():
    # Here we choose initial values. These work fairly well.
    # See ftree.__doc__ for details
    t = 100
    r = 0.6
    ang2rad = pi/180.
    theta = 90.0*ang2rad
    dtheta = 60.0*ang2rad
    lines = ftree(8,(150,0),t,r,theta,dtheta)
    pil_render_lines(lines)
    return

if __name__ == '__main__': main()

While putting up the Christmas tree this year I was reminded by these pretty little trees; Frame's web site at http://www.math.union.edu/research/fractaltrees has more analysis of their properties. There are even prettier forms, see, for example http://pyx.sourceforge.net/examples/path/index.html. But this does the simplest type, and is still fun to play with.

There would be lots of fun things to implement along these lines even if you don't want to go to the general tree like the pyx people do. Should be fairly easy to have different contractions/angles for the left and right branches, and to see how this affects the tree growth. And it would be really cool to figure out a way to do this in 3D.