L-Systems

Published on Sept. 23, 2023 | Tags: math generative art fractals

In this post, I want to talk about L-Systems. These are a mathematical object that allows us to model complex recurring figures, almost fractal like structures, that can be defined very well mathematically. In the end, and what I used them for, was to draw beautiful figures.


So, what are l-systems?


According to Wikipedia:


| An L-system or Lindenmayer system is a parallel rewriting system and a type of formal grammar.


And, indeed, you define an alphabet and some rules, and it produces a new structure based on what level of recursion you want.


I first learned about l-systems thanks to the coding train on YouTube. And after watching the video, I decided to implement my own generator in python.


Find the code here. But basically it boils down to


def fractal(
model: InputModel,
level: int,
sentence: str = "",
) -> str:
sentence = sentence or model.axiom
return (
"".join(
fractal(model, level - 1, model.rules[letter])
if letter in model.alphabet
else letter
for letter in sentence
)
if level > 0
else sentence
)

where the InputModel is


class InputModel(NamedTuple):
alphabet: list[str]
angle: float
axiom: str
constants: list[str]
dist: float
drawingrules: dict[str, str]
rules: dict[str, str]

A holder for the required parts of this to function.


Then, it is just a matter of using every letter of this "sentence" as a drawing rule. For example, going forward, turning right, turning left, going back to a previous position, etc...


All in all, this is super fun to play around. In my repo you will be able to find some examples. However, there are more available elsewhere and should not be hard to find more.


Ferran Jovell