♪Music, Built

Act III · Voices

Part 21 of 68

Form

Foundationsstarts at this level31 min of film14 chaptersprerequisites: Part 14, Part 15, Part 18, Part 20

What holds a long piece of music together, and can a program find it from the sound?

Loop a spoken phrase and it turns into song: repetition is the strongest signal that sound is music, and form is the plan of what comes back. Themes are built as periods, a question answered, or sentences, an idea repeated and broken up. Whole pieces are binary, ternary, rondo, variation, sonata or song, each a different plan of return or transformation; a miniature sonata on the Tune, its second theme the opening inverted, travels from C to G, through A minor, F and D minor, and home. A self-similarity matrix compares every moment with every other, so that repeats show as stripes and sections as blocks, and Foote's novelty curve finds the seams: from sound alone it finds 9 of the sonata's 11 boundaries, but hardly any between variations, which keep their harmony, and it can never see the seam between a passage and its own repeat. Part 14's tunes repeat a four-note figure on 32 notes in a hundred, against 1 when shuffled. A golden-section division turns up by chance one time in six, and the sonata itself divides at 0.625. Listeners hear local structure at once but large-scale tonal closure only in short pieces (Cook 1987). The Tune is heard as a miniature sonata.

What you need. Part 14 for the tunes and repetition; Part 15 for keys and the key finder; Part 18 for cadences; Part 20 for fugue. Cosine similarity, convolution, precision and recall.

Ideas, mathematics and history
phrase, period and sentence; binary, ternary, rondo, variation, sonata; song forms; repetition; self-similarity matrices
What we build, compute and hear
form found from audio; the Tune as a miniature sonata

What you will be able to do

Foundations

  • Recognize a period and a sentence, and the plans of binary, ternary, rondo, variation, sonata and song forms.
  • Read a self-similarity matrix: stripes for returns, blocks for sections.
  • Hear whether a short piece ends in the key it began in.

Full course

  • Compute chroma from notes and from sound, a self-similarity matrix and Foote's novelty curve.
  • Score boundaries by precision, recall and F within a tolerance, and explain what novelty cannot find.
  • Measure repetition against a shuffled control, and the base rate of a 'golden' proportion.

Research

  • Compare the evidence on whether listeners hear large-scale form, and design an experiment that separates memory for themes from memory for keys.
  • Describe annotated corpora of musical structure and why annotators disagree.

Practice

  • Find the sections of a track for editing, remixing or looping, and choose the analysis scale to suit.
  • Plan the returns of a song so that the listener wants them when they come.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Foundations 19 min · Full course 28 min · Research 31 min · Practice 21 min.

  1. 0Say it againFoundations2 min
  2. 1Phrase, period, sentenceFoundations3 min
  3. 2Binary and ternaryFoundations1 min
  4. 3Seeing repetitionFull course3 min
  5. 4Finding the seamsFull course2 min
  6. 5Rondo and variationFoundations2 min
  7. 6Sonata: a drama of keysFoundations3 min
  8. 7Song formsFoundations1 min
  9. 8Form from soundPractice2 min
  10. 9Why so much repetition?Foundations2 min
  11. 10The golden section, testedFull course2 min
  12. 11Must the ending be home?Foundations1 min
  13. 12Frontier: form at scaleResearch3 min
  14. Variation 21, recap and problemsAll tracks3 min

Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · Build the film.

Lecture

The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.

Say it againFoundations2 min

In the mid-1990s the psychologist Diana Deutsch was checking a recording of her own voice, and left one phrase looping. After a few repetitions it was no longer speaking. It was singing. Here is a phrase spoken by this series' narrator, repeated ten times. Listen for the moment it stops being speech.

Repeated speech can begin to sound songlike for some listeners; this synthesized example may vary in effectiveness: the syllables take on pitches, a rhythm, a tune. The altered percept can persist, even when you hear it again inside its original sentence. In 2011 Deutsch and her colleagues showed that repetition alone does it: when the repeats were changed slightly, transposed or jumbled, the effect weakened. Repetition is one important cue to musical organization. Repetition is prominent in many musical traditions, as it also is in some speech and poetry, and this part will measure how much. Form is the plan of what comes back, and when.

This part goes from the small forms to the large. First the phrase, the period and the sentence. Then the forms of whole pieces: binary and ternary, rondo, variation, sonata, and the forms of songs. Along the way it builds a picture in which repetition can be seen, and a program that finds a piece's sections from its sound alone. It measures how much music repeats, and tests a famous claim about proportion. And it ends with the hardest question: does a listener actually hear form?

1Phrase, period, sentenceFoundations3 min

What is the smallest complete thought in music?

Form starts small. In this classical teaching model, a phrase is a musical unit typically articulated by a cadence, the musical equivalent of punctuation. A period is two phrases that answer each other: the first has a weaker close, often on the dominant, a question; the second ends closed, on the tonic, often beginning the same way as the first. A sentence works differently: a short idea, the idea again, and then a quicker continuation that breaks the idea into fragments and drives to the cadence. William Caplin's theory of classical form, from 1998, takes these two as the main ways a theme is built.

Two themes made from the Tune's notes. One is a period, the other a sentence. Which is the period, A or B?

B is the period: its first phrase, C C G G A A G, stops on the dominant chord, open; the second phrase answers and closes on C. That is the Tune's own opening. A is a sentence: the idea C C G G, then the same idea again, then a run down the scale, A G F E D C, to the cadence.

Caplin's theory goes further than names: it says what each part of a theme does, its formal function. In the sentence, the first four bars present: an idea, then the idea again, so the listener learns it. The next bars continue: they break the idea into fragments and speed up the harmony, which signals that something is about to happen. The last bars are cadential: they close. The point is that function is not content. The same four notes could begin a piece or end one; what they do depends on where they are, and listeners hear the difference.

These are schematic eight-bar classical examples; actual themes can be shorter, longer or irregular, built of two and two and four, or four and four. The period works by answer. Often its second phrase starts like the first, so the ear expects the same and gets a different ending; the Tune's opening is a contrasting period, whose answer starts elsewhere. The sentence works by acceleration: the idea, the idea again, then its pieces faster and faster. Beethoven's first piano sonata opens with a textbook sentence. And the two ideas, return and acceleration, scale up: the rest of this part is about how whole pieces return to what they began with.

2Binary and ternaryFoundations1 min

What are the two oldest plans for a whole piece?

One common historical plan for a whole piece has two halves, each played twice. Binary form: repeat the first half, repeat the second. Typically the first half travels from the home key to the dominant, and the second half finds its way back. Nearly every dance in a Baroque suite is built this way. When the second half ends by bringing back the opening, the form is called rounded binary, and it is one historical source of later sonata practices. On the left, a picture of a binary piece on the Tune, which the next chapters will explain: for now, notice the four squares, and how the first two match.

The second plan has three parts. Ternary form: a statement, a contrast, a return. The middle section is usually in another key, often with another character, faster or slower, louder or softer. The da capo aria of Baroque opera is ternary: the singer returns to the first section and ornaments it, to show that it is not the same as before. So is the minuet and trio of the classical symphony. The return is the point. Heard after the contrast, the opening means something it could not mean the first time: it is now a homecoming.

3Seeing repetitionFull course3 min

Can a picture show the form of a piece?

In 1999 Jonathan Foote proposed a picture in which repetition can be seen. Start with the Tune's melody. For every beat, list how much of each of the twelve notes is sounding, a column of twelve numbers. Then compare every beat with every other beat: the two columns' cosine similarity, one if they contain the same notes in the same proportions, zero if they share none. The Tune has beats, so the picture is by , with time running down and across from the top left. The bright diagonal is every beat compared with itself.

Now read it. The Tune has six phrases: A, B, C, C, A, B, with C the middle phrase G G F F E E D, sung twice. Wherever a passage comes back, there is a bright stripe parallel to the diagonal, offset by the time between the two appearances. The pink box is the opening sixteen beats compared with the closing sixteen: a clean stripe, because the end repeats the beginning exactly. The blue box is C against the C straight after it. Once you can read stripes and blocks, the form of a piece can be seen at a glance, and so can every one of the forms in this part.

There is a second way to draw the same numbers. Instead of time against time, plot time across and the lag, how far back you are comparing, down. Now every repeat becomes a horizontal line at its lag: the Tune's return of its opening, thirty-two beats later, is a line at lag thirty-two, starting when the return starts. Lines are easier for a program to find than diagonal stripes, and this time-lag picture is how repetition-based segmenters find the seams that novelty misses: problem four asks you to build one.

The same picture can be made from a recording, with no score at all: cut the sound into frames, measure the energy near each of the twelve notes in every octave, and compare. Here is the Tune with its harmony, on the piano of Part 7, with the picture of its written notes, melody and chords, beside the picture of its sound. The chords make both busier than the melody's alone, and the piano's overtones blur the second, but the same pattern is there.

4Finding the seamsFull course2 min

Where does one section end and the next begin?

In 2000 Foote turned the picture into a program for finding the seams of a piece. Take a small checkerboard and slide it along the bright diagonal. Two of its squares count when the music just before a moment is like itself, and the music just after is like itself. The other two count against, when before and after are alike. Add it up at every moment, and the total can peak where one homogeneous stretch gives way to a different one. The peaks of this novelty curve are the candidate boundaries.

Here is the novelty curve of the Tune, computed from its sound, with a checkerboard four beats on a side. The grey lines are where the Tune's phrases really end; the pink dots are the peaks the program picks.

It finds of the phrase ends within two beats, and adds more, in the middle of phrases where the harmony changes. A checkerboard four beats wide sees the harmony move, not only the phrases end.

The checkerboard width changes which contrasts this detector emphasizes. Narrow, it reports every change of chord. Wide, it smooths those away and responds only to changes that last, the boundaries between larger sections, and on a piece as short as the Tune it finds almost nothing. Form has levels, chord, phrase, section, movement, and a listener, like the program, hears the level they attend to.

5Rondo and variationFoundations2 min

How else can a piece come back to its start?

A piece built on the Tune, about half a minute long. Count how many times you hear the Tune's opening strain.

Three times: A, then a contrasting B in the dominant, A again, then C, the opening of the Ode to Joy in F major, and A once more. A refrain that keeps returning between different episodes is a rondo, the favourite last movement of the classical concerto and sonata.

Their pictures. In the rondo, the refrain lights up a bright block at every return, in a regular lattice: A against A, wherever they fall. The episodes, B and C, are dark against everything but themselves. On the right, a set of variations: the Tune's strain, then with its notes rearranged, then with its rhythm doubled. Because every variation keeps the harmony, the whole picture stays bright, and the boundaries are hard to see at all.

The rondo has relatives. In the Baroque concerto, the orchestra's opening, the ritornello, returns between the soloist's passages, but in different keys each time, and often shortened. Between the returns, the soloist's episodes travel from key to key. In the classical era, the rondo absorbed the sonata's logic: in the sonata-rondo, A B A C A B A, the B section appears first in the dominant and, near the end, at home, exactly like a sonata's second theme. In all of them, the refrain is the anchor and the episodes are the journey.

Variation form keeps the plan of the theme, its phrases and its harmony, and changes what lies on top: the surface of the melody, its rhythm, its mode, its texture. Mozart wrote twelve variations on this very Tune, probably around 1781, which Part 26 will take apart. And this series is itself a set of variations: every part ends with a variation on the Tune, and the ledger records them. So there are two ways to make a long piece from short material: bring it back, as a rondo does, or transform it, as variations do.

6Sonata: a drama of keysFoundations3 min

Why does a sonata go away, and how does it come back?

Sonata form is the plan of most first movements of symphonies, sonatas and quartets from about 1750 to 1900. The exposition states a first theme at home, travels through a transition, and states a second theme in another key, often the dominant in major, or the relative major in minor. The development breaks the themes into fragments and takes them through several keys, then works its way back to the dominant. The recapitulation states both themes again, the second one now in the home key. That is the drama: what was stated away from home must be restated at home. It is rounded binary grown large, with the return in the second half made into an event.

Here is the plan of a miniature sonata built on the Tune, which ends this part as Variation 21. Below the sections, the key that Part 15's key finder hears, eight beats at a time. The first theme is the Tune's opening, in C. The second theme is the same opening turned upside down, in G. The development takes the Tune's first notes through A minor, F major and D minor, and arrives on the dominant. The recapitulation brings both themes back in C. The colours tell the story without a note being heard: home, away, far away, home.

How far does the miniature travel? Its development visits A minor, F major and D minor before the dominant. Ask Part 19's pathfinder: every one of them is a single pivot chord away from C. The miniature never leaves C's neighbourhood. Other developments, including Beethoven’s, may explore more remote tonal regions; in Part 19’s particular pivot graph every key is at most two edges away. Enharmonic changes offer additional routes. A return can suggest homecoming, without a proven proportional law relating feeling to graph distance.

In 2006 James Hepokoski and Warren Darcy described the exposition as a journey with a goal. The transition ends with a pause on the new key's dominant, the medial caesura, a door through which the second theme enters. In the miniature sonata it is the transition's last chord, D major. In this theory, essential expositional closure is the first satisfactory perfect authentic cadence in the secondary-theme zone, with exclusions and exceptions. And the recapitulation must reach the same cadence at home, the moment the whole movement has been heading for. Seen this way, a form is a set of expectations that a composer can meet, delay or defy, and the drama is in which.

7Song formsFoundations1 min

How are songs built?

Songs have forms of their own. A widespread one is strophic: one tune, sung again with new words for each verse, as in most folk songs and hymns. The popular songs of Tin Pan Alley, from the 1920s to the 1950s, were mostly AABA: two statements, a contrasting bridge, and a return, thirty-two bars in all. Rock and pop songs alternate verses, whose words change, with a chorus, whose words typically recur. The chorus is a refrain, and its picture shows it: a lattice of bright blocks, like the rondo's.

One influential form has a characteristic harmonic framework: the twelve-bar blues. Three lines of four bars: four bars of the home chord; two of the subdominant and two of home; then dominant, subdominant, and home. Here it is with the Tune's first notes as a riff.

The form is the progression, repeated as long as the singer has verses, and the melody is free to change every time. Part 38 is about the blues, and Part 39 builds jazz on top of it.

8Form from soundPractice2 min

Can a program find a piece's sections by listening?

Now give the program the whole miniature sonata, about three-quarters of a minute of piano, and nothing else: no score, no bar lines, no idea what a sonata is. Its picture is on the left; its novelty curve, with a checkerboard eight beats wide, on the right. Grey lines mark where the music really changes section; pink dots are where the program thinks it does.

It finds of the boundaries within two beats, with false alarms. Where the music changes key, the change in its notes is large, and the picture shows it plainly.

Run it on every piece in this part, scoring the boundaries it finds by the F-score, which combines how many true boundaries it found with how many of its finds were true. The sonata scores best, because its sections change key. The set of variations scores lowest: every variation keeps the theme's harmony, so in a picture made of notes there is hardly a seam to find, although a listener hears each new variation begin at once. With one of three settings selected on this same collection, the program scores about in a hundred: better than nothing, with no human baseline measured here.

So what does the picture miss? Novelty sees contrast: a change of key, of harmony, of texture. It cannot see a seam between a passage and its own repeat: in A A B B, the two A's join without a change. Finding those needs the stripes, the diagonals, as well as the blocks. Practical systems measure timbre, rhythm and loudness too, and search for stripes and blocks together. And a listener hears a new variation begin by its new figure, a change of surface that a picture made of pitch classes throws away.

9Why so much repetition?Foundations2 min

How much of a tune is a repeat?

How much does music repeat? Take every tune in Part 14's collection and ask, for each note, whether it belongs to a four-note figure, the same intervals and the same rhythm, that the tune has already sung earlier. On average, notes in a hundred do. Permute the same pitch-duration pairs into a random order and the figure, by chance, repeats for about in a hundred. The Tune repeats itself more than most: notes in a hundred, its last two phrases a copy of its first two, and its middle phrase sung twice. Prose that repeated a third of its phrases would be thought broken; music is built that way.

The extremes are telling. The most repetitive tune in the collection is the Tune itself, followed by O Tannenbaum and Amazing Grace. At the other end, tunes never repeat a four-note figure exactly, and one of them is Row, Row, Row Your Boat. That is not a contradiction: a round can repeat between voices even when this within-line metric is low. Its line keeps moving so that, sung against itself, it sounds full; the chosen metric does not measure all its repetition.

Why repeat? Repetition makes a pattern learnable: what was strange at first becomes something the listener can predict, Part 14's statistical learning. Psychologists since Robert Zajonc in 1968 have found that mere exposure makes things liked, up to a point, after which they grow tiresome. And repetition frees attention: once the notes are known, the ear can follow the shape, the words, the dance. In her 2014 book On Repeat, Elizabeth Hellmuth Margulis argues that repetition is what makes sounds feel like music at all, the lesson of this part's opening phrase. And it is how we listen to whole pieces too: most music is heard many times, and a form is partly a plan for a listener who already knows what is coming.

10The golden section, testedFull course2 min

Do composers divide their pieces at 0.618?

A claim about form appears in many books. The golden section divides a whole so that the whole is to the larger part as the larger is to the smaller, which puts the division at 0.618 of the way through. It has been found in Bartók by Ernő Lendvai, in Debussy by Roy Howat, and in Mozart by John Putz, who in 1995 measured Mozart's piano sonatas. In many sonata movements, he found, the development and recapitulation together take up close to 0.618 of the whole. The question a statistician asks is not whether some ratios lie near 0.618. It is how often they would by chance.

Here is the chance. In a piece with two parts, the larger part is almost never less than half the whole, and rarely more than three quarters: for this illustrative null, assume it is uniformly distributed over that range. Call it a hit if it lies within two hundredths of 0.618, a band four hundredths wide. Then chance alone gives a hit times in a hundred, about one piece in six; a simulation of two hundred thousand random divisions agrees. Under this assumed uniform null, the chance of at least one hit increases with the number examined. And this part's own miniature sonata, whose displayed section lengths give an illustrative near match: its development and recapitulation take of the whole. A hit.

The tunes can be tested too. Mark where each tune's highest note first arrives. of the climaxes come in the first half, as Part 14 found: these tunes leap up early and spend the rest coming down. Just fall within two hundredths of 0.618, about the that chance would put there. Proportion matters in music, but this small illustration does not establish intentional golden-section design or refute every published claim; conclusions depend on the null model, chosen landmarks and multiple comparisons.

11Must the ending be home?Foundations1 min

Do listeners hear where a long piece ends up?

Two short pieces built on the Tune. Both begin in C major. Which one ends in the key it began in, A or B?

B. Both pieces move to G in their middle; B comes back and closes in C, while A closes in G, a full cadence in the wrong key. These short examples invite a comparison; responses have not been measured here: A sounds finished, but somewhere else.

But does that hold for a whole movement? In 1987 Nicholas Cook took classical pieces and rewrote their endings to finish in a different key from their beginnings. Music students, and listeners without training, rated how complete and coherent each version sounded. For pieces shorter than about a minute, they preferred the version that ended at home. For longer pieces they showed no reliable preference: in that task, ratings did not reliably favor the original endings; this does not directly prove that tonic memory had vanished. In 1992 Michael Karno and Vladimir Konečni rearranged the sections of a Mozart symphony's first movement, and listeners liked the scrambled versions about as well. So is large-scale form something the ear hears, or something the mind knows from the score and from habit? That is the frontier.

12Frontier: form at scaleResearch3 min

What is known about form, and what is not?

What do listeners hear? Local structure, at once: cadences, phrase ends, a chord out of place, as Part 18 found in the brain's responses. Global structure, weakly: pieces whose sections have been reordered are judged nearly as coherent as the originals. Barbara Tillmann and Emmanuel Bigand, reviewing these experiments, concluded that these tasks often reveal stronger local than global effects, rather than a universal one-minute memory limit. But a returning theme is recognized after minutes, and the recognition is felt. Perhaps form works on listeners through memory for themes, the stripes in the picture, more than through the plan of keys.

The forms of this part are journeys, away and back. Not every tradition plans time that way. In Javanese gamelan, a piece is a cycle marked by the great gong, repeated with layers of elaboration, sped up and slowed down. One common instrumental Hindustani performance sequence grows: a free, unmetred opening, then a pulse, then faster and denser playing, then a composition with drums. A dance-music track is a loop, with layers added and taken away. Form as a cycle, or as a growth, rather than a return: Parts 34, 36 and 40 take these up, and they are a reminder that the self-similarity picture shows any of them.

Machines are measured on the same task as this part's program. In 2011 the SALAMI project published structural annotations by experts for well over a thousand recordings, and segmenters are compared on them every year, both on where the boundaries are and on which sections are the same. One lesson: two expert annotators of the same song often disagree, so evaluation depends on annotation choices; disagreement is not a mathematical ceiling on a score against one reference. For writing music, the 2018 Music Transformer used attention across long spans so that the music it generated would return to its own material. Even so, the long-range plan, the thing this part is about, is still where generated music is weakest.

And the questions now. Which levels of form does a listener actually track, and for how long? Is form a property of the music, of the way it is listened to, or of the analysis? This part's research problem asks for an experiment that separates memory for themes from memory for keys, the two candidates for what holds a long piece together.

Variation 21, recap and problemsAll tracks3 min

Every part ends by doing something to the Tune with what it has built. This part built forms. So the Tune becomes a miniature sonata: its opening as the first theme in C; a transition to G; a second theme that is the opening turned upside down; a development that carries the Tune's first notes through three keys; and a recapitulation that brings both themes home. Listen for the second theme coming back in C.

Row twenty-one of the ledger. seconds. The measurement: the program of chapter eight, listening to the sound alone, found of its section boundaries within two beats.

What did we find? Repetition can make selected speech sound songlike, and form is the plan of what returns. The period works by question and answer, the sentence by an idea repeated and then broken up. The large forms bring material back, or transform it. A self-similarity matrix shows repeats as stripes and sections as blocks, and its novelty curve finds the seams. From sound alone a program found most of the sonata's sections, but hardly any variation's. Tunes repeat a third of their notes against one in a hundred by chance, and our chosen uniform division model gives golden-section hits about one time in six.

Five problems. One to compute, one to prove, one for your ears, one to build, and a research problem, marked with a star. Solutions are in this part's notes. Pause here.

Where does this come back? In analysis, which asks whether form is a grammar. In the classical style, where the sonata is at home, and the Romantic century, which stretched it. In the song, in composing a long piece, and in Part 62, where the segmenter of this part grows up into a structure analyser.

And in practice. Listeners can draw a piece's plan in letters as they hear it. Performers shape the returns, since the second A is not the first. Songwriters decide what comes back, and when the listener will want it. And producers use structure analysis to find the sections of a track.

The books and papers this part follows. The full list, with notes, is in the README.

Where it goes next. Analysis and grammars in Part 22; the classical sonata in Part 26; Romantic forms in Part 27; song forms in Part 40; long-range planning in composing in Part 42; structure analysis by machine in Part 62.

Key results

The part's results in one place, for revision.

Segmenting the sonata from sound\(\displaystyle 9 \text{ of } 11 \text{ boundaries }\allowbreak \text{within }\allowbreak \text{two }\allowbreak \text{beats}; \ F = 0.82\)
Variations\(\displaystyle F \approx 0.14: \ \text{same }\allowbreak \text{harmony, }\allowbreak \text{hardly }\allowbreak \text{a }\allowbreak \text{seam}\)
Repetition\(\displaystyle 32\% \text{ of }\allowbreak \text{notes }\allowbreak \text{in }\allowbreak \text{a }\allowbreak \text{repeated }\allowbreak \text{four-note }\allowbreak \text{figure} \ (\text{shuffled } 1\%)\)
The golden section by chance\(\displaystyle P(|r - 0.618| \le 0.02) = 0.04 / 0.25 = 0.16\)
Novelty\(\displaystyle N(t) = \sum_{i,j} K(i, j) \, S(t + i, t + j), \ K = \text{checkerboard} \times \text{Gaussian}\)

Try it

Lab 21 · Form, measured

Build pieces from a plan of sections, see their self-similarity matrices and novelty curves, score the boundaries a program finds, measure how much a tune repeats itself, test the golden section against chance, and name forms by ear.

Figure produced by Lab 21: Form, measured
Produced by the lab below, seed 0, in 0.3 s.
python -m videos.music.labs 21 needs numpy, scipy, matplotlib · download lab21.py · source on GitHub
plan A A B A C A: section starts (beats)                                         0, 8, 16, 24, 32, 40
where the material changes / where novelty peaks                                 [16, 24, 32, 40] / [4, 12, 18, 24, 30, 36, 44]
boundaries found: precision, recall, F                                           0.43, 0.75, 0.55
the labels the picture gives the sections                                        A A B A C A
Frère Jacques: notes in a repeated four-note figure                              0.31 (shuffled 0.00; corpus average 0.32)
Frère Jacques: its phrases in letters                                            A A B B C C D D
chance of a 'golden' division (larger part uniform on 0.5 to 0.75, within 0.02)  0.162 (formula 0.160)
ear problem, the six plans in the order played (listen first)                    A A B A;  A A B B;  A B A;  A B A C A;  A A B B;  A B A C A

A self-similarity matrix shows returns as stripes and sections as blocks; its novelty curve peaks where the material changes, at a scale set by the checkerboard's width, and cannot see a seam between a passage and its own repeat; tunes repeat themselves far beyond chance; and a golden division turns up about one time in six by accident.
The code (114 lines; it asserts its own result)
"""Lab 21: form computed: self-similarity matrices and novelty curves for plans of your own, boundaries scored,
repetition in a tune against shuffled tunes, the golden section's base rate, and forms named by ear."""

import numpy as np

from videos.coursekit import labs
from explainer.music.monochord import Clip, concat
from explainer.music.monochord import chords as CH
from explainer.music.monochord import form as FM
from explainer.music.monochord import melody as M
from explainer.music.monochord.partkit import organ_tone

TITLE = "Form, measured"
GOAL = ("Build pieces from a plan of sections, see their self-similarity matrices and novelty curves, score the "
        "boundaries a program finds, measure how much a tune repeats itself, test the golden section against chance, "
        "and name forms by ear.")
TASKS = [
    "Write a PLAN of your own from the letters A, B and C (for example A B A C A B A). Which boundaries does the novelty curve find, and which does it miss?",
    "Change WIDTH, the checkerboard's half-width in beats, from 2 to 16. At which width are the section boundaries found best, and why?",
    "Choose a TUNE from Part 14's corpus. How much of it repeats? Is it more or less repetitive than the average?",
]
PLAN = "A A B A C A"
WIDTH = 6
TUNE = "Frère Jacques"
SR = 48_000
CHORDS = {"A": [(60, 64, 67), (65, 69, 72), (67, 71, 74), (60, 64, 67)],      # C F G C
          "B": [(67, 71, 74), (62, 66, 69), (67, 71, 74), (62, 66, 69)],      # G D G D
          "C": [(57, 60, 64), (62, 65, 69), (64, 68, 71), (57, 60, 64)]}      # Am Dm E Am


def plan_notes(plan, beats_per_chord=2):
    ev, t, starts = [], 0.0, []
    for x in plan.split():
        starts.append(t)
        for ch in CHORDS[x]:
            for p in ch:
                ev.append((p, t, float(beats_per_chord)))
            t += beats_per_chord
    return ev, starts, t


def render(ev, beat=0.18):
    T = max(a + d for _, a, d in ev)
    y = np.zeros(int((T * beat + 0.6) * SR))
    for p, a, d in ev:
        tone = organ_tone(CH.hz(p), d * beat, partials=5, rolloff=0.7, decay=1.0)
        i = int(a * beat * SR)
        y[i:i + len(tone)] += tone[: len(y) - i] * 0.3
    return Clip(y, SR).fade(0.01, 0.2).at_level(-20.0)


def run(seed=0):
    rng = np.random.default_rng(seed)
    lab = labs.Lab()

    # 1. a plan: its picture, its novelty, its boundaries
    ev, starts, total = plan_notes(PLAN)
    S = FM.ssm(FM.chroma_notes(ev, step=1.0))
    assert np.allclose(S, S.T) and np.allclose(np.diag(S), 1.0)
    nov = FM.novelty(S, L=WIDTH)
    found = FM.peaks(nov, min_gap=max(2, WIDTH), threshold=0.2)
    names = PLAN.split()
    truth = [int(starts[i]) for i in range(1, len(names)) if names[i] != names[i - 1]]
    sc = FM.boundary_score(found, truth, tol=2)
    lab.row(f"plan {PLAN}: section starts (beats)", ", ".join(str(int(s)) for s in starts))
    lab.row("where the material changes / where novelty peaks", f"{truth} / {found}")
    lab.row("boundaries found: precision, recall, F", f"{sc['precision']:.2f}, {sc['recall']:.2f}, {sc['f']:.2f}")
    lab.row("the labels the picture gives the sections", " ".join(FM.label_sections(S, [int(s) for s in starts[1:]])))

    # 2. repetition in a tune, against shuffled versions of it
    m = [x for x in M.corpus() if x.name == TUNE][0]
    share = FM.repeated_share(m.pitches, m.beats)
    shuf = FM.shuffled_share(m.pitches, m.beats, trials=200)
    allshare = np.mean([FM.repeated_share(x.pitches, x.beats) for x in M.corpus()])
    lab.row(f"{TUNE}: notes in a repeated four-note figure", f"{share:.2f} (shuffled {shuf:.2f}; corpus average {allshare:.2f})")
    lab.row(f"{TUNE}: its phrases in letters", FM.form_letters(m))

    # 3. the golden section against chance
    sim = rng.uniform(0.5, 0.75, size=100_000)
    rate = float(np.mean(np.abs(sim - FM.PHI) <= 0.02))
    lab.row("chance of a 'golden' division (larger part uniform on 0.5 to 0.75, within 0.02)", f"{rate:.3f} (formula {FM.golden_base_rate():.3f})")
    assert abs(rate - FM.golden_base_rate()) < 0.01

    # 4. Problem 3, for the ear: six short forms
    plans = ["A A B B", "A B A", "A B A C A", "A A B A", "A A B B", "A B A C A"]
    order = rng.permutation(len(plans))
    clips, answers = [], []
    for k in order:
        e, _, _ = plan_notes(plans[k], beats_per_chord=1)
        clips.append(render(e))
        answers.append(plans[k])
    lab.audio = concat(clips, gap=1.2)
    lab.row("ear problem, the six plans in the order played (listen first)", ";  ".join(answers))

    fig, (a, b) = labs.figure(2)
    a.imshow(S, cmap="magma", origin="upper")
    for s in starts[1:]:
        a.axhline(s - 0.5, color="w", lw=0.5)
        a.axvline(s - 0.5, color="w", lw=0.5)
    a.set_title(f"Self-similarity of {PLAN}")
    a.set_xlabel("beat")
    a.set_ylabel("beat")
    b.plot(nov, color=labs.GOLD)
    for t in truth:
        b.axvline(t, color="#888", ls="--")
    b.plot(found, [nov[i] for i in found], "o", color="#d66")
    b.set_title(f"Novelty (checkerboard {WIDTH} beats on a side)")
    b.set_xlabel("beat")
    lab.fig = fig
    lab.note = ("A self-similarity matrix shows returns as stripes and sections as blocks; its novelty curve peaks where "
                "the material changes, at a scale set by the checkerboard's width, and cannot see a seam between a "
                "passage and its own repeat; tunes repeat themselves far beyond chance; and a golden division turns up "
                "about one time in six by accident.")
    return lab

Now change it

  1. Write a PLAN of your own from the letters A, B and C (for example A B A C A B A). Which boundaries does the novelty curve find, and which does it miss?
  2. Change WIDTH, the checkerboard's half-width in beats, from 2 to 16. At which width are the section boundaries found best, and why?
  3. Choose a TUNE from Part 14's corpus. How much of it repeats? Is it more or less repetitive than the average?

Problems, with solutions

Try each problem before opening its solution.

  1. Compute. Label the phrases of Ode to Joy (Part 14's version) and say whether its first eight bars are a period or a sentence.

    Solution

    Its four two-bar phrases are A B A B′: E E F G G F E D | C C D E E. D D, then the same again with the ending E. D C C. The first four bars end on D over the dominant (open), the second four on C (closed), and both halves begin alike: a parallel period, the classic case.

  2. Prove. Show that a self-similarity matrix is symmetric with ones on its diagonal, and that a passage repeated after d beats makes a stripe on the d-th diagonal.

    Solution

    S(i, j) is the cosine of the angle between columns i and j, which is symmetric in i and j and equals 1 when i = j (for any non-zero column). If the music from beat a to beat a + L is repeated exactly from beat a + d, columns a + k and a + d + k are equal for k < L, so S(a + k, a + d + k) = 1 along a segment of the d-th diagonal: a bright stripe parallel to the main one, offset by d.

  3. Ear. The lab plays six short forms on the Tune. For each, name the plan: AABB, ABA, ABACA, AABA, or variations.

    Solution

    The lab prints the answers. Count the returns of the opening strain and listen for whether a contrasting section comes back (rondo) or never does (binary); variations keep the harmony and change the surface.

  4. Build. Add a stripe detector to the segmenter, so that it finds the seam between a passage and its own repeat, and score it on this part's pieces.

    Where to look. Smooth the matrix along its diagonals, then look for bright segments on off-diagonals (a time-lag matrix makes them horizontal lines); the start of each segment and the start of its repeat are boundaries. Score with form.boundary_score against all section starts, not only the change boundaries; the binary piece's middle seam (A|A) should appear.

  5. ★ Themes or keys? Design an experiment that measures listeners' memory for themes and for keys separately, over minutes.

    Where the frontier is. Cook's design manipulates the final key; a complementary design manipulates whether the final theme returns, crossing the two, at several piece lengths, with recognition and completeness ratings and with musicians and non-musicians. If the theme manipulation survives at lengths where the key manipulation fades, form works through thematic memory.

Notes and sources

Sources

  • D. Deutsch, T. Henthorn and R. Lapidis, "Illusory transformation from speech to song", JASA 129 (2011).
  • W. E. Caplin, Classical Form (1998); J. Hepokoski and W. Darcy, Elements of Sonata Theory (2006); C. Rosen, Sonata Forms (1980).
  • J. Foote, "Visualizing music and audio using self-similarity", ACM Multimedia (1999); "Automatic audio segmentation using a measure of audio novelty", ICME (2000).
  • E. H. Margulis, On Repeat (2014); R. B. Zajonc, "Attitudinal effects of mere exposure", JPSP 9 (1968).
  • J. Putz, "The golden section and the piano sonatas of Mozart", Mathematics Magazine 68 (1995); E. Lendvai, Béla Bartók: An Analysis of His Music (1971); R. Howat, Debussy in Proportion (1983).
  • N. Cook, "The perception of large-scale tonal closure", Music Perception 5 (1987); M. Karno and V. J. Konečni, "The effects of structural interventions in the first movement of Mozart's Symphony in G minor, K. 550, on aesthetic preference", Music Perception 10 (1992); B. Tillmann and E. Bigand, "The relative importance of local and global structures in music perception", JAAC 62 (2004).
  • J. B. L. Smith, J. A. Burgoyne, I. Fujinaga, D. De Roure and J. S. Downie, "Design and creation of a large-scale database of structural annotations", ISMIR (2011); C.-Z. A. Huang and others, "Music Transformer", ICLR (2019).
  • Part 14 for the tunes; Part 15 for the key finder; Part 7 for the piano.
About this partfrom its README

Part 21 of a sixty-eight-part course in music (see the series plan and the syllabus), the sixth part of Act III. Parts 16 to 20 built music a few bars at a time; this part asks what holds minutes together. It starts from the speech-to-song illusion, teaches the small forms (phrase, period, sentence) and the large ones (binary, ternary, rondo, variation, sonata, song), builds a picture in which repetition can be seen (the self-similarity matrix) and a program that finds a piece's sections from its sound alone (Foote's novelty curve), measures how much tunes repeat themselves, tests the golden-section claims against chance, and ends with the experiments on whether listeners hear large-scale form at all. The form tools are Monochord's (explainer/music/monochord/form.py); the pieces are composed in compute.py from the Tune and played on Part 7's piano; the looped phrase is spoken by the series' own narrator voice. Published findings are the ones listed under Sources.

  • Say it again. Deutsch's discovery (mid-1990s) and her 2011 study; a phrase, "sometimes behave so strangely", spoken by the narrator's voice and repeated ten times, heard; form as the plan of what returns; the plan.
  • 1. Phrase, period, sentence. Cadence and phrase; Caplin's period and sentence (1998); an ear question (which of two themes on the Tune is the period?); the Tune's opening as a contrasting period; Beethoven's first sonata.
  • 2. Binary and ternary. ‖: A :‖: B :‖, rounded binary and the Baroque suite; A B A, the da capo aria and the minuet and trio; their self-similarity pictures.
  • 3. Seeing repetition. Foote's self-similarity matrix (1999): a chroma column per beat, cosine similarity; the Tune (A B C C A B) read as stripes and blocks; the same picture from the sound of the Tune with its harmony, heard.
  • 4. Finding the seams. Foote's checkerboard kernel and novelty curve (2000); on the Tune's sound, 5 of 5 phrase ends found within two beats, with 5 extra peaks at chord changes; the kernel's width sets the scale of form it sees.
  • 5. Rondo and variation. An ear question (how many times does the opening strain return?): A B A C A on the Tune, with B in G and C the opening of Ode to Joy in F, heard; rondo and variation pictures; Mozart's variations on the Tune; this series as a set of variations.
  • 6. Sonata: a drama of keys. Exposition, development, recapitulation; a miniature sonata on the Tune whose second theme is its opening inverted, its keys over time from Part 15's key finder (C, G; A minor, F, D minor, G; C); Hepokoski and Darcy's medial caesura and essential closures (2006).
  • 7. Song forms. Strophic, AABA, verse and chorus (a rondo in disguise), and the twelve-bar blues on the Tune's head, heard.
  • 8. Form from sound. The segmenter on the whole sonata, heard: 9 of its 11 boundaries within two beats, 2 false alarms; on every piece of this part (best of three kernel widths): sonata 82 in a hundred, rondo and ternary 50, verse-chorus 44, AABA 40, binary 17, variations 14; one setting for all, 44; what novelty cannot see (a seam between a passage and its own repeat).
  • 9. Why so much repetition? In Part 14's 54 tunes, 32 notes in a hundred belong to a four-note figure (intervals and rhythm) heard earlier in the same tune, against 1 when the notes are shuffled; the Tune, 64; mere exposure (Zajonc 1968); Margulis's On Repeat (2014).
  • 10. The golden section, tested. The claims (Lendvai, Howat, Putz 1995); if a larger part lies anywhere between half and three-quarters of the whole, a hit within 0.02 of 0.618 happens 16 times in a hundred by chance (simulated: 16.1); this part's sonata, composed without regard to it, divides at 0.625; climaxes of the 54 tunes: 37 in the first half, 2 within 0.02 of 0.618, as chance predicts (2.2).
  • 11. Must the ending be home? An ear question (two short pieces, one ending in G, one in C: which ends where it began?); Cook (1987): a home ending preferred only for pieces under about a minute; Karno and Konečni (1992): a rearranged Mozart movement liked about as well.
  • 12. Frontier: form at scale. Local and global structure in perception (Tillmann and Bigand); the SALAMI annotations (2011) and annotator disagreement; Music Transformer (2018) and long-range structure. ★ research problem: memory for themes and memory for keys, measured separately.
  • Variation 21, recap and problems. The miniature sonata, heard whole; the ledger; what we found; five problems; where it comes back; in practice; references; Part 22.
What is computed and built

python -m videos.music.music21.compute (a few minutes) fills .cache/music21/.

Item What it computes Checked against
hook the spoken phrase, looped ten times —
phrase a sentence and a period on the Tune —
forms self-similarity matrices of binary, ternary, rondo, variations, AABA and verse-chorus plans symmetric, unit diagonal
tune the Tune with harmony: chroma from notes and sound, self-similarity, novelty at two widths, boundaries the Tune's phrase ends
rondo A B A C A, heard —
sonata the miniature sonata: keys over time, novelty, boundaries its section starts
blues twelve bars on the Tune's head —
segment the segmenter on every piece, three kernel widths the pieces' change boundaries
repetition repeated four-note figures in the 54 tunes shuffled tunes
golden climax positions; the chance of a golden hit a simulation
closure two short pieces, one ending away —

Monochord's form tools are held in tests/music/test_form.py; this part's claims and clips in tests/music/test_music21.py.

Sounds. Part 7's piano (a struck string through the soundboard, physical model) in twelve-tone equal temperament; the looped phrase is the series' synthesized narrator voice (synthesized). There are no recordings.

What the models are, and are not. The pieces are composed for this part on the Tune and on Ode to Joy, with block chords every two beats; they are demonstrations of plans, not stylistic imitations. Chroma from the sound gives each short-time spectrum's energy to the nearest of the twelve pitch classes between 60 Hz and 2 kHz, and is averaged per beat with the beat known; real systems must find the beat first (Part 62). The novelty curve uses Foote's tapered checkerboard; boundaries are scored only where the material changes (between different sections), within two beats, since a seam between a passage and its own repeat produces no novelty, and the film says so. Repetition is measured on four-note figures with their rhythm, transposition allowed, in Part 14's tunes, which were written out from memory. The golden-section base rate assumes the larger part is equally likely anywhere between half and three-quarters of the whole; other assumptions change the number but not the point. The perception experiments are summarized from the publications, not recomputed.

Notes

The form templates are classical teaching examples, not definitions covering all music. Sonata secondary areas often use the dominant in major and the relative major in minor, with many alternatives. Graph distance does not predict emotional homecoming proportionally. The simplified graph in Part 19 has maximum distance two, so references to three steps cannot use that metric.

The sound-based detector receives an analysis grid calibrated to the generated beat duration. It receives no score labels, but it does not estimate tempo independently. Kernel choices are compared on this same small synthetic collection, not held-out recordings, and no human baseline is measured. The repetition shuffle permutes pitch-duration pairs; the reported shares count only later nonoverlapping matches under this exact four-note interval/rhythm definition.

The golden-section simulation assumes uniform larger-part ratios from 0.5 to 0.75; its 16 percent is conditional on that choice. The climax comparison uses a different uniform position reference, despite the observed early-climax distribution. Neither exercise establishes composers’ intentions or rejects every golden-section claim. Selection of landmarks and multiple testing matter.

Speech-to-song responses vary with the voice, phrase and listener. The closure studies support task-specific results, not a universal one-minute memory limit. Annotator disagreement changes interpretation of benchmark scores but does not make perfect agreement with one reference mathematically impossible. Historical machine examples do not establish current model performance ceilings.

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Hook: a spoken phrase looped ten times, heard; Deutsch; form as the plan of what returns; the plan.
  2. Phrase, period, sentence: Caplin; an ear question (which theme is the period?).
  3. Binary and ternary: the suite, rounded binary, the da capo aria, the minuet and trio; their pictures.
  4. Seeing repetition: the self-similarity matrix of the Tune, from notes and from sound, heard.
  5. Finding the seams: Foote's novelty curve on the Tune, heard; the kernel's width as the scale of form.
  6. Rondo and variation: an ear question (count the returns); rondo and variation pictures; Mozart's variations.
  7. Sonata: a drama of keys: a miniature sonata's plan and key path; sonata theory.
  8. Song forms: strophic, AABA, verse and chorus; the twelve-bar blues, heard.
  9. Form from sound: the segmenter on the sonata, heard; scores on every piece; what novelty cannot see.
  10. Why so much repetition: repeated figures in the tunes against shuffled ones; mere exposure; Margulis.
  11. The golden section, tested: the base rate of a hit; the sonata; the tunes' climaxes.
  12. Must the ending be home: an ear question (which piece ends where it began?); Cook; Karno and Konečni.
  13. Frontier: local and global structure in perception; SALAMI; long-range structure in generated music.
  14. Variation 21: the Tune as a miniature sonata. Outro: problems, payoffs.

Covers: motive, phrase, period and sentence; binary and ternary; rondo; variation; sonata form as a drama of keys; song forms from strophic to verse-chorus and the twelve-bar blues; repetition; self-similarity; the golden-section claims, tested. Built and computed: monochord/form.py: chroma from notes and from sound, self-similarity matrices, Foote's checkerboard novelty and peak picking, boundary scores, section labels, repetition of figures with shuffled controls, the golden-section base rate; pieces composed on the Tune in every form of the part and rendered on Part 7's piano; the segmenter scored on all of them. The "Library" of the plan is, for now, Part 14's corpus of tunes. Variation 21: the Tune as a miniature sonata whose second theme is its own first phrase, inverted. Frontier: do listeners hear large-scale tonal form? The experiments and the arguments. Reading: Caplin, Classical Form; Hepokoski & Darcy; Margulis, On Repeat.

Build the film

python -m videos.music.music21.compute        # the part's numbers, into .cache/music21
python tools/build.py music21                  # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py music21 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/music/music21. Setup: see the course page. Source of these notes: the README and the scenes' narration.

Build it
python -m videos.music.music21.compute                          # numbers and sounds (a few minutes)
EXPLAINER_TTS=silent python tools/build.py music21 -q l --fps 15   # a silent-narration preview, with the sounds
python tools/qa_sound.py music21 --sync                         # the sound gates
python tools/dead_air.py renders/music21_480p.mp4 --sound music21  # no empty screen; no sound over a still one
python tools/lecture_length.py music21                          # 30 to 60 minutes, listening included
python tools/build.py music21                                   # 1080p30, narrated
python -m pytest -q tests/music                                 # Monochord against its references; this part's claims and clips
python -m videos.music.labs 21                                  # the lab (writes a figure and a short WAV)