Rhythm#

Five rhythms that come from a piece of math. Each one has its formula, the few lines of Python that turn it into a pattern, and a picture whose cursor moves with the sound. Press ▶ Play and watch the picture. Then move the controls: the sound changes on the next loop. Each example's code is folded away under it: open Show the code to read or change it.

Show the setup code 18 lines
import math
from itertools import combinations

import marimo as mo
import numpy as np
from eddy import n, note, s, scale, sequence, silence, slowcat, stack, timecat
from eddy.euclid import bjorklund
from eddy.marimo import Picture, Player, cursor, play, render


def hits(bits, sound):
    """A row of 0s and 1s as a rhythm: `sound` on every 1, a rest on every 0."""
    return s(" ".join(sound if bit else "~" for bit in bits))


def steps(values):
    """A list of numbers as equal steps, for `note(...)` or `scale(...)`. None is a rest."""
    return sequence(*["~" if value is None else value for value in values])

One algorithm, a rhythm and a scale#

Euclid's algorithm for the greatest common divisor, run on hits and steps, spreads \(k\) hits over \(n\) steps as evenly as it can. Up to a rotation, hit number \(i\) lands on step

\[ h_i = \left\lfloor \frac{i \cdot n}{k} \right\rfloor, \qquad i = 0, 1, \dots, k - 1 \]

Godfried Toussaint showed in 2005 that this generates a large family of traditional rhythms; it is the "bd(3,8)" of eddy's mini-notation. Music theorists had met the same shapes in pitch: Clough and Douthett's maximally even sets (1991) are the scales that spread their notes as evenly as possible over the 12 semitones.

So one function gives both. Spread 7 over 12 and read the slots as time: a West African bell pattern. Read the same slots as semitones: a diatonic scale. Below you hear both at once, the scale climbing in its own rhythm, while the hand goes round the circle once per bar.

Show the code 3 lines
euclid_hits = mo.ui.slider(1, 11, value=7, label="hits out of 12", show_value=True)
euclid_player = Player()
mo.vstack([euclid_hits, mo.ui.anywidget(euclid_player)])
CD♭DE♭EFF♯GA♭AB♭BCDE♭FGA♭B♭
7 of 12, as even as they can be: x . x x . x . x x . x . Clockwise from the top, the circle is one bar of 12 steps. It is also one octave of 12 semitones, and read that way the dots are a diatonic scale (the shape of the piano's white keys).
Show the code 38 lines
_bits = bjorklund(euclid_hits.value, 12)  # 7 hits: [1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0]

# the 12 slots as time: a bell pattern
_bell = hits(_bits, "cb").gain(0.6)
# the 12 slots as semitones: a scale, each note played at its own slot
_climb = note(steps([i if bit else None for i, bit in enumerate(_bits)])).s("pluck")

_names = ["C", "D♭", "D", "E♭", "E", "F", "F♯", "G", "A♭", "A", "B♭", "B"]
_picture = ring([(i / 12, "s1", _names[i]) for i, bit in enumerate(_bits) if bit], _names, polygon=True, hand=1)
euclid_player.load(render(stack(_bell, _climb, s("bd*4").gain(0.8)), cycles=2, cps=0.5), _picture)

_shapes = {
    1: "a single note",
    2: "a tritone",
    3: "an augmented triad",
    4: "a diminished seventh chord",
    5: "a pentatonic scale (the shape of the piano's black keys)",
    6: "the whole-tone scale",
    7: "a diatonic scale (the shape of the piano's white keys)",
    8: "the octatonic scale",
    9: "Messiaen's third mode",
    10: "Messiaen's seventh mode",
    11: "the chromatic scale with one note missing",
}
mo.hstack(
    [
        _picture,
        mo.md(
            f"**{euclid_hits.value} of 12**, as even as they can be:\n\n"
            f"`{' '.join('x' if bit else '.' for bit in _bits)}`\n\n"
            f"Clockwise from the top, the circle is one bar of 12 steps. It is also one octave "
            f"of 12 semitones, and read that way the dots are {_shapes[euclid_hits.value]}."
        ).style({"max-width": "440px"}),
    ],
    justify="start",
    align="center",
    gap=2,
)

Counting rhythms: Fibonacci before Fibonacci#

How many rhythms fill \(n\) beats, if a syllable is either short (1 beat) or long (2 beats)? Indian scholars of poetry counted them. The idea goes back to Pingala's treatise on Sanskrit metre, and Virahāṅka and Hemachandra (about 1150) spelled out the rule: a rhythm of \(n\) beats is a rhythm of \(n - 1\) beats plus a short syllable, or one of \(n - 2\) beats plus a long one.

\[ R(n) = R(n - 1) + R(n - 2), \qquad R(1) = 1, \quad R(2) = 2 \]

So each count is the sum of the two before it, half a century before Fibonacci's rabbits. Rachel Hall's Math for Poets and Drummers tells the story.

The recursion below is that rule, word for word. You hear every rhythm in turn, one row per cycle.

Show the code 3 lines
meter_beats = mo.ui.slider(2, 6, value=5, label="beats", show_value=True, debounce=True)
meter_player = Player()
mo.vstack([meter_beats, mo.ui.anywidget(meter_player)])
long, 2 beatsshort, 1 beat
5 beats can be filled in 8 ways. For 1, 2, 3, … beats the counts are 1, 2, 3, 5, 8, 13, 21, 34, …
Show the code 29 lines
def meters(beats):
    """Every way to fill `beats` with short (1) and long (2) syllables."""
    if beats <= 1:
        return [[1] * beats]
    return [[1, *rest] for rest in meters(beats - 1)] + [[2, *rest] for rest in meters(beats - 2)]


_all = meters(meter_beats.value)

# one rhythm per cycle: a low tom for a long syllable, a high tom for a short one
_bars = [timecat(*[(length, s("lt" if length == 2 else "ht")) for length in meter]) for meter in _all]

_picture = blocks(
    [[(length, "s1" if length == 2 else "s2") for length in meter] for meter in _all],
    key=[("s1", "long, 2 beats"), ("s2", "short, 1 beat")],
    times=[(row, row + 1) for row in range(len(_all))],  # row k sounds during cycle k
)
meter_player.load(render(slowcat(*_bars), cycles=len(_all), cps=4 / meter_beats.value), _picture)

_counts = [len(meters(beats)) for beats in range(1, 9)]
mo.vstack(
    [
        _picture,
        mo.md(
            f"**{meter_beats.value} beats can be filled in {len(_all)} ways.** "
            f"For 1, 2, 3, … beats the counts are {', '.join(map(str, _counts))}, …"
        ),
    ]
)

The Rhythmicon: harmony, slowed down#

The composer Henry Cowell argued in New Musical Resources (1930) that rhythm and harmony are the same ratios at different speeds: "three against two" is a perfect fifth (3:2) slowed down until you can count it. In 1931 Leon Theremin built him the Rhythmicon, often called the first drum machine. Its keys play the harmonic series of one note, and the \(k\)-th harmonic pulses \(k\) times per cycle:

\[ f_k = k \cdot f_1, \qquad \text{pitch}_k = 12 \log_2 k \ \text{semitones above the first}, \qquad \text{pulse}_k = k \ \text{per cycle} \]

In eddy that is one list comprehension. Note that the pitches are not whole numbers of semitones.

Show the code 3 lines
harmonics = mo.ui.slider(1, 12, value=6, label="harmonics", show_value=True)
rhythmicon_player = Player()
mo.vstack([harmonics, mo.ui.anywidget(rhythmicon_player)])
1×harmonic 1: 1 times per cycle2×harmonic 2: 2 times per cycleharmonic 2: 2 times per cycle3×harmonic 3: 3 times per cycleharmonic 3: 3 times per cycleharmonic 3: 3 times per cycle4×harmonic 4: 4 times per cycleharmonic 4: 4 times per cycleharmonic 4: 4 times per cycleharmonic 4: 4 times per cycle5×harmonic 5: 5 times per cycleharmonic 5: 5 times per cycleharmonic 5: 5 times per cycleharmonic 5: 5 times per cycleharmonic 5: 5 times per cycle6×harmonic 6: 6 times per cycleharmonic 6: 6 times per cycleharmonic 6: 6 times per cycleharmonic 6: 6 times per cycleharmonic 6: 6 times per cycleharmonic 6: 6 times per cycle
Any two rows are a polyrhythm and, as pitches, an interval: 2 and 1 an octave, 3 and 2 a fifth, 4 and 3 a fourth, 5 and 4 a major third.
Show the code 26 lines
_voices = [
    note(12 * math.log2(k) - 12)  # harmonic k of a low C ...
    .s("pluck")
    .fast(k)  # ... k times per cycle
    .gain(1 / math.sqrt(k))
    .pan(0.2 + 0.6 * (k % 2))
    for k in range(1, harmonics.value + 1)
]

_picture = blocks(
    [[(1 / k, "s1", f"harmonic {k}: {k} times per cycle")] * k for k in range(1, harmonics.value + 1)],
    labels=[f"{k}×" for k in range(1, harmonics.value + 1)],
    unit=540,
    times=[(0, 1)] * harmonics.value,  # every row spans the one cycle
)
rhythmicon_player.load(render(stack(*_voices), cycles=1, cps=0.25), _picture)

mo.vstack(
    [
        _picture,
        mo.md(
            "Any two rows are a polyrhythm and, as pitches, an interval: "
            "2 and 1 an octave, 3 and 2 a fifth, 4 and 3 a fourth, 5 and 4 a major third."
        ),
    ]
)

Clapping Music: a rhythm against its own rotations#

Steve Reich's Clapping Music (1972) is one pattern \(a\) of 12 steps. One performer claps it for the whole piece. The other claps the same pattern, but every few bars jumps one step ahead, until twelve jumps later the two are together again. After \(k\) jumps the second part, and the number of claps that land together, are

\[ b_k(t) = a\big((t + k) \bmod 12\big), \qquad \text{together}(k) = \sum_{t=0}^{11} a(t)\, a\big((t + k) \bmod 12\big) \]

The second part is just the list rotated by \(k\). No rotation equals the original, so all twelve bars sound different. Here each shift lasts one bar (Reich asks for eight or twelve).

shift 0shift 1shift 2shift 3shift 4shift 5shift 6shift 7shift 8shift 9shift 10shift 11shift 12
both claponly the first performeronly the second
Claps that land together, bar by bar: 8, 4, 5, 6, 5, 6, 4, 6, 5, 6, 5, 4, 8.
Show the code 20 lines
clap = [1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0]
shifted = [clap[k % 12 :] + clap[: k % 12] for k in range(13)]  # the second performer, bar by bar

_piece = slowcat(*[stack(hits(clap, "cp").pan(0.2), hits(row, "cp:1").pan(0.8)) for row in shifted])

_colour = {(1, 1): "ink", (1, 0): "s1", (0, 1): "s2", (0, 0): None}
_picture = blocks(
    [[(1, _colour[pair]) for pair in zip(clap, row)] for row in shifted],
    labels=[f"shift {k}" for k in range(13)],
    key=[("ink", "both clap"), ("s1", "only the first performer"), ("s2", "only the second")],
    times=[(k, k + 1) for k in range(13)],
)
_together = [sum(a & b for a, b in zip(clap, row)) for row in shifted]
mo.vstack(
    [
        _picture,
        mo.md(f"Claps that land together, bar by bar: {', '.join(map(str, _together))}."),
        play(_piece, cycles=13, cps=0.5, picture=_picture),
    ]
)

Canons that tile time#

A rhythmic canon is one motif \(A\) played by several voices that enter at the times in a set \(B\). It tiles when every step of the loop is hit by exactly one voice: no gaps and no collisions. In symbols, the loop of 12 steps splits into a direct sum,

\[ A \oplus B = \mathbb{Z}_{12}: \quad \text{every step } t \text{ is } a + b \pmod{12} \text{ for exactly one pair } a \in A,\ b \in B \]

The mathematician Dan Tudor Vuza worked out the theory in 1991, and Tom Johnson composed with it, as he describes in Tiling in My Music.

Python can simply try every set of entry times. Pick a motif: the voices come in one by one, each on its own note, and together they fill all 12 steps.

Show the code 15 lines
canon_motif = mo.ui.dropdown(
    [
        "x x . . . x",
        "x . x . . . . x",
        "x . . . . x . x",
        "x . x . x",
        "x x . x . . x",
        "x . x . . x . x",
        "x x . . . . x x",
    ],
    value="x x . . . x",
    label="motif",
)
canon_player = Player()
mo.vstack([canon_motif, mo.ui.anywidget(canon_player)])
voice 1, enters at 0voice 2, enters at 3voice 3, enters at 6voice 4, enters at 9together
1 way(s) to tile 12 steps with this motif; this is the first. A canon in which neither the motif nor the entries repeat within the loop needs at least 72 steps.
Show the code 43 lines
def tilings(motif, size):
    """Every set of entry times at which copies of `motif` hit each step of the loop exactly once."""
    found = []
    for later in combinations(range(1, size), size // len(motif) - 1):
        entries = (0, *later)
        if sorted((entry + step) % size for entry in entries for step in motif) == list(range(size)):
            found.append(entries)
    return found


_motif = [i for i, mark in enumerate(canon_motif.value.split()) if mark == "x"]
_entries = tilings(_motif, 12)[0]
_voices = [[(step - entry) % 12 in _motif for step in range(12)] for entry in _entries]

# each voice plays the motif on its own note of a chord
_parts = [
    note(steps([tone if on else None for on in voice])).s("pluck").pan(0.2 + 0.2 * v)
    for v, (voice, tone) in enumerate(zip(_voices, [-12, 3, 7, 10]))
]
# the voices enter one by one, then stay together
_canon = slowcat(*[stack(*_parts[: k + 1]) for k in range(len(_parts))], stack(*_parts), stack(*_parts))
_cycles = len(_parts) + 2

_owner = [next(v for v, voice in enumerate(_voices) if voice[step]) for step in range(12)]
_picture = blocks(
    [[(1, f"s{v + 1}" if on else None) for on in voice] for v, voice in enumerate(_voices)]
    + [[(1, f"s{v + 1}") for v in _owner]],
    labels=[f"voice {v + 1}, enters at {entry}" for v, entry in enumerate(_entries)] + ["together"],
    # voice v joins in cycle v; the last row lights up once everyone is in
    times=[[(c, c + 1) for c in range(v, _cycles)] for v in [*range(len(_parts)), len(_parts) - 1]],
)
canon_player.load(render(_canon, cycles=_cycles, cps=0.5), _picture)

mo.vstack(
    [
        _picture,
        mo.md(
            f"{len(tilings(_motif, 12))} way(s) to tile 12 steps with this motif; this is the first. "
            "A canon in which neither the motif nor the entries repeat within the loop needs "
            "[at least 72 steps](https://arxiv.org/abs/1304.6609)."
        ),
    ]
)

eddy is the pattern engine of Vortex, the Python port of TidalCycles, repackaged with a numpy synth. GPL-3.0-or-later. The examples run in your browser with marimo islands and Pyodide.