Chaos and noise#

Melodies from dynamical systems and from noise: the logistic map, a picture-making map of the plane, and the statistics of music itself. 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])

Chaos you can dial in#

The logistic map takes a number \(x\) between 0 and 1 and replaces it, over and over, with

\[ x_{n+1} = r \, x_n \, (1 - x_n) \]

For small \(r\) the numbers settle on one value. Turn \(r\) up and they alternate between two values, then four, then eight, and beyond about 3.57 they never settle at all, apart from islands of order (try 3.83). Jeff Pressing's Nonlinear Maps as Generators of Musical Design (1988) used maps like this to compose.

Each number becomes a note of a scale, so the picture and the melody are the same thing. Drag the orange line across the plot while it plays (or click anywhere on it): the dots show the new melody at once, and you hear it from the next loop.

Show the code 3 lines
r_picker = mo.ui.anywidget(LogisticPicker(settled, r=3.5))
chaos_player = Player()
mo.vstack([r_picker, mo.ui.anywidget(chaos_player)])
Show the code 8 lines
_r = np.linspace(2.8, 4.0, 240)
_x = np.full_like(_r, 0.3)
for _ in range(400):  # let them settle
    _x = _r * _x * (1 - _x)
settled = []
for _ in range(48):  # then keep 48 values each
    _x = _r * _x * (1 - _x)
    settled += zip(_r.tolist(), _x.tolist())
Show the code 31 lines
_r = r_picker.value["r"]
_x, _orbit = 0.3, []
for _ in range(300 + 32):
    _x = _r * _x * (1 - _x)
    _orbit.append(_x)
_orbit = _orbit[-32:]  # skip the run-in and keep where it ends up

# 0..1 becomes three octaves of a seven-note scale
_tune = n(scale("dorian", steps([int(x * 21) for x in _orbit])) - 12).s("pluck").slow(2)

# the cursor rings each dot on the plot as its note plays: 16 notes per cycle
chaos_player.load(
    render(stack(_tune, s("bd*4").gain(0.7)), cycles=2, cps=0.5),
    r_picker.widget.picture(_orbit, each=1 / 16),
)

_period = next(
    (p for p in (1, 2, 4, 8, 16, 3, 6, 12, 5, 10) if all(abs(a - b) < 1e-4 for a, b in zip(_orbit, _orbit[p:]))),
    None,
)
mo.md(
    f"**r = {_r:g}:** "
    + (
        "the melody never repeats."
        if _period is None
        else "one note, over and over."
        if _period == 1
        else f"the melody repeats every {_period} notes."
    )
    + " Grey: where the map settles for each r. Orange: the line you drag, and the notes you hear."
)

Orbits on a loop: Simone Conradi's map#

The physicist Simone Conradi draws with dynamical systems in Python (@S_Conradi, notebooks). One of the best known of those pictures comes from a map of the plane that fits on one line:

\[ x_{n+1} = \sin\!\big(x_n^2 - y_n^2 + a\big), \qquad y_{n+1} = \cos\!\big(2\,x_n y_n + b\big) \]

The two arguments are the real and imaginary parts of \((x + iy)^2\), so this is a cousin of the map \(z \to z^2 + c\) behind Julia sets. Take thousands of starting points, apply the map over and over, and mark everywhere they land: the folds and spirals appear by themselves. Paul Bourke catalogued it as the Simone attractor.

Let \(a\) and \(b\) drift and the picture breathes. Here they walk once round a circle, one step per bar,

\[ a_k = a + \rho \cos\frac{2\pi k}{8}, \qquad b_k = b + \rho \sin\frac{2\pi k}{8}, \qquad k = 0, \dots, 7 \]

so after eight bars picture and music are back where they began: a loop.

In every picture one starting point is followed for 16 steps (the orange dots), and those 16 points are the bar's melody. The higher the point, the higher the note; the further right, the further right in your headphones. Where the path spirals into a bright spot, the tune settles on one note.

Show the code 12 lines
orbit_a = mo.ui.slider(0, 6.28, step=0.01, value=5.46, label="a", show_value=True, debounce=True)
orbit_b = mo.ui.slider(0, 6.28, step=0.01, value=4.55, label="b", show_value=True, debounce=True)
orbit_radius = mo.ui.slider(
    0, 1, step=0.05, value=0.4, label="ρ, the size of the loop", show_value=True, debounce=True
)
orbit_player = Player()
mo.vstack(
    [
        mo.hstack([orbit_a, orbit_b, orbit_radius], justify="start", gap=1.5, wrap=True),
        mo.ui.anywidget(orbit_player),
    ]
)
picture 1, step 1picture 1, step 2picture 1, step 3picture 1, step 4picture 1, step 5picture 1, step 6picture 1, step 7picture 1, step 8picture 1, step 9picture 1, step 10picture 1, step 11picture 1, step 12picture 1, step 13picture 1, step 14picture 1, step 15picture 1, step 161picture 2, step 1picture 2, step 2picture 2, step 3picture 2, step 4picture 2, step 5picture 2, step 6picture 2, step 7picture 2, step 8picture 2, step 9picture 2, step 10picture 2, step 11picture 2, step 12picture 2, step 13picture 2, step 14picture 2, step 15picture 2, step 162picture 3, step 1picture 3, step 2picture 3, step 3picture 3, step 4picture 3, step 5picture 3, step 6picture 3, step 7picture 3, step 8picture 3, step 9picture 3, step 10picture 3, step 11picture 3, step 12picture 3, step 13picture 3, step 14picture 3, step 15picture 3, step 163picture 4, step 1picture 4, step 2picture 4, step 3picture 4, step 4picture 4, step 5picture 4, step 6picture 4, step 7picture 4, step 8picture 4, step 9picture 4, step 10picture 4, step 11picture 4, step 12picture 4, step 13picture 4, step 14picture 4, step 15picture 4, step 164picture 5, step 1picture 5, step 2picture 5, step 3picture 5, step 4picture 5, step 5picture 5, step 6picture 5, step 7picture 5, step 8picture 5, step 9picture 5, step 10picture 5, step 11picture 5, step 12picture 5, step 13picture 5, step 14picture 5, step 15picture 5, step 165picture 6, step 1picture 6, step 2picture 6, step 3picture 6, step 4picture 6, step 5picture 6, step 6picture 6, step 7picture 6, step 8picture 6, step 9picture 6, step 10picture 6, step 11picture 6, step 12picture 6, step 13picture 6, step 14picture 6, step 15picture 6, step 166picture 7, step 1picture 7, step 2picture 7, step 3picture 7, step 4picture 7, step 5picture 7, step 6picture 7, step 7picture 7, step 8picture 7, step 9picture 7, step 10picture 7, step 11picture 7, step 12picture 7, step 13picture 7, step 14picture 7, step 15picture 7, step 167picture 8, step 1picture 8, step 2picture 8, step 3picture 8, step 4picture 8, step 5picture 8, step 6picture 8, step 7picture 8, step 8picture 8, step 9picture 8, step 10picture 8, step 11picture 8, step 12picture 8, step 13picture 8, step 14picture 8, step 15picture 8, step 168
Read the pictures like a comic strip, left to right and top to bottom: one per bar. Blue: where the 30,000 points go. Orange: the one point you hear, 16 steps of it.
Show the code 42 lines
def conradi(a, b, x, y, count):
    """Simone Conradi's map, applied `count` times. x and y can be single numbers or whole arrays of points."""
    visited = []
    for _ in range(count):
        x, y = np.sin(x * x - y * y + a), np.cos(2 * x * y + b)
        visited.append((x, y))
    return visited


# eight bars: (a, b) walks once round a circle, so the last bar leads back into the first
_loop = [
    (orbit_a.value + orbit_radius.value * math.cos(angle), orbit_b.value + orbit_radius.value * math.sin(angle))
    for angle in np.linspace(0, 2 * math.pi, 8, endpoint=False)
]

# the pictures: where 30,000 random starting points go in 50 steps
_crowd = np.random.default_rng(0).uniform(-1, 1, (2, 30_000))
_pictures = [ink(conradi(a, b, *_crowd, count=50)) for a, b in _loop]

# the melodies: where one starting point goes in 16 steps
_paths = [[(float(x), float(y)) for x, y in conradi(a, b, -0.6, 0.8, count=16)] for a, b in _loop]
_tune = slowcat(
    *[
        n(scale("dorian", steps([round(7 * (y + 1)) for _, y in path])) - 12)  # height is pitch
        .s("pluck")
        .pan(steps([(x + 1) / 2 for x, _ in path]))  # left and right are left and right
        for path in _paths
    ]
).room(0.3)

_picture = tiles(_pictures, _paths, each=1)  # one picture per cycle
orbit_player.load(render(stack(_tune, s("bd*2").gain(0.6)), cycles=8, cps=0.5), _picture)

mo.vstack(
    [
        _picture,
        mo.md(
            "Read the pictures like a comic strip, left to right and top to bottom: one per bar. "
            "Blue: where the 30,000 points go. Orange: the one point you hear, 16 steps of it."
        ),
    ]
)

Neither random nor predictable: 1/f music#

In 1975 Richard Voss and John Clarke measured how pitch and loudness wander in recordings, from Bach to rock radio, and found the same statistics everywhere. The power of the wandering at frequency \(f\) falls off as

\[ S(f) \propto \frac{1}{f^{\beta}}: \qquad \beta = 0 \ \text{(white)}, \qquad \beta = 1 \ \text{(pink, or } 1/f\text{)}, \qquad \beta = 2 \ \text{(brown)} \]

and music is pink. In white noise every note is a fresh roll of the dice, with no memory. In brown noise every note is a small step from the last one, with too much memory. Pink sits in between.

Voss's recipe for pink, which Martin Gardner made famous in Scientific American in 1978, uses several dice \(d_0, d_1, d_2, \dots\) Die \(d_k\) is re-rolled only every \(2^k\) notes, and note number \(i\) is their sum,

\[ \text{note}_i = \sum_{k=0}^{4} d_k\big(\lfloor i / 2^k \rfloor\big) \]

so it has surprises at every time scale. Compare the three.

Show the code 4 lines
colour = mo.ui.radio(["white", "pink (1/f)", "brown"], value="pink (1/f)", inline=True)
reroll = mo.ui.button(value=0, on_click=lambda count: count + 1, label="🎲 roll again")
noise_player = Player()
mo.vstack([mo.hstack([colour, reroll], justify="start", gap=1.5), mo.ui.anywidget(noise_player)])
162note 0: 11note 1: 7note 2: 4note 3: 4note 4: 13note 5: 11note 6: 13note 7: 13note 8: 12note 9: 10note 10: 14note 11: 10note 12: 12note 13: 11note 14: 13note 15: 14note 16: 6note 17: 6note 18: 9note 19: 10note 20: 4note 21: 2note 22: 5note 23: 7note 24: 12note 25: 10note 26: 14note 27: 16note 28: 13note 29: 13note 30: 15note 31: 15note 32: 10note 33: 10note 34: 12note 35: 9note 36: 7note 37: 9note 38: 8note 39: 8note 40: 10note 41: 9note 42: 11note 43: 12note 44: 10note 45: 9note 46: 12note 47: 12note 48: 7note 49: 7note 50: 9note 51: 8note 52: 5note 53: 8note 54: 3note 55: 6note 56: 7note 57: 8note 58: 11note 59: 10note 60: 8note 61: 9note 62: 10note 63: 8
64 notes of pink noise, as steps of a pentatonic scale.
Show the code 33 lines
def white(count, rng):
    """No memory: every note is a fresh roll."""
    return [int(value) for value in rng.integers(0, 21, count)]


def brown(count, rng):
    """Too much memory: every note is a small step from the last."""
    level, notes = 10, []
    for _ in range(count):
        level = min(20, max(0, level + int(rng.integers(-2, 3))))
        notes.append(level)
    return notes


def pink(count, rng, dice=5):
    """Voss's dice: die k is re-rolled every 2**k notes, and the note is the sum of the dice."""
    faces, notes = [0] * dice, []
    for i in range(count):
        for k in range(dice):
            if i % 2**k == 0:
                faces[k] = int(rng.integers(0, 5))
        notes.append(sum(faces))
    return notes


_make = {"white": white, "pink (1/f)": pink, "brown": brown}[colour.value]
_notes = _make(64, np.random.default_rng(reroll.value))

_tune = n(scale("majpent", steps(_notes)) - 24).s("pluck").room(0.3).slow(4)
_picture = curve(_notes, span=(0, 4))
noise_player.load(render(_tune, cycles=4, cps=0.5), _picture)

mo.vstack([_picture, mo.md(f"64 notes of {colour.value.split()[0]} noise, as steps of a pentatonic scale.")])

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.