Melody and structure#

Four ways to get a melody from a rule: set algebra, a self-similar series, a herd of cows and the permutations of church bells. 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])

Xenakis' sieves: scales by set algebra#

Iannis Xenakis built scales from what he called sieves. The building block is a residue class, every \(a\)-th point of a line starting at \(i\),

\[ a_i = \{\, x : x \equiv i \pmod a \,\} \]

and classes are combined with union \(\cup\), intersection \(\cap\) and complement. If the points are semitones, a sieve is a scale. Unlike the scales we are used to, it need not repeat at the octave: two classes together repeat every \(\operatorname{lcm}(a, b)\) semitones. Xenakis' own example is the major scale, written with the moduli 3 and 4 only:

\[ (\overline{3_2} \cap 4_0) \ \cup\ (\overline{3_1} \cap 4_1) \ \cup\ (3_2 \cap 4_2) \ \cup\ (\overline{3_0} \cap 4_3) \]

Python's sets already have the operators. The run below plays three octaves; the row of octave marks shows how the sieve drifts against them.

Show the code 20 lines
sieve_a = mo.ui.slider(2, 9, value=3, label="every a-th", show_value=True)
sieve_b = mo.ui.slider(2, 9, value=5, label="every b-th", show_value=True)
sieve_shift = mo.ui.slider(0, 8, value=1, label="b starts at", show_value=True)
sieve_op = mo.ui.dropdown(
    {
        "∪  in either": set.union,
        "∩  in both": set.intersection,
        "∖  in a but not b": set.difference,
        "△  in exactly one": set.symmetric_difference,
    },
    value="∪  in either",
    label="combine",
)
sieve_player = Player()
mo.vstack(
    [
        mo.hstack([sieve_a, sieve_b, sieve_shift, sieve_op], justify="start", gap=1.5, wrap=True),
        mo.ui.anywidget(sieve_player),
    ]
)
abthe sieveoctaves
17 of 36 semitones. The two classes line up again every 15 semitones, so each octave gets different notes.
Show the code 34 lines
def residues(modulus, shift=0, size=36):
    """Every `modulus`-th point starting at `shift`: Xenakis writes it modulus_shift."""
    return {point for point in range(size) if point % modulus == shift % modulus}


_a, _b = residues(sieve_a.value), residues(sieve_b.value, sieve_shift.value)
_sieve = sieve_op.value(_a, _b)
_period = math.lcm(sieve_a.value, sieve_b.value)

# three octaves of semitones, bottom to top; the notes in the sieve sound, the rest are silent
_run = note(steps([point - 12 if point in _sieve else None for point in range(36)])).s("pluck").room(0.3)

_picture = blocks(
    [
        [(1, "s1" if point in _a else None) for point in range(36)],
        [(1, "s2" if point in _b else None) for point in range(36)],
        [(1, "ink" if point in _sieve else None) for point in range(36)],
        [(1, "muted" if point % 12 == 0 else None) for point in range(36)],
    ],
    labels=["a", "b", "the sieve", "octaves"],
    times=[(0, 1)] * 4,
)
sieve_player.load(render(_run, cycles=1, cps=0.2), _picture)

mo.vstack(
    [
        _picture,
        mo.md(
            f"{len(_sieve)} of 36 semitones. The two classes line up again every "
            f"**{_period}** semitones"
            + (", so every octave gets the same notes." if 12 % _period == 0 else ", so each octave gets different notes.")
        ),
    ]
)
Show the code 5 lines
_mod3 = [residues(3, shift, 12) for shift in range(3)]
_mod4 = [residues(4, shift, 12) for shift in range(4)]
major_scale = (_mod4[0] - _mod3[2]) | (_mod4[1] - _mod3[1]) | (_mod4[2] & _mod3[2]) | (_mod4[3] - _mod3[0])
assert major_scale == {0, 2, 4, 5, 7, 9, 11}
mo.md(f"`{sorted(major_scale)}` are the semitones of C D E F G A B.")

The infinity series: a tune that contains itself#

The Danish composer Per Nørgård found his infinity series in 1959 and built pieces such as Voyage into the Golden Screen and his Second Symphony on it. Three short rules define it:

\[ a_0 = 0, \qquad a_{2n} = -a_n, \qquad a_{2n+1} = a_n + 1 \]

It is A004718 in the OEIS, and Shallit and Drexler-Lemire have studied it. Read as steps of a scale, the series is a melody with a strange property, which follows from applying the first rule twice:

\[ a_{4n} = a_n \quad \text{(every fourth note is the tune again)}, \qquad a_{2n} = -a_n \quad \text{(every second note is the tune upside down)} \]

Add either one underneath and listen to them meet. The series' odd and even numbers also spell out the Thue–Morse sequence, which makes a good drum part.

Show the code 12 lines
under = mo.ui.dropdown(
    {
        "nothing": 0,
        "every 4th note: the same tune, 4× slower": 4,
        "every 2nd note: the tune upside down, 2× slower": 2,
    },
    value="every 4th note: the same tune, 4× slower",
    label="underneath",
)
drums = mo.ui.checkbox(value=True, label="Thue–Morse drums")
infinity_player = Player()
mo.vstack([mo.hstack([under, drums], justify="start", gap=1.5), mo.ui.anywidget(infinity_player)])
6-50note 0: 0note 1: 1note 2: -1note 3: 2note 4: 1note 5: 0note 6: -2note 7: 3note 8: -1note 9: 2note 10: 0note 11: 1note 12: 2note 13: -1note 14: -3note 15: 4note 16: 1note 17: 0note 18: -2note 19: 3note 20: 0note 21: 1note 22: -1note 23: 2note 24: -2note 25: 3note 26: 1note 27: 0note 28: 3note 29: -2note 30: -4note 31: 5note 32: -1note 33: 2note 34: 0note 35: 1note 36: 2note 37: -1note 38: -3note 39: 4note 40: 0note 41: 1note 42: -1note 43: 2note 44: 1note 45: 0note 46: -2note 47: 3note 48: 2note 49: -1note 50: -3note 51: 4note 52: -1note 53: 2note 54: 0note 55: 1note 56: -3note 57: 4note 58: 2note 59: -1note 60: 4note 61: -3note 62: -5note 63: 6
The first 64 numbers, as a melody. The dots are the notes the slower voice plays.
Show the code 31 lines
def infinity(count):
    """Per Nørgård's infinity series: a(2n) = -a(n) and a(2n + 1) = a(n) + 1."""
    a = [0]
    for i in range(1, count):
        a.append(-a[i // 2] if i % 2 == 0 else a[i // 2] + 1)
    return a


_a = infinity(64)
assert _a[::4] == _a[:16]  # every 4th note is the tune again
assert _a[::2] == [-x for x in _a[:32]]  # every 2nd note is the tune upside down

_layers = [n(scale("dorian", steps(_a))).s("pluck")]
if under.value:
    _layers.append(n(scale("dorian", steps(_a[:: under.value])) - 12).s("superpiano").gain(0.8))
if drums.value:
    # even numbers get a kick, odd numbers a hi-hat: bd hh hh bd hh bd bd hh ...
    _layers += [hits([x % 2 == 0 for x in _a], "bd").gain(0.8), hits([x % 2 for x in _a], "hh").gain(0.5)]

_picture = curve(_a, marks=range(0, 64, under.value) if under.value else (), span=(0, 4))
infinity_player.load(render(stack(*_layers).slow(4), cycles=4, cps=0.4), _picture)

mo.vstack(
    [
        _picture,
        mo.md(
            "The first 64 numbers, as a melody. "
            + ("The dots are the notes the slower voice plays." if under.value else "")
        ),
    ]
)

Narayana's cows#

In 1356 the Indian mathematician Narayana Pandita asked: a cow has one calf every year, and each calf has a calf of her own every year from her fourth year on. How many animals are there after 20 years? Each year's herd is last year's herd plus the calves of every cow that was alive three years ago:

\[ N_n = N_{n-1} + N_{n-3} \qquad \longrightarrow \qquad 1,\ 1,\ 1,\ 2,\ 3,\ 4,\ 6,\ 9,\ 13,\ 19,\ \dots \]

(A000930.) Tom Johnson turned the problem into Narayana's Cows (1989), which plays the herd year by year: a long note for every cow, a short note for every calf. Writing \(C\) for a cow and \(c_1, c_2, c_3\) for a calf in her first, second and third year, each year rewrites the herd by the rule

\[ C \to C\,c_1, \qquad c_1 \to c_2, \qquad c_2 \to c_3, \qquad c_3 \to C\,c_1 \]

and that rule is the whole composition. The pitches are this notebook's choice, not Johnson's score: each generation sits one step higher, and calves sing an octave above their mothers.

Show the code 3 lines
years = mo.ui.slider(1, 9, value=6, label="years", show_value=True, debounce=True)
cows_player = Player()
mo.vstack([years, mo.ui.anywidget(cows_player)])
year 1year 2year 3year 4year 5year 6
the first cowher daughtersgranddaughtersgreat-granddaughters
Wide blocks are cows, narrow blocks are calves. Herd sizes: 2, 3, 4, 6, 9, 13.
Show the code 51 lines
def next_year(herd):
    """An animal is (age, generation). At age 3, her fourth year, she is a cow and has a calf every year."""
    grown = []
    for age, generation in herd:
        age = min(age + 1, 3)
        grown.append((age, generation))
        if age == 3:
            grown.append((0, generation + 1))
    return grown


_herds = [[(3, 0), (0, 1)]]  # year 1: the first cow and her first calf
for _ in range(years.value - 1):
    _herds.append(next_year(_herds[-1]))

# a cow is a long note and a calf a short one; a breath between years
_score, _when = [], []
for _herd in _herds:
    _begin = sum(length for length, _ in _score)
    for _age, _generation in _herd:
        _degree = _generation if _age == 3 else _generation + 5
        _score.append((2 if _age == 3 else 1, n(scale("minpent", _degree)).s("superpiano")))
    _when.append((_begin / 8, sum(length for length, _ in _score) / 8))  # this year, in cycles
    _score.append((2, silence()))

# 8 beats to a cycle: pad the end so the loop is a whole number of cycles
_beats = sum(length for length, _ in _score)
_cycles = math.ceil(_beats / 8)
if _cycles * 8 > _beats:
    _score.append((_cycles * 8 - _beats, silence()))

_picture = blocks(
    [[(2 if age == 3 else 1, f"s{generation + 1}") for age, generation in herd] for herd in _herds],
    labels=[f"year {year + 1}" for year in range(len(_herds))],
    key=[
        (f"s{g + 1}", name)
        for g, name in enumerate(["the first cow", "her daughters", "granddaughters", "great-granddaughters"])
    ],
    times=_when,
)
cows_player.load(render(timecat(*_score).slow(_cycles), cycles=_cycles, cps=1), _picture)

mo.vstack(
    [
        _picture,
        mo.md(
            "Wide blocks are cows, narrow blocks are calves. "
            f"Herd sizes: {', '.join(str(len(herd)) for herd in _herds)}."
        ),
    ]
)

Change ringing: every order of the bells#

English church bells swing through a full circle and are far too heavy to play tunes on, so since the 1600s ringers have rung permutations instead (change ringing). The rules: start and end with the bells in order from highest to lowest, never repeat a row, and let a bell move at most one place from one row to the next.

Plain Bob Minimus rings all 24 orders of four bells using just three swaps of neighbouring places, \(a = (1\,2)(3\,4)\), \(b = (2\,3)\) and \(c = (3\,4)\):

\[ \big( (ab)^3 \, a \, c \big)^3 = e \]

Three times "\(a\,b\,a\,b\,a\,b\,a\,c\)", and you are back where you started, having passed through every element of the symmetric group \(S_4\) exactly once. In today's words it is a Hamiltonian cycle on a Cayley graph of \(S_4\), worked out by ringers long before group theory had a name. Follow one colour to see a bell weave through the others.

lead 1lead 2lead 3row 1: bell 1 in place 1row 2: bell 1 in place 2row 3: bell 1 in place 3row 4: bell 1 in place 4row 5: bell 1 in place 4row 6: bell 1 in place 3row 7: bell 1 in place 2row 8: bell 1 in place 1row 9: bell 1 in place 1row 10: bell 1 in place 2row 11: bell 1 in place 3row 12: bell 1 in place 4row 13: bell 1 in place 4row 14: bell 1 in place 3row 15: bell 1 in place 2row 16: bell 1 in place 1row 17: bell 1 in place 1row 18: bell 1 in place 2row 19: bell 1 in place 3row 20: bell 1 in place 4row 21: bell 1 in place 4row 22: bell 1 in place 3row 23: bell 1 in place 2row 24: bell 1 in place 1row 25: bell 1 in place 111row 1: bell 2 in place 2row 2: bell 2 in place 1row 3: bell 2 in place 1row 4: bell 2 in place 2row 5: bell 2 in place 3row 6: bell 2 in place 4row 7: bell 2 in place 4row 8: bell 2 in place 3row 9: bell 2 in place 4row 10: bell 2 in place 3row 11: bell 2 in place 2row 12: bell 2 in place 1row 13: bell 2 in place 1row 14: bell 2 in place 2row 15: bell 2 in place 3row 16: bell 2 in place 4row 17: bell 2 in place 3row 18: bell 2 in place 4row 19: bell 2 in place 4row 20: bell 2 in place 3row 21: bell 2 in place 2row 22: bell 2 in place 1row 23: bell 2 in place 1row 24: bell 2 in place 2row 25: bell 2 in place 222row 1: bell 3 in place 3row 2: bell 3 in place 4row 3: bell 3 in place 4row 4: bell 3 in place 3row 5: bell 3 in place 2row 6: bell 3 in place 1row 7: bell 3 in place 1row 8: bell 3 in place 2row 9: bell 3 in place 2row 10: bell 3 in place 1row 11: bell 3 in place 1row 12: bell 3 in place 2row 13: bell 3 in place 3row 14: bell 3 in place 4row 15: bell 3 in place 4row 16: bell 3 in place 3row 17: bell 3 in place 4row 18: bell 3 in place 3row 19: bell 3 in place 2row 20: bell 3 in place 1row 21: bell 3 in place 1row 22: bell 3 in place 2row 23: bell 3 in place 3row 24: bell 3 in place 4row 25: bell 3 in place 333row 1: bell 4 in place 4row 2: bell 4 in place 3row 3: bell 4 in place 2row 4: bell 4 in place 1row 5: bell 4 in place 1row 6: bell 4 in place 2row 7: bell 4 in place 3row 8: bell 4 in place 4row 9: bell 4 in place 3row 10: bell 4 in place 4row 11: bell 4 in place 4row 12: bell 4 in place 3row 13: bell 4 in place 2row 14: bell 4 in place 1row 15: bell 4 in place 1row 16: bell 4 in place 2row 17: bell 4 in place 2row 18: bell 4 in place 1row 19: bell 4 in place 1row 20: bell 4 in place 2row 21: bell 4 in place 3row 22: bell 4 in place 4row 23: bell 4 in place 4row 24: bell 4 in place 3row 25: bell 4 in place 444
Rows run left to right; the top line is the first place in the row. Bell 1 is the highest note.
Show the code 32 lines
def plain_bob_minimus():
    """All 24 orders of four bells. Every change swaps neighbours only."""
    cross = lambda row: [row[1], row[0], row[3], row[2]]  # a: both pairs swap
    inside = lambda row: [row[0], row[2], row[1], row[3]]  # b: the middle pair swaps
    behind = lambda row: [row[0], row[1], row[3], row[2]]  # c: the back pair swaps
    row, rows = [1, 2, 3, 4], []
    for lead in range(3):
        for change in [cross, inside] * 3 + [cross, behind]:
            rows.append(row)
            row = change(row)
    return rows


bell_rows = plain_bob_minimus()
assert len({tuple(row) for row in bell_rows}) == 24  # every order, exactly once

# two rows per cycle and then a pause, as ringers do; bell 1 is the highest
_peal = slowcat(
    *[
        n(scale("major", steps([4 - bell for bell in bell_rows[i] + bell_rows[i + 1]] + [None])))
        for i in range(0, 24, 2)
    ]
).s("superpiano").room(0.3)

_picture = braid(bell_rows + [bell_rows[0]], lead=8, per_cycle=2, rests=1)
mo.vstack(
    [
        _picture,
        mo.md("Rows run left to right; the top line is the first place in the row. Bell 1 is the highest note."),
        play(_peal, cycles=12, cps=0.6, picture=_picture),
    ]
)

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.