♪Music, Built

Act XII · Coda

Part 68 of 68

The Variations

Foundationsstarts at this level36 min of film13 chaptersprerequisites: Part 1, Part 10, Part 43, Part 55, Part 57, Part 58, Part 61, Part 63, Part 67

What survives when a tune travels the whole chain, from a score to a listener and back to a score, and what did the series build?

An ear question: Variation 1 exactly as Part 1 made it; the Goldberg Variations and their aria da capo; the plan. The Chain with every link lit, which act built which link, and the experiment: the whole Tune performed on Part 38's piano, in a room, through a microphone, a master and Part 58's coder, and back by onsets, pitch, a drifting tempo, a key and a fingerprint. Down the chain, heard at five stages, each measured by what it changes; spectrograms; an ear question at 16 kbit/s; the coder rate by rate, and its fallback band at 16 kbit/s, which starves the melody's band (37 of 42 keys wrong), heard. Back up the chain: settings chosen on four other tunes (YIN 34 per cent of keys wrong, the onset reading 23, with SuperFlux 20); the Tune's wrong keys by stage (6 as written, 14 mastered, 12 at 16 kbit/s); every change of key found as written, repeated notes the weak spot; the key misled by the rhythm; an ear question on three recovered scores. What survives: the sound filled by the room and emptied by the coder while the melody's moves hold; fingerprints, tempo and key; the room alone, heard; why notation kept pitch and time. Ordering a suite: the excerpts mapped, path lengths (as made shorter than 99.8 per cent of random orders), an ear question on the longest and shortest steps, the nearest-next order heard. The suite in three movements, every Variation for 8.5 seconds. Monochord counted; the ledger; what is still unknown, with an ear question on two fifths. Variation 68 and Variation 1 again.

What you need. Part 1 for the string and its question; Part 10 for what notation keeps; Part 43 for performance; Parts 54 to 58 for the studio chain; Part 61 for transcription; Part 63 for features and fingerprints; Part 67 for listening tests. Edit distance, onset detection, classical scaling, nearest-neighbour heuristics.

Ideas, mathematics and history
the whole chain run once, end to end; what survives it; what was built; the suite performed
What we build, compute and hear
the round trip from score to sound to score; the concert

What you will be able to do

Foundations

  • Hear the Tune at each stage of the chain and say what each stage changed; hear a recovered score.
  • Hear the suite and place each Variation in the series' story.
  • Explain why a score survives transmission better than a sound does.

Full course

  • Measure a chain stage by stage (timing, reverberation, noise, crest factor, noise against the mask).
  • Transcribe a line by onsets and pitch, quantize it, and score it against the written score by edit distance.
  • Choose settings on held-out material, and order a set of pieces by a feature-space path.

Research

  • Design the experiment that separates the ear's part from the culture's in consonance.

Practice

  • Check a chain's settings at every rate, listen at the end of the chain, and keep a score with every recording.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Foundations 29 min · Full course 32 min · Research 36 min · Practice 32 min.

  1. 0The aria againFoundations3 min
  2. 1The chain, once moreFoundations3 min
  3. 2Down the chainFoundations5 min
  4. 3Back up the chainFoundations6 min
  5. 4What survivesFoundations4 min
  6. 5Ordering a suiteFoundations3 min
  7. 6The suite, I: Sound, Notes and VoicesFoundations1 min
  8. 7The suite, II: a thousand years, many musics, the craftFoundations1 min
  9. 8The suite, III: the mind, the studio, the machinesFoundations1 min
  10. 9What was builtPractice3 min
  11. 10The ledgerPractice1 min
  12. 11Frontier: what is still unknownResearch4 min
  13. Variation 68, recap, and the aria againAll 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.

The aria againFoundations3 min

Sixty-seven parts ago this series began with one string, simulated, and with it played the Tune. Here is that Variation again, exactly as Part 1 made it. What do you hear in it now that you could not hear the first time?

The same file, the same samples. But the opening leap is now many things at once: a ratio of three to two, an interval whose aligned harmonic partials do not beat against each other, a tonic-to-dominant move in this key, the first step of a phrase, and a line a machine could write down. The notes have not changed. The listener has.

In 1741 Johann Sebastian Bach published an aria with thirty variations, for a harpsichord with two keyboards. Every third variation through number twenty-seven is a canon, the first at the unison, the next at the second, and so on up to the ninth; the thirtieth is a quodlibet, two folk songs sung over the bass. The variations keep the aria's bass and harmony, not its melody. And at the end the aria comes back, note for note: aria da capo. The story that gives the work its name, an insomniac count and his harpsichordist Goldberg, was first told in 1802 and may be a legend. The da capo is not: it is in the score.

This series is built the same way. Sixty-seven parts, each of which did something to the Tune with what it had just taught, from one string to a machine that writes. This is the last part. It does what the Goldberg does: it plays the Variations, and then the aria again. But first it does one thing no single part could: it runs the Tune through the whole chain the series built, from a score to a listener, and back to a score, and measures what survives.

Here is the plan. The chain the series built, link by link. The Tune down the whole chain, heard and measured at every stage. And back up it: transcribed, quantized and identified. What survives the journey, and why notation kept what it kept. How to order sixty-seven Variations, and then the suite itself, in three movements. And last, what was built, the ledger, what is still unknown, and the aria again.

1The chain, once moreFoundations3 min

What path does a piece of music travel, and which part built each link?

Every chapter card of this series has carried the same drawing: the Chain, the path a piece of music travels. A mind makes a score; hands play it on an instrument; the sound crosses the air to an ear, and so to another mind. From Act Nine on, the detour lit up: a microphone, a mix, a master, a codec, a stream, a loudspeaker. And Act Eleven added the way back, from sound to a machine to a score. Every link is now lit.

Which act built which link? Acts One and Two built the instrument, the air and the ear, and then the score. Acts Three to Seven filled the score and the hands: voices, a thousand years of style, the world's other musics, and the craft of orchestrating, composing and performing. Act Eight was the listener at the far end. Acts Nine and Ten built the studio: microphones, mixing, mastering, codecs. Act Eleven built the way back, machines that listen. And this act asked how the field knows what it knows, and now runs the whole chain at once.

So here is the experiment, one tune through every link. The score: the whole Tune, forty-two notes at a hundred and twenty beats a minute. A performance, as Part 43 modelled one: a tempo that breathes, phrase ends held, dynamics that swell to the middle of each phrase. The instrument: Part 38's simulated piano. A room, with a reverberant tail of one point four seconds. A microphone's band and its noise. A master's limiter. Part 58's coder, at four bit rates. And then the way back: onsets and pitch, a score with a drifting tempo, a key, a fingerprint. Each link is a model a part built and checked; none is new here.

What is measured? Each stage on the way down is measured by what it changes: timing, dynamics, space, noise, peaks and bandwidth. What comes back is scored against what was written: the notes found, the keys that are wrong, the note values that are wrong. Wrong keys are counted by edit distance, the fewest insertions, deletions and substitutions that turn one line into the other, so one missed note costs one, not every note after it. And the transcriber's settings were chosen on four other tunes sent down the same chain, never on the Tune, so that the Tune is a fair test.

2Down the chainFoundations5 min

What does each link do to the Tune?

Here is the Tune going down the chain: ten seconds of it at five stages. As written, played strictly. Performed. In a room. Mastered. And through the coder at sixteen kilobits a second, the end of the chain. Listen for what each stage adds, and for what never changes.

The intended performed notes and their order were held fixed. Almost everything else did: the timing, the loudness, the space around the sound, its colour, and at the end its cleanness.

What did each stage change? Measured, each by its own quantity. The performance moved the onsets about milliseconds, on average, from a strict tempo, and spread the dynamics over decibels. The room added reverberation decibels below the direct sound. The microphone narrowed the band and added noise decibels below the music. The master's limiter cut the crest factor from to decibels. And the coder: at a hundred and twenty-eight kilobits its estimated noise-to-mask ratio sits decibels under the mask, below this simplified masking estimate, which does not establish inaudibility; at sixteen it is decibels over it.

The same eight seconds as pictures: time across, pitch up, brightness for level. Performed, each note is a stack of bright partials, and each strike of a hammer a thin vertical line. In the room, the gaps between notes fill with reverberation. Mastered, the quiet background rises further, with the noise and the limiting. And after the coder at sixteen kilobits, the quiet background is gone, the band stops at five and a half kilohertz, a few stray patches of the coder's own noise sit below the melody, and the thin lines of the hammer strikes have nearly vanished. But in every picture the lowest bright line, the melody, climbs and falls in the same places.

Now the end of the chain alone: the first two phrases after every stage, ending in the coder at sixteen kilobits. Could you still sing it back? And what has gone?

You could very likely still sing it back: every note is there. What has gone is the cleanness of the sound, and most of the room. The coder's noise is now above its own estimate of what the ear masks, and with too few bits to go round it kept what was loud, the notes, and let what was quiet, the reverberation, fall to nothing.

The coder, rate by rate, as Part 58 built it. At a hundred and twenty-eight kilobits the band reaches eighteen kilohertz and the estimated quantization-noise level is below the model mask. At sixty-four the band is cut to fourteen kilohertz and the noise reaches the mask. At thirty-two, nine kilohertz, and the noise is over it. At sixteen, five and a half kilohertz, and still over. A coder spends bits where the ear would hear their absence, and below some rate there are not enough to go round.

One setting deserves a closer look. Part 58's coder takes its band from a table, and the table has no entry for sixteen kilobits, so the coder falls back to its full band of eighteen kilohertz. This chain cut it to five and a half, between the table's neighbours. Here is what the fallback does. Spreading too few bits over the whole band, it lets the loudest bands, where the melody lives, fall by decibels, while the bands above survive. The machine then gets keys wrong of forty-two, against . Hear both.

The second keeps only the upper part of the spectrum, so what is left is thin and high, a ghost of the Tune. A coder is not only its algorithm but its settings, and an implementation setting can fail on a particular input in a way an average can hide; this chain explicitly overrides the sixteen-kilobit cutoff.

3Back up the chainFoundations6 min

Can a machine recover the score from what the chain delivers?

The way back starts with a machine that listens, assembled from Part 61's tools. It finds onsets where the spectrum's energy jumps; or, in a refinement called SuperFlux, from Böck and Widmer, where it rises above everything in the last few frames, so that energy which flickers on and off does not count as a new note. It can read each note's pitch one way, with YIN, from the period of the sound over the note. Or another way: the note whose harmonics gained the most energy at the onset. Then it writes a score: note values and a tempo that may drift, found by dynamic programming, and a key. The Tune is one line, so the machine listens for one line.

Before the Tune was sent, the machine's settings were chosen on four other tunes sent down the same chain: and , notes in all. Each way of listening was given its best settings. With YIN, per cent of the keys came back wrong, averaged over all nine stages. The reason is the piano: each note rings on through its release while the next begins, and YIN, reading the whole sound, is pulled between the two; what changed at the onset is the new note alone. Reading the onset, per cent. With SuperFlux as well, per cent, mostly because the coder's flickering bands stop counting as notes. So the machine listens that way, and the Tune was never used to choose.

And here is the Tune. For each stage, the number of the forty-two keys that came back wrong, counted by edit distance. As written: . Performed: . In the room: . Through the microphone: . Mastered: . Through the coder at a hundred and twenty-eight kilobits: ; at sixty-four, ; at thirty-two, ; at sixteen, . Below, the note F score, which also asks that each onset be within fifty milliseconds of the performance.

How does that compare with Part 61's network, which was trained on random polyphony? Its note F is on the performance, mastered, and at sixteen kilobits. The one-line machine scores , and . A general tool can lose to a narrow one on a narrow task: the network expects chords, and finds ghosts of them in the room's reverberation.

Which notes go wrong? Split them in two. The Tune has twenty-four note positions counted as pitch changes, including its opening: as written, onsets are detected near all positions, through the room and the microphone , and after the master between and . And eighteen that repeat the key before: C, C; G, G. Those attacks are the weak spot in this onset-only diagnostic, found as written and at worst. A re-struck key adds little that is new to the spectrum. And the master's limiter, which reduces peaks and alters many attacks, costs notes of both kinds: most of the loss arrives there, and the coders add little to it. The two lowest rates add something else: and onsets where there was no note, the coder's own.

Now the score itself, keys and note values together, for the first two phrases recovered from the master. Red marks what differs. Over the whole Tune, edits turn the recovered score into the written one. The tempo it found is beats a minute, for a performance played at a hundred and twenty with rubato. And the key: from the performance on, the key finder names . Counting the recovered notes alone, without the lengths the quantizer gave them, it names . Counting and duration weighting produce different key estimates here; that does not prove every recovered pitch is right. A missed repeat lengthens the note before it, and the lengths it wrote give D and G more time than the score does, and C less: the weight of G major.

Three scores the machine wrote down, played back strictly on the piano: one from the master, one from thirty-two kilobits, one from sixteen, in a shuffled order. Which came from where?

A came from , B from , and C from . Played back strictly, a recovered score keeps none of the coder's sound: only its mistakes, a wrong key here, a wrong length there. That is all the chain can do to a score; and it is why a score is such a durable thing to send.

4What survivesFoundations4 min

Which parts of music survive the journey, and why did notation keep those?

Put the sound and the notes side by side. Above, how much of the sound's picture lies within forty decibels of its loudest: a thresholded spectrogram occupancy, not a direct noise-floor measurement. Performed, per cent; the room fills the gaps, ; the microphone and the master fill them further, ; and the starved coders empty them, . The sound is remade at every link. Below, detected onsets at pitch-changing note positions: of twenty-four as written, through the room and the microphone, to after the master. This spectral occupancy changes greatly while many onset positions remain detectable.

Three more questions a listener, or a machine, asks of a recording. What is it? Part 63's fingerprinter was given the sixty-seven Variations and the Tune as performed, and queried with six seconds of each stage. On the performance itself the right match has aligned votes. Through the room, , barely above the next best; and from the master on, the best match, right or wrong, has hardly more votes than the next: against at the master. A fingerprint is a picture of the loudest points of the spectrum, and the room and the limiter move them. How fast is it? Part 62's tempo estimate stays between and beats a minute until the last stage, where it jumps to , half as fast again, probably because the coder's false onsets suggest a quicker pulse. And what key? Counting the recovered notes, C major at stages of .

What the chain adds can be heard on its own. Here is the performance dry, and then the room alone: the room's sound with the direct sound taken away.

In the room alone the melody is still faintly there, smeared, because the room only repeats what it is given. But nothing in a score records it.

Why did notation keep what it kept? A basic pitch-duration encoding records selected aspects of pitch and time; richer scores also specify dynamics, instruments and articulation, as Part 10 found. The chain changes timbre and space at every link, and pitch and time hardly at all. So a score is a code for what survives transmission, and a very compact one: Part 10 used an illustrative compact Tune encoding of a hundred and sixty-eight bits, relying on shared decoding assumptions; its PCM audio used vastly more bits, without making this a lossless audio-compression comparison. A copyist, a hall, a codec: each passes the notes on, and each changes the sound. What notation leaves out is not unimportant. It is what each performance, each room and each listener supplies.

What does this experiment not show? Its model is simple: one piano, one tune, one room, one take. Real chains have more links, and worse ones: phone loudspeakers, noisy rooms, streams coded twice over. The transcriber listens for one line; with a chorus or a band the notes survive less well, as Parts 61 and 64 found. The finding to keep is relative: in this particular chain, some intended note information remains recoverable despite large timbral changes.

5Ordering a suiteFoundations3 min

In what order should sixty-seven Variations be played?

The plan for this part promised a suite. Sixty-seven Variations last about thirty-nine minutes, too long and too uneven for one sitting. So the suite takes an excerpt of each: the first eight and a half seconds from its first sound, normalized by the chosen excerpt-level rule. The rule was fixed in advance, not chosen by ear, so no excerpt was picked for flattering its part. Then it needs an order, because a suite is heard in sequence, each piece against the one before. Three candidates: the order they were made in; each followed by whichever sounds nearest; and at random.

To compare orders, each excerpt is described by the content features of Part 63: the levels and spread of twenty-four frequency bands, a chroma, and the flux of the spectrum, each standardized. Here they are, flattened onto the page by classical scaling, coloured by act: excerpts that sound alike by these measures sit close together. And here is the path in the order they were made. It wanders, but in places it stays in a neighbourhood for several parts at a time, where consecutive parts share their instruments.

Add up the steps of a path and you have a distance in these standardized content features, not a validated perceptual measure. Two thousand random orders travel between and units, ninety-five times in a hundred. The order the Variations were made in travels : shorter than per cent of the random ones. Consecutive parts are closer under these features than most sampled random permutations. And a rule that always moves to the nearest excerpt not yet played travels only .

Two pairs of neighbours from the suite as it was made, five seconds of each Variation. Which pair sounds closer together, the first or the second?

By the features, the second: the step from Variation to is the shortest in the suite, and the step from to the longest. Whether your ear agreed is the real test of the features, and it may not have: they measure bands and chroma, not everything a listener hears.

Here is the nearest-next order, its first eight steps, four seconds each. Listen to how smoothly it moves, and how little it tells you.

Smooth, and shuffled across the whole series: the story of how the Tune changed, part by part, is gone.

Which order, then? The nearest-next order is the smoothest, and tells no story. A random order is neither smooth nor a story. The order they were made in is a history: each Variation uses what the parts before it built. And it is already smoother than nearly every random order. So the suite is played as the Variations were made, in three movements.

6The suite, I: Sound, Notes and VoicesFoundations1 min

What did the Tune become in Acts I to III?

The first movement: Acts One to Three, twenty-two Variations, eight and a half seconds of each, in the order they were made, each from its first sound and brought to the same loudness. Listen first for the sound itself changing: a string, bottles of water, pure tones added one by one, a Tune whose fundamentals are missing, chords in eight tunings, then the instruments family by family. Then the Tune is written down, and gains a meter, modes, chords, voices, a canon and a form.

That was the foundation: what a musical sound is, and how sounds became notes and notes became voices. Every later Variation stands on these twenty-two.

7The suite, II: a thousand years, many musics, the craftFoundations1 min

What did the Tune become in Acts IV to VII?

The second movement: Acts Four to Seven. First a thousand years of European style in five steps, from chant to a Romantic song. Then what is left after tonality: whole-tone planing, a twelve-tone row, the Tune phased against itself, paths on the Tonnetz. Then the world's other answers: a raga, three maqamat, the qin and the gamelan, an interlocking pattern, the blues, bebop and a pop single. And last the craft: orchestrated, composed by a search, and performed.

Through most of that movement the Tune's opening was there to be found, though some Variations, like the twelve-tone row, bury it on purpose. A melody survives modes, meters, tunings and whole traditions remarkably well, which is one reason the series could carry one tune through sixty-seven parts.

8The suite, III: the mind, the studio, the machinesFoundations1 min

What did the Tune become in Acts VIII to XII?

The third movement: Acts Eight to Twelve, twenty-three Variations. The mind: the Tune hidden in another line, three endings, a chain of thirty simulated singers. Electric sound: bits and dither, rooms and plates, hard-tuned voices, synthesizers, a tracker. The studio: microphones, a mix, a master, a codec, an arena. And then the machines that listen and write, and last the critical edition of Part 67. Here the instruments are mostly not new: the Tune is carried by what earlier parts built, and changed by what happens to sound after it is made.

That is all sixty-seven, about ten minutes of music made by sixty-seven parts. One Variation is missing: this part's own. It is the suite you have just heard.

9What was builtPractice3 min

What is Monochord now, and how do we know it works?

Monochord began in Part 1 as one simulated string. Here it is, counted from the repository. modules, about lines of code, and tests that hold it to account. Parts 1 to 67 computed sounds with it, about hours of them, generated or assembled by the code, including the transparently described transformations of earlier synthetic clips. And there is a lab for every part.

Its layers, each the size of the code it takes. The core holds the sounds, the clips, the Tune and the corpora. The physics: strings, air, the ear, the instruments and their tunings. The theory, from pitch to grammar. The styles: eras, and the world's other musics. The craft and the mind. The electronics, from sampling to the workstation. The studio. And last the machines that listen and make. The theory and the styles are as large as the physics: much of music's knowledge is about structure, not sound.

How do we know it works? The project includes independent checks for many layers, alongside internal consistency tests and model-specific assumptions. Against closed forms: d'Alembert's solution for the string, Bessel's functions, Sabine's formula, the binomial distribution. Against other people's code: SciPy's signal processing, and ffmpeg's loudness meter beside the series' own. Against published numbers, like Krumhansl and Kessler's key profiles. Against scores whose analysis is known, Bach's chorales above all. And where there was nothing independent to check against, each part says so in its notes.

And what can you now do, with it or without it? Simulate a string, a pipe, a membrane, a room, and say what an ear will make of them. Tune a scale, spell a chord, find a key, check a counterpoint, parse a phrase. Read a style or a tradition by its own rules: a talea, a tihai, the moves of a maqam. Filter, synthesize, mix, master and code a sound, and measure what each step did. And build a machine that listens or writes, split its data honestly, and audit its verdicts.

10The ledgerPractice1 min

What was done to the Tune, and what was measured each time?

What is the ledger, then? Every row measures its Variation by the idea of its part, not by taste. The measures are of many kinds: cents, decibels, bits, counts of rules broken, seconds and dollars. Some are verdicts that the series later checked: Part 67 re-ran five, and found one weaker than had been said. And every row's sound, score and numbers are kept in its part's files, with its claim held by that part's tests.

11Frontier: what is still unknownResearch4 min

Why do simple ratios sound good, and what else is open?

The series began with a question. Stop a string at two thirds of its length and it sounds a fifth higher. That is an ancient experiment linking music and physical measurement, and it is a musical one. The question it left is two and a half thousand years old: why do simple ratios sound good? Sixty-seven parts later, how much of it is answered?

First, Part 1's string once more. It sounds a fifth with the open string twice: once at exactly three to two, and once with the bridge moved by one per cent. Which one beats?

The second. The open string's third partial and the fifth's second partial sit hertz apart, and so beat about times a second. At exactly three to two those two partials coincide, and those two partials do not beat against each other. That is Helmholtz's answer, and Part 5's.

How much is answered? The physics: at simple ratios the partials of harmonic tones coincide, so those coinciding components do not beat against one another; other partial pairs can still contribute beating or roughness. That was Helmholtz's answer, and Part 5 measured it. The ear: such a chord also looks to a pitch model like a single harmonic series, a single source. The timbre: bend the partials, as Variation 5 did, and other intervals become the smooth ones, so the ratios are good only for the sounds that have harmonic partials. And the culture: in 2016 listeners in the Bolivian Amazon, who had heard little Western music, heard roughness as others do but did not prefer consonant chords. So part of the answer is in the sound, part in the ear, and part in what a listener has learnt. How the parts divide is still open.

And what else is still open? How much of consonance, of key and of meter is learnt, how fast, and in how many cultures. What in the brain computes harmonicity and expectation, and why music moves people at all. Why music exists: the theories of its origin are many and the evidence thin. Machines that judge music as listeners do, and that are honest about what they learnt from. And the research problems this series posed as questions, gathered in Part 67.

So the last research problem goes back to the first part. Separate the ear's part from the culture's. Play the same chords, with harmonic partials and with stretched ones, to listeners of many musical cultures, and to some who know little music at all. Measure what each hears, the roughness, the fusion into one sound, the pitch, apart from what each prefers. If roughness is heard everywhere and preference varies, the goodness of the ratio is part sound and part learning, and the experiment helps compare perceptual and cultural contributions, without uniquely decomposing their causes. Every tool it needs is in this series: stretched partials from Part 5, and listening tests with enough power from Part 67.

Variation 68, recap, and the aria againAll tracks3 min

Every part ends with its Variation. This part's is the suite: every Variation, in the order the series made them. Its row closes the ledger, with the measure this part took: how many of the Tune's forty-two keys come back wrong, as written, after the master, and at the end of the chain.

What did we find? The chain is the series: every link a model some part built and checked. Down the chain, the sound is remade at every link: its timing, its space, its noise, its peaks, its band. Back up it, onsets at pitch-changing note positions are detected, of twenty-four as written and at worst, while repeated notes are the weak spot, and most of the loss arrives at the master's limiter, not at the coders. The simplified score encoding tracks intended pitch and duration separately from many timbral changes. The Variations, in the order they were made, sit closer together than almost any random order. And what is still unknown includes the question Part 1 began with.

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

Where from here? Keep the instrument: Monochord is in the repository, and every module runs without the films, with its tests. Keep the labs: one for every part, each a page of numbers and a sound you can change. Go wider: Statistics, Built for the methods of Part 67, and AI, Built for the networks of Act Eleven. And go to the music. This series described many pieces it could not play, because they are under copyright or need a hall. Hear them, in good recordings and in good rooms.

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

And so, as the Goldberg does, the aria again. Variation 1, the Tune on one simulated string, the same samples as in the original cached rendering of Variation 1.

The same notes. A different listener. That was Music, Built. Thank you for listening.

Where it goes next. The end of the series: the open problems of Part 67 and this part's research question.

Key results

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

Edit distance\(\displaystyle D_{i,j} = \min(D_{i-1,j} + 1,\ D_{i,j-1} + 1,\ D_{i-1,j-1} + [a_i \ne b_j])\)
SuperFlux\(\displaystyle \mathrm{SF}(n) = \textstyle\sum_k \max\big(0,\ L(n,k) - \max_{1 \le \mu \le \lambda,\ |j - k| \le w} L(n - \mu, j)\big)\)
Crest factor\(\displaystyle C = 20 \log_{10} \big( \max |x| \,/\, \sqrt{\overline{x^2}} \big)\)
Classical scaling\(\displaystyle B = -\tfrac12 J D^{(2)} J,\ \ X = V_2 \Lambda_2^{1/2}\)
Beats of a mistuned fifth\(\displaystyle f_{\mathrm{beat}} = |3 f_1 - 2 f_2|\)

Try it

Lab 68 · The round trip

Send a tune down a chain (Part 1's plucked string, a room, a limiter, a perceptual coder) and back up it (onsets, pitch, a score with a drifting tempo), and count what comes back wrong at each stage.

Figure produced by Lab 68: The round trip
Produced by the lab below, seed 0, in 6.9 s.
python -m videos.music.labs 68 needs numpy, scipy, matplotlib · download lab68.py · source on GitHub
played: notes found; wrong keys (edit distance); wrong keys and values; tempo          30; 2; 3; 133 bpm
room: notes found; wrong keys (edit distance); wrong keys and values; tempo            30; 2; 3; 133 bpm
master: notes found; wrong keys (edit distance); wrong keys and values; tempo          30; 2; 3; 133 bpm
coded: notes found; wrong keys (edit distance); wrong keys and values; tempo           29; 5; 7; 133 bpm
the tune                                                                               Ode to Joy, 30 notes
what the room adds (reverberant energy against the direct sound)                       -4.2 dB
crest factor before and after the limiter                                              14.3 dB, 10.0 dB
ear problem: the tune played, then after the whole chain; can you still sing it back?  coded at 32 kbit/s

A chain changes the sound at every link and the notes hardly at all, until the coder runs out of bits: which is why a score, which keeps only notes and times, travels so well.
The code (85 lines; it asserts its own result)
"""Lab 68: the round trip.  A tune is played, put in a room, mastered and coded, then transcribed back to a score and
compared with what was written, key by key."""

import numpy as np

from videos.coursekit import labs
from explainer.music.monochord import SR, Clip, concat
from explainer.music.monochord import codec as K
from explainer.music.monochord import melody as ML
from explainer.music.monochord import roundtrip as RT
from explainer.music.monochord import space as SPC
from explainer.music.monochord.mir import transcribe as TR
from explainer.music.monochord.instruments.plucked import plucked

TITLE = "The round trip"
GOAL = ("Send a tune down a chain (Part 1's plucked string, a room, a limiter, a perceptual coder) and back up it (onsets, pitch, "
        "a score with a drifting tempo), and count what comes back wrong at each stage.")
TASKS = [
    "Change KBPS, the coder's bit rate. Where does the line start to come back wrong? Where can you no longer sing it?",
    "Change TUNE (an index into Part 14's melodies). Are repeated notes or leaps harder for the machine?",
    "Change REVERB, the room's level against the direct sound. Which stage of the way back suffers first?",
]
KBPS = 32
TUNE = 4            # Ode to Joy
REVERB = 0.7
CUT = {16: 5500.0}  # Part 58's table has no entry for 16 kbit/s (see Part 68)


def play(keys, beats, beat=0.45):
    """Each note on Part 1's plucked string, retuned to the note, damped 0.15 s after the next would begin."""
    t, y, cache = 0.0, np.zeros(int((sum(beats) * beat + 2.0) * SR)), {}
    for m, b in zip(keys, beats):
        if m not in cache:
            cache[m] = np.asarray(plucked(f1=440 * 2 ** ((m - 69) / 12), seconds=1.2), float)
        z = cache[m][: int(b * beat * SR) + int(0.15 * SR)].copy()
        r = int(0.1 * SR)
        z[-r:] *= np.linspace(1, 0, r) ** 2
        i = int(t * SR)
        y[i:i + len(z)] += z[: len(y) - i]
        t += b * beat
    return y / (np.max(np.abs(y)) + 1e-12) * 0.8


def chain(y, seed=0):
    from scipy.signal import fftconvolve
    ir = SPC.noise_tail(1.4, 1.6, seed=seed, start=0.012)
    wet = fftconvolve(y, ir)[: len(y)]
    room = y + wet * (REVERB * np.sqrt(np.mean(y ** 2)) / (np.sqrt(np.mean(wet ** 2)) + 1e-12))
    room = room / np.max(np.abs(room)) * 0.8
    master = np.tanh(2.2 * room) * 0.9
    coded = K.encode(master, KBPS, cutoff=CUT.get(KBPS))["y"][: len(master)]
    return {"played": y, "room": room, "master": master, "coded": coded}


def run(seed=0):
    lab = labs.Lab()
    m = ML.corpus()[TUNE]
    keys, beats = [72 + p for p in m.pitches], [float(b) for b in m.beats]
    st = chain(play(keys, beats), seed)
    errs = {}
    for k, y in st.items():
        est = RT.monophonic_notes(y, method="onset", compress=10.0, delta=0.2, lag=3)
        b = RT.back_to_score(est)
        e = RT.score_errors(b["keys"], b["values"], keys, beats)
        errs[k] = e["pitch"]
        lab.row(f"{k}: notes found; wrong keys (edit distance); wrong keys and values; tempo", f"{len(est)}; {e['pitch']}; {e['score']}; {b['bpm']:.0f} bpm")
    lab.row("the tune", f"{m.name}, {len(keys)} notes")
    assert errs["played"] <= 2
    lab.row("what the room adds (reverberant energy against the direct sound)", f"{RT.late_to_early_db(st['room'] / 0.8 * np.max(np.abs(st['room'])), st['played']):.1f} dB")
    lab.row("crest factor before and after the limiter", f"{RT.crest_db(st['room']):.1f} dB, {RT.crest_db(st['master']):.1f} dB")
    lab.audio = concat([Clip(st["played"], SR), Clip(st["coded"] / (np.max(np.abs(st["coded"])) + 1e-12) * 0.8, SR)], gap=0.8)
    lab.row("ear problem: the tune played, then after the whole chain; can you still sing it back?", f"coded at {KBPS} kbit/s")
    fig, (ax1, ax2) = labs.figure(2)
    names = list(st)
    ax1.bar(range(len(names)), [errs[k] for k in names], color=labs.GOLD)
    ax1.set_xticks(range(len(names)), names)
    ax1.set_ylabel("wrong keys")
    L = TR.logfreq(st["coded"][: 8 * SR], SR, fmin_midi=48, fmax_midi=120, per_semitone=1, hop=1920)
    ax2.imshow(20 * np.log10(L["S"] + 1e-9), origin="lower", aspect="auto", vmin=-60 + 20 * np.log10(L["S"].max()), cmap="magma")
    ax2.set_xlabel("frame")
    ax2.set_ylabel("semitones above C3")
    lab.fig = fig
    lab.note = ("A chain changes the sound at every link and the notes hardly at all, until the coder runs out of bits: "
                "which is why a score, which keeps only notes and times, travels so well.")
    return lab

Now change it

  1. Change KBPS, the coder's bit rate. Where does the line start to come back wrong? Where can you no longer sing it?
  2. Change TUNE (an index into Part 14's melodies). Are repeated notes or leaps harder for the machine?
  3. Change REVERB, the room's level against the direct sound. Which stage of the way back suffers first?

Problems, with solutions

Try each problem before opening its solution.

  1. Compute. A line of 42 notes comes back with one note missed near the start. How many positions disagree, and what is the edit distance?

    Solution

    Compared position by position, every note after the gap is shifted by one, so up to 41 positions disagree (fewer where neighbouring notes repeat). The edit distance is 1: insert the missed note. That is why the film counts wrong keys by edit distance (roundtrip.edit_distance).

  2. Prove. Show that the greedy nearest-neighbour order can be longer than the best order by a factor that grows with the number of pieces.

    Solution

    Rosenkrantz, Stearns and Lewis (1977) built point sets on which nearest-neighbour tours are Θ(log n) times longer than the optimum, and proved the ratio is at most ½(⌈log₂ n⌉ + 1) for distances obeying the triangle inequality. The construction places points so that each greedy choice is locally shortest but leaves a far cluster to be fetched later, recursively at every scale; summing the detours over log n scales gives the factor.

  3. Ear. The lab sends a tune of your choice down the chain. At which bit rate can you no longer sing it back?

    Solution

    Set KBPS from 128 down to 16 (the lab cuts the band to 5.5 kHz at 16, as the film does). For most listeners the tune stays singable at every rate; what goes first is the sound's cleanness. The lab's table shows where the machine's wrong keys begin to rise, which is usually earlier than where a listener loses the tune.

  4. Build. Add a stage to the chain (a phone's loudspeaker, Part 54) and find what it costs the round trip.

    Where to look. In the lab's chain, band-limit the master to 300 Hz to 8 kHz (or use Part 54's loudspeaker response) before the coder. The fundamentals of low notes go, the harmonics stay: the onset reading still finds most keys, YIN may jump an octave. Compare the two readings' wrong keys.

  5. ★ Why do simple ratios sound good? Design the experiment that would separate the ear's part from the culture's.

    Where the frontier is. Play the same chords with harmonic and with stretched partials to listeners of many musical cultures and to some with little musical experience; measure perceived roughness, fusion and pitch apart from preference, with enough trials for the effects expected (Part 67). McDermott et al. (2016) and later cross-cultural studies are the place to start.

Notes and sources

Sources

  • J. S. Bach, Clavier-Übung IV (the Goldberg Variations, 1741); J. N. Forkel, Über Johann Sebastian Bachs Leben, Kunst und Kunstwerke (1802), the source of the Goldberg story.
  • H. von Helmholtz, On the Sensations of Tone (1863); J. H. McDermott, A. F. Schultz, E. A. Undurraga and R. A. Godoy, "Indifference to dissonance in native Amazonians reveals cultural variation in music perception", Nature (2016).
  • M. Müller, Fundamentals of Music Processing (2nd ed., 2021); A. de Cheveigné and H. Kawahara, "YIN, a fundamental frequency estimator for speech and music", JASA (2002); S. Böck and G. Widmer, "Maximum filter vibrato suppression for onset detection" (SuperFlux), DAFx (2013); A. T. Cemgil and B. Kappen, "Monte Carlo methods for tempo tracking and rhythm quantization", JAIR (2003).
  • V. I. Levenshtein, "Binary codes capable of correcting deletions, insertions and reversals" (1966); D. J. Rosenkrantz, R. E. Stearns and P. M. Lewis, "An analysis of several heuristics for the traveling salesman problem", SIAM J. Computing (1977); W. S. Torgerson, "Multidimensional scaling" (1952).
  • J. O. Smith, Physical Audio Signal Processing (2010).

Review scope: pitch-change/restrike detection counts match onset proximity within 80 ms and do not verify pitch; the separate note F-score requires pitch and a 50 ms onset window. Compact notation bit counts rely on shared decoding assumptions. The 16 kbit/s chain uses an explicit 5.5 kHz cutoff override. Feature-space ordering is not a validated perceptual optimum.

About this partfrom its README

The last part of a sixty-eight-part course in music (see the series plan and the syllabus), the second of Act XII, Coda. Bach's Goldberg Variations end by playing the opening aria again, note for note, and it does not sound the same. This part runs the series' whole chain once, from a score to a listener and back to a score, measures what survives the journey, orders the sixty-seven Variations into a suite and plays it, counts what was built, and ends with Variation 1 again. Its tools are Monochord's (explainer/music/monochord/roundtrip.py, with Part 61's transcription and Part 63's features).

  • The aria again. An ear question (Variation 1, exactly as Part 1 made it: what do you hear now?); the Goldberg Variations (1741: an aria, thirty variations, every third a canon, the aria da capo; the Goldberg story is from 1802); the series map; the plan.
  • 1. The chain, once more. The Chain with every link lit, and the way back; which act built which link; the experiment (the whole Tune, 42 notes, through a performance, Part 38's piano, a room, a microphone, a master and Part 58's coder, and back by onsets, pitch, a drifting tempo, a key and a fingerprint); what is measured.
  • 2. Down the chain. Five stages heard; each measured by what it changes (onsets 123 ms from a strict tempo; reverberation 3.1 dB under the direct sound; noise 33 dB under the music; crest factor 14.6 to 8.8 dB; the coder's noise -13 dB against its mask at 128 kbit/s and +5 at 16); four spectrograms; an ear question (the end of the chain at 16 kbit/s: can you still sing it?); the coder rate by rate, and what its fallback band does at 16 kbit/s (the melody's band 82 dB down; 37 of 42 keys wrong), heard.
  • 3. Back up the chain. How the machine listens (onsets by spectral flux or SuperFlux; pitch by YIN or by the harmonics gained at each onset); settings chosen on four other tunes (Frère Jacques, Mary Had a Little Lamb, London Bridge, Ode to Joy): YIN 34 % of keys wrong, Part 61's flux with the onset reading 23 %, SuperFlux 20 %; the Tune: wrong keys by stage (as written 6; performed 6; room 8; microphone 8; master 14; 128 12; 64 15; 32 14; 16 kbit/s 12); which notes go wrong (every change of key found as written, 17 of 24 at worst; repeated notes the weak spot, 9 to 14 of 18 found; the coder's false onsets at 32 and 16 kbit/s); beside Part 61's network; the first two phrases written and recovered; the key, G major by the recovered lengths and C major by the notes; an ear question (three recovered scores, replayed: which came from where?).
  • 4. What survives. Thresholded spectrogram occupancy (changed by the room, master and coder) against the notes that change key, stage by stage; does it still sound like itself (the fingerprinter's match: 689 aligned votes on the performance, 25 through the room, and from the master on hardly more than the next best; tempo; the key, C major at 6 of 9); the room alone, heard; why notation kept pitch and time (Part 10's 168 bits); what the experiment does not show.
  • 5. Ordering a suite. An excerpt rule fixed in advance; the excerpts mapped by Part 63's features; path lengths (as made 636, nearest-next 390, 2000 random orders 653 to 745); an ear question (the suite's longest and shortest steps, Variations 27 to 28 and 31 to 32); the nearest-next order, heard; the order chosen: as made.
  • 6–8. The suite. Three movements: Variations 1–22 (Acts I–III), 23–44 (IV–VII) and 45–67 (VIII–XII), 8.5 seconds of each, 10.1 minutes in all, each cell lit as it plays with its ledger title.
  • 9. What was built. Monochord counted (95 modules, about 25,531 lines, 879 tests, 999 sounds, 4.3 hours, 68 labs); its layers; how it was checked; what you can now do.
  • 10. The ledger. All sixty-eight rows, page by page; what the ledger is.
  • 11. Frontier: what is still unknown. Part 1's question; an ear question (a fifth at 3:2 and one mistuned by 1 %: partials 392 and 389 Hz beat about 4 times a second); physics, ear, timbre and culture; what is still open (44 research problems from the parts); ★ research problem: separate the ear's part from the culture's.
  • Variation 68, recap, and the aria again. The ledger's last row; what we found; five problems; from here; references; Variation 1 again, on the drawn monochord; the end.
What is computed and built

python -m videos.music.music68.compute (some minutes: the chain is run for the Tune and four other tunes) fills .cache/music68/.

Item What it computes Checked against
chain, pictures, wide the Tune at nine stages down the chain, each stage's measure, spectrograms; the coder's fallback band the coder's bit rates (tests)
calibrate the transcriber's settings, chosen on four other tunes over every stage the Tune is not among them (tests)
roundtrip, back the line transcribed, quantized and keyed at each stage; three recovered scores replayed the written score (edit distance)
identify, survive fingerprints, tempo and key at each stage; brightness against wrong keys; the room alone —
order, pairs, nearest the excerpts' features, classical scaling, path lengths, 2000 random orders the rule's definition (tests)
suite, hook, fifths the three movements from every part's stored Variation; Variation 1; two fifths the ledger (tests)
built Monochord and the series counted from the repository —

Monochord's tools are held in tests/music/test_roundtrip.py; this part's claims and clips in tests/music/test_music68.py.

Sounds. Part 38's piano through the chain; every part's own Variation, as stored; Part 1's string.

What the models are, and are not. The chain has one piano, one tune, one room, one take, and a performance made by rule; real chains have more links and worse ones. The transcriber listens for one line; it would do worse on a chorus or a band. The coder is Part 58's: at 16 kbit/s its table has no band, and the chain uses 5.5 kHz, between its entries for 12 and 24 kbit/s; the fallback is shown separately. The ordering features measure bands, chroma and flux, not everything a listener hears; the excerpt rule was fixed before the suite was heard.

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Hook: an ear question (Variation 1, as Part 1 made it); the Goldberg Variations and the aria da capo; the plan.
  2. The chain, once more: every link lit; which act built which link; the experiment; what is measured.
  3. Down the chain: five stages heard and measured; spectrograms; an ear question (16 kbit/s); the coder rate by rate; its fallback band, heard.
  4. Back up the chain: how the machine listens; settings chosen on other tunes; wrong keys by stage; which notes; a network beside it; the score recovered; an ear question (three recovered scores).
  5. What survives: the sound's quiet part against the melody's moves; fingerprint, tempo and key; the room alone, heard; why notation kept pitch and time; what the experiment does not show.
  6. Ordering a suite: the excerpt rule; the map; path lengths; an ear question (the longest and shortest steps); nearest-next, heard; the order chosen. 7–9. The suite in three movements: Acts I–III, IV–VII, VIII–XII.
  7. What was built: Monochord counted; its layers; how it was checked; what you can now do.
  8. The ledger: all sixty-eight rows.
  9. Frontier: Part 1's question; an ear question (two fifths); what is answered; what is open; the last research problem.
  10. Variation 68, recap, problems, from here, references; Variation 1 again; the end.

Covers: the chain end to end (performance, instrument, room, microphone, master, codec) and back (onsets, pitch, quantization, key, identification); what the chain preserves (pitch and time) and what it remakes (space, noise, peaks, band), and why notation chose as it did; ordering pieces into a suite; what was built; what is still unknown about the question of Part 1. Built and computed: monochord/roundtrip.py: a line transcriber (onsets by spectral flux or SuperFlux; pitch by YIN or by the harmonics gained at the onset), edit distance, stage measures, the suite's helpers. Settings chosen on four other tunes (34 % of keys wrong with YIN, 23 % reading the onset, 20 % with SuperFlux); the Tune's wrong keys 6 as written, 14 after the master, 12 at 16 kbit/s, with every change of key found as written and repeated notes the weak spot; Part 58's coder at 16 kbit/s with its fallback band (37 wrong); the suite's order as made shorter than 99.8 % of random orders; Monochord counted (95 modules, 866 tests, 4.3 hours of sound). Heard and seen: the suite, ten minutes, every Variation for 8.5 seconds; then Variation 1 again. Variation 68: the suite itself. Frontier: why simple ratios sound good: separating the ear's part from the culture's. Reading: Bach, Goldberg Variations; Müller, Fundamentals of Music Processing; Böck & Widmer (2013); McDermott et al. (2016).

Build the film

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

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

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