Harmony and tuning#

Why twelve notes, and how chords move: stacked fifths that almost close, and walks on the grid of triads. 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])

Why twelve notes?#

The sweetest interval after the octave (2:1) is the pure fifth (3:2). Stack fifths, fold each one back into the octave, and you build scales the way the Pythagoreans did: 5 fifths give a pentatonic scale, 7 a diatonic one. But the circle can never close, because no power of 3/2 is a power of 2. It can only nearly close, when \(n\) fifths are almost \(m\) octaves:

\[ \left(\tfrac{3}{2}\right)^{n} \approx 2^{m} \quad\Longleftrightarrow\quad \frac{m}{n} \approx \log_2 \tfrac{3}{2} = 0.58496\ldots = \cfrac{1}{1 + \cfrac{1}{1 + \cfrac{1}{2 + \cfrac{1}{2 + \cfrac{1}{3 + \cdots}}}}} \]

Cutting that continued fraction off early gives the best such fractions: 1/2, 3/5, 7/12, 24/41, 31/53. Twelve fifths miss seven octaves by the Pythagorean comma,

\[ \frac{(3/2)^{12}}{2^{7}} = \frac{3^{12}}{2^{19}} = 1.01364\ldots \approx 23.5 \ \text{cents, about a quarter of a semitone} \]

and equal temperament hides it by shaving a little off every fifth. After twelve, the next good stopping points are 41 and 53 notes per octave.

You hear the scale you have built, and then the first note together with the last fifth. The closer the circle is to closing, the slower the two notes beat against each other.

Show the code 3 lines
fifths = mo.ui.slider(1, 53, value=12, label="fifths stacked", show_value=True, debounce=True)
tuning_player = Player()
mo.vstack([fifths, mo.ui.anywidget(tuning_player)])
CDEFGABfifth 1fifth 2fifth 3fifth 4fifth 5fifth 6fifth 7fifth 8fifth 9fifth 10fifth 11the starting notefifth 12
startfifthsthe last fifth
12 pure fifths land 23.5 cents above the starting note. A semitone is 100 cents; the small grey ticks are today's 12 equal semitones. Continued fraction of log₂(3/2): 1/2, 3/5, 7/12, 24/41, 31/53. Read 7/12 as: 12 fifths ≈ 7 octaves.
Show the code 51 lines
FIFTH = math.log2(3 / 2)  # a pure fifth as a fraction of an octave: 0.58496...


def convergents(x, count):
    """The best fractions close to x, from its continued fraction."""
    found, (p0, q0, p1, q1) = [], (0, 1, 1, 0)
    for _ in range(count):
        whole = math.floor(x)
        p0, q0, p1, q1 = p1, q1, whole * p1 + p0, whole * q1 + q0
        found.append((p1, q1))
        x = 1 / (x - whole)
    return found


_turns = [(k * FIFTH) % 1 for k in range(fifths.value + 1)]  # each fifth, folded into one octave
_gap = (_turns[-1] + 0.5) % 1 - 0.5  # how far the last one lands from the start, in octaves

# first the scale: every note so far, low to high. Then the start and the last fifth together.
_rising = sorted(_turns[:-1])
_scale = note(steps([12 * turn - 12 for turn in _rising])).s("pluck")
_pair = note(stack(-12, 12 * _gap - 12)).s("sine").gain(0.8)
_bars = math.ceil(fifths.value / 12)

_dots = [(turn, "s1", f"fifth {k}") for k, turn in enumerate(_turns)][1:-1]
_dots += [(0, "ink", "the starting note"), (_turns[-1], "s2", f"fifth {fifths.value}")]
_picture = ring(
    _dots,
    ["C", "", "D", "", "E", "F", "", "G", "", "A", "", "B"],
    key=[("ink", "start"), ("s1", "fifths"), ("s2", "the last fifth")],
    # ring each note of the scale as it sounds, then the start and the last fifth together
    lit=[(k * _bars / len(_rising), (k + 1) * _bars / len(_rising), turn) for k, turn in enumerate(_rising)]
    + [(_bars, _bars + 1, 0), (_bars, _bars + 1, _turns[-1])],
)
tuning_player.load(render(timecat((_bars, _scale), (1, _pair)).slow(_bars + 1), cycles=_bars + 1, cps=0.5), _picture)

mo.hstack(
    [
        _picture,
        mo.md(
            f"**{fifths.value} pure fifths** land {abs(_gap) * 1200:.1f} cents "
            f"{'above' if _gap > 0 else 'below'} the starting note. "
            "A semitone is 100 cents; the small grey ticks are today's 12 equal semitones.\n\n"
            "Continued fraction of log₂(3/2): "
            + ", ".join(f"{p}/{q}" for p, q in convergents(FIFTH, 7)[2:])
            + ". Read 7/12 as: 12 fifths ≈ 7 octaves."
        ).style({"max-width": "440px"}),
    ],
    justify="start",
    align="center",
    gap=2,
)

Walking the Tonnetz#

Write the notes on a triangular grid so that a step to the right is a perfect fifth (7 semitones) and a step up and to the right is a major third (4 semitones):

\[ \text{note}(i, j) = 7i + 4j \pmod{12} \]

Every triangle is then a major or minor chord. Leonhard Euler drew this Tonnetz ("tone net") in 1739; since the 1980s neo-Riemannian theory has used it to study chord progressions.

Flipping a triangle over one of its edges keeps two notes and moves the third by a small step. The three flips are called P, L and R. On a major chord with root \(r\):

\[ \{r,\ r{+}4,\ r{+}7\} \ \xrightarrow{\ P\ }\ \{r,\ r{+}3,\ r{+}7\}, \qquad \xrightarrow{\ L\ }\ \{r{-}1,\ r{+}4,\ r{+}7\}, \qquad \xrightarrow{\ R\ }\ \{r,\ r{+}4,\ r{+}9\} \]

A chord progression is a walk. Because note names repeat, the grid wraps around into a torus, so walks come home: P and L alternating return after 6 chords, P and R after 8, and R and L only after visiting all 24 major and minor chords. Richard Cohn's analysis of the scherzo of Beethoven's Ninth finds 19 chords in a row along that last path.

The code keeps no table of chords. A chord is a triangle, and the notes are read off its corners.

Show the code 14 lines
preset = mo.ui.dropdown(
    {
        "RL × 9: the scherzo of Beethoven's Ninth": "RL" * 9,
        "RL × 12: all 24 chords": "RL" * 12,
        "PL × 3: home after 6 chords": "PL" * 3,
        "PR × 4: home after 8 chords": "PR" * 4,
        "LPR × 2: six chords around one note": "LPR" * 2,
    },
    value="RL × 9: the scherzo of Beethoven's Ninth",
    label="walk",
)
word = mo.ui.text(placeholder="e.g. PLRLP", label="or type your own, with the letters P, L and R")
tonnetz_player = Player()
mo.vstack([mo.hstack([preset, word], justify="start", gap=1.5, wrap=True), mo.ui.anywidget(tonnetz_player)])
CAmFDmB♭GmE♭CmA♭FmD♭B♭mF♯E♭mBA♭mED♭mACGEAFDB♭GE♭CA♭FD♭B♭F♯E♭BA♭ED♭A
C → Am → F → Dm → B♭ → Gm → E♭ → Cm → A♭ → Fm → D♭ → B♭m → F♯ → E♭m → B → A♭m → E → D♭m → A 19 different chords. The boldest triangle is the start.
Show the code 58 lines
FLIP = {  # which neighbour each letter flips to
    (True, "P"): (0, -1), (True, "R"): (-1, 0), (True, "L"): (0, 0),
    (False, "P"): (0, 1), (False, "R"): (1, 0), (False, "L"): (0, 0),
}  # fmt: skip
NOTES = ["C", "D♭", "D", "E♭", "E", "F", "F♯", "G", "A♭", "A", "B♭", "B"]


def pitch(i, j):
    """The note at a grid point: a step right is a fifth (7 semitones), a step up-right a major third (4)."""
    return (7 * i + 4 * j) % 12


def corners(up, i, j):
    return [(i, j), (i + 1, j), (i, j + 1)] if up else [(i + 1, j), (i, j + 1), (i + 1, j + 1)]


def walk(letters):
    """Start on C major and flip once per letter."""
    up, i, j = True, 0, 0
    path = [(up, i, j)]
    for letter in letters:
        di, dj = FLIP[up, letter]
        up, i, j = not up, i + di, j + dj
        path.append((up, i, j))
    return path


_letters = [c for c in (word.value or preset.value).upper() if c in "PLR"][:48]
_path = walk(_letters)
_chords = [sorted(pitch(*corner) for corner in corners(*triangle)) for triangle in _path]
_names = [NOTES[pitch(i, j)] if up else NOTES[pitch(i, j + 1)] + "m" for up, i, j in _path]
_roots = [pitch(i, j) if up else pitch(i, j + 1) for up, i, j in _path]

_cycles = math.ceil(len(_chords) / 2)
_harmony = stack(
    note(steps([stack(*chord) for chord in _chords])).s("superpiano").room(0.3),
    note(steps([root - 24 for root in _roots])).s("bass").gain(0.9),
).slow(_cycles)

_picture = lattice(
    [(corners(*triangle), name) for triangle, name in zip(_path, _names)],
    {corner: NOTES[pitch(*corner)] for triangle in _path for corner in corners(*triangle)},
    each=_cycles / len(_chords),  # how long each chord lasts, in cycles
)
tonnetz_player.load(render(_harmony, cycles=_cycles, cps=0.5), _picture)

_home = _chords[-1] == _chords[0] and len(_chords) > 1
mo.vstack(
    [
        _picture,
        mo.md(
            " → ".join(_names)
            + f"\n\n{len(set(_names))} different chords"
            + (", and the walk ends where it began." if _home else ".")
            + " The boldest triangle is the start."
        ),
    ]
)

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.