L-systems: Growing Natural Forms with Recursive Grammar

L-systems (Lindenmayer systems) are formal grammars used to model the growth processes of plant development. By applying simple rewrite rules recursively, you can generate incredibly complex and natural-looking structures - from fern fronds to tree branches to seashell spirals.

What Are L-systems?

L-systems consist of:

The key insight: L-systems use context-free grammars, meaning each replacement happens simultaneously without considering neighboring symbols. This creates parallel growth patterns that naturally emerge from simple local instructions.

Basic Python Implementation

class LSystem:
    def __init__(self, axiom, rules):
        """
        Initialize an L-system.
        
        Args:
            axiom: Starting string (e.g., "F")
            rules: Dictionary mapping symbols to their replacement strings
                   Example: {'F': 'FF+[+F-F]-[-F+F]', '+': '+', '-': '-', 
                          '[': '[', ']': ']'}. Note: '+' and '-' are often
                          not replaced, just used for turtle graphics commands.
        """
        self.axiom = axiom
        self.rules = rules
    
    def iterate(self, steps):
        """Apply production rules iteratively."""
        current = self.axiom
        
        for _ in range(steps):
            new_string = ""
            for symbol in current:
                # If symbol is in rules, replace it; otherwise keep as-is
                if symbol in self.rules:
                    new_string += self.rules[symbol]
                else:
                    new_string += symbol
            current = new_string
        
        return current

# Example: A simple plant-like L-system
plant_rules = {
    'F': 'FF+[+F-F]-[-F+F]',  # Branching with angles
    '+': '+',                  # Angle commands don't change
    '-': '-',
    '[': '[',                 # Save position/angle
    ']': ']'                  # Restore position/angle
}

plant = LSystem('F', plant_rules)
generation_3 = plant.iterate(3)  # "FF+[+F-F]-[-F+F]" -> much longer string

Adding Turtle Graphics Rendering

To visualize L-systems, you need to interpret symbols as turtle graphics commands:

import turtle

def draw_lsystem(lstring, angle=25.0):
    """
    Draw an L-system using turtle graphics.
    
    Args:
        lstring: The fully expanded L-system string
        angle: Angle for +/- commands in degrees
    """
    screen = turtle.Screen()
    screen.setup(800, 600)
    
    t = turtle.Turtle()
    t.speed(0)  # Fastest speed
    
    stack = []  # For branching ([])
    
    for char in lstring:
        if char == 'F':
            t.forward(15)
        elif char == '+':
            t.right(angle)
        elif char == '-':
            t.left(angle)
        elif char == '[':
            # Save state (position, heading, and stack depth)
            t.push()
            stack.append(t.pos())
            stack.append(t.heading())
        elif char == ']':
            # Restore most recent state
            if len(stack) >= 2:
                heading = stack.pop()
                t.setheading(heading)
                pos = stack.pop()
                t.penup()
                t.goto(pos[0], pos[1])
                t.pendown()

# Example usage
lstring = plant.iterate(4)
draw_lsystem(lstring)

Famous L-system Patterns

Here are some classic patterns to experiment with:

Pattern Axiom Rules Description
Fractal Tree F {F: FF+[+F-F]-[-F+F]} Classic branching tree
Sierpinski Triangle --+ {+: ++, -: +-, []: [,-]} (simplified) Triangle pattern
Snowflake (Koch Curve) --X--- {X:+YX+--XY++, Y:-X-Y+-++Y-} Snowflake-like pattern

Varying Parameters for Different Styles

You can create diverse natural forms by adjusting:

# Example with tapering branches and angle variation
def draw_tapered_lsystem(lstring, angle=25.0, initial_length=15):
    length = initial_length
    
    for char in lstring:
        if char == 'F':
            t.forward(length)
            # Taper the branch
            length *= 0.75
        elif char == '+':
            t.right(angle + random.gauss(0, 2))  # Add slight randomness
        elif char == '-':
            t.left(angle + random.gauss(0, 2))

Tips for Better Results

Next Steps for Experimentation

Try exploring:

The beauty of L-systems is that you're essentially writing a "growth algorithm" - giving simple instructions and watching complex, lifelike structures emerge. It's like programming nature itself!