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:
- An alphabet of symbols (axioms and productions)
- Axiom - the starting string
- Production rules that replace each symbol with a string of symbols
- Iterations - applying rules repeatedly to grow the structure
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:
- F: Move forward (draw a line)
- +/-: Turn left/right by an angle (usually 25°)
- []: Save state and push to stack
- ]: Pop state from stack and restore
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:
- Angle size: 20°-35° for tree-like structures; smaller angles (10°-15°) for ferns
- Branch length decay: Multiply forward distance by 0.7-0.9 each iteration to simulate tapering branches
- Rule complexity: More complex rules create denser patterns; simpler rules create sparser structures
- Randomness: Add slight random variations to angles for organic imperfection
# 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
- Start simple: Begin with basic trees, then add complexity
- Iterate gradually: Don't go too many iterations at once - watch how patterns evolve
- Save intermediate states: Record each generation to create animation sequences
- Combine with colors: Map different branches or depths to varying colors for visual depth
- Experiment with angle ranges: Try angles from 15°-40° to find what looks natural
Next Steps for Experimentation
Try exploring:
- Different axiom strings: Try starting with "F", "--+", or longer initial sequences
- Multidimensional L-systems: Extend to 3D for more complex organic structures
- Context-sensitive rules: Modify rules based on neighboring symbols (requires different approach)
- Hybrid systems: Combine L-systems with cellular automata or noise textures
- Animation: Create time-based growth sequences showing evolution from axiom to mature form
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!