♪Music, Built

Act II · Notes

Part 14 of 68

Melody

Foundationsstarts at this level37 min of film14 chaptersprerequisites: none

What do melodies do, which of those things would any string of notes in a small range do anyway, and can a machine learn to expect the next note?

Textbooks have said for four hundred years that a leap should be followed by a step back. The part tests that on fifty-four tunes that half the world can sing, and then on the same tunes with their notes shuffled: the shuffled ones obey the rule more often. A melody is first a contour, which listeners keep before the intervals; it is the same tune in any key, and eight moves of up, down and repeat tell all fifty-four apart. Half of all moves are steps, a quarter repeats and a quarter leaps; steps mostly fall and fourths mostly rise; the ear splits a line that leaps too far into two streams. A tune fits in an octave and lives near its middle. Phrases are arches about a breath long that end lower than they began. Then the leap rule is explained: a leap away from the middle of a small range lands near its edge, and the next note is probably back toward the middle, as it is for a die; real tunes and shuffled ones both turn back after leaps away from the middle and carry on after leaps toward it (von Hippel and Huron, 2000). What chance does not explain is the rest: gap-fill in part, momentum after a step, leaps that land on the notes of the home chord, tendency tones (7 to 1, 4 to 3, 6 to 5), repetition and sequence, and phrases that end as questions until the last one answers on the first degree. A note carries 4.3 bits if nothing is known, 3.2 given which notes are common and 2.6 given the note before; patterns of moves follow Zipf's law. A model that only counts what followed what is surprised by the Tune exactly once, at its leap of a fifth, and finds a minor-key tune from another tradition hardest of all. Speech has its own melody, which a song must respect. The frontier is predicting what a listener expects, and what makes a tune stick. The Tune's first phrase is played eight ways.

What you need. Part 4 for streaming and pitch; Part 10 for contour codes; Part 11 for rhythm and stress; Part 12 for scale degrees; Part 13 for the home chord and the tritone. Probability: conditional probability, regression to the mean, entropy in bits.

Ideas, mathematics and history
contour, steps and leaps, the arch, gap-fill and regression to the mean, motif and sequence, entropy and expectation
What we build, compute and hear
an n-gram model of folk melody; the Tune's surprise, note by note

What you will be able to do

Foundations

  • Describe a melody by its contour, moves, range and phrase shapes.
  • Name the tendency tones of a major scale and say where each goes.
  • Mark a tune's phrases, its repeats and its sequences, and write its plan in letters.

Full course

  • Test a claimed regularity of melody against shuffled notes and against a random walk in the same range.
  • Compute the chance that a die turns back after a rise, and explain the leap rule by regression to the mean.
  • Train a variable-order Markov model on a corpus and read a tune's information content in bits.

Research

  • Separate what follows from range and step size from what needs a composer.
  • Say why a model's surprise depends on the music it was trained on.

Practice

  • Write a singable tune: within an octave, mostly steps, with a peak and a repeated motive.
  • Set words so that stress, or tone, agrees with the melody.
  • Use a contour code to find a tune from a hummed fragment.

Contents

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

  1. 0A rule that noise obeysFoundations2 min
  2. 1The shape of a tuneFoundations3 min
  3. 2Small stepsFoundations3 min
  4. 3Room to singFoundations2 min
  5. 4The archFoundations2 min
  6. 5The rule that chance obeysResearch4 min
  7. 6Where notes want to goFull course3 min
  8. 7Saying it twiceFoundations2 min
  9. 8Question and answerFoundations1 min
  10. 9How much news is in a note?Full course3 min
  11. 10A model that is surprisedFull course3 min
  12. 11Words and tunePractice2 min
  13. 12Frontier: predicting the listenerResearch3 min
  14. Variation 14, recap and problemsAll tracks4 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.

A rule that noise obeysFoundations2 min

Open a textbook on writing melodies and you will find a rule that is four hundred years old. After a leap, turn back. Jump up, and then step down. Jump down, and then step up. It sounds like craft: advice that good composers follow. So let us test it. This series now has a small library: mostly Western traditional tunes in hand-entered versions that many listeners may sing, about nineteen hundred notes. In them there are leaps of a minor third or more. And when a tune moves on from a leap, it turns back times in a hundred. The rule holds.

Now a control experiment. Take the same tunes, and shuffle each one's notes into a random order. Every note is still there. Their sequential design is disrupted, while pitch-duration pairs and the assigned phrase boundaries remain. Here is the Tune; and then the Tune, shuffled.

Nobody composed that. Yet count the leaps in the shuffled tunes, and they turn back times in a hundred: more often than the real ones do. Noise obeys the rule better than music does. Reversal frequency alone therefore cannot establish intentional craft.

That is the question of this part. Part 13 stacked notes into chords; a melody is notes in a line, and people have been writing rules for it for centuries. We will ask, of each rule: do melodies really do this? And would they do it anyway, by arithmetic alone? We begin with what a melody is: before anything else, a shape. Then how tunes move: in small steps, in a small range, in arches. Then the leap rule, and why noise obeys it. Then patterns not fully explained by these particular chance controls: notes that lean, patterns that repeat, phrases that ask and answer. We measure how much information a note carries. And we build a model that learns from tunes and offers testable predictions about learned expectation.

1The shape of a tuneFoundations3 min

What do you remember of a melody?

Start with a puzzle for your ear. One famous tune, disguised twice. In A, every note has the right name, but is in the wrong octave. In B, every nonzero interval is expanded, but the notes go up and down as the tune does. Which one can you name?

You may find B easier to recognize than A; we have not measured listener responses to these particular examples. It is Frère Jacques.

In A, every note had the right name. Only the octaves were scrambled, and that destroyed the ups and downs: just of the thirteen moves kept their direction. In B, every interval was doubled, so every nonzero interval changed, while repeats remained repeats; but the shape was. Diana Deutsch did the first experiment of this kind in 1972, and Jay Dowling showed soon after that contour can be particularly useful for recognizing unfamiliar melodies: the pattern of ups and downs. Exact intervals come later, with familiarity.

So a melody is not a list of notes. It is first of all a shape in time. Then, hung on that shape, exact intervals in a scale. Alongside them is rhythm, which Part 11 took apart. This part is about the shape: what shapes melodies have, and why they have them.

There is a fact about melody so familiar that it is easy to miss. Here is the Tune's first phrase starting on C; and then starting on F sharp.

The two versions do not have a single note in common, while many listeners recognize the same tune. A child can sing a song back in a different key without noticing. So a melody is not its notes. It is a pattern of relations between notes: the same shape, with the same intervals, wherever it is put. Very few people can name a note they hear; nearly everyone can recognise a tune.

How much does contour alone tell you? Write a tune as nothing but ups, downs and repeats. In 1975 Denys Parsons published a directory of thousands of themes indexed this way, so that you could look up a tune you could only hum. Try it on our library. With five moves of contour, of the tunes are already unlike every other. With , all of them are. Three symbols, a handful of moves, and a tune is identified. Contour is one useful retrieval feature, alongside intervals, rhythm and learned audio representations.

2Small stepsFoundations3 min

How does a tune move?

Take every move from one note to the next in the fifty-four tunes: moves. Half of them are steps: one or two semitones. A quarter are repeats of the same note. A quarter are leaps, and nearly all of those are small: moves in a hundred are a fifth or less. The average move is semitones.

And there are two asymmetries. Steps go down more often than up: the commonest move of all is a whole tone down, of them against up. Leaps of a fourth go the other way: up against down. Melodies climb by leaping, and come down by walking. The same pattern has been counted in collections of thousands of songs, from Europe, China, southern Africa and native America.

Why steps? One reason is the voice: nearby pitches often require less vocal adjustment, though pitch depends on tissue tension, length and aerodynamic conditions. The other reason is the ear. Listen to a three-note gallop, low, high, low, played fast. First with the middle note a tone away; then with it nine semitones away.

The first is one line that gallops. The second splits into two lines, a high one and a low one, and the gallop is gone. Albert Bregman named this auditory streaming: at speed, the ear groups sounds by their nearness in pitch. Wide rapid alternation can encourage stream segregation; tempo, timbre, attention and exposure also matter. Bach used the effect on purpose, to make one violin sound like two.

An ear question. Two melodies made by chance, on the white keys. Which one sounds more like a tune: A or B?

B, for most listeners. In A, each note was drawn at random from the octave. In B, each move was drawn at random from the moves that our fifty-four tunes make: mostly steps and repeats. Neither was composed. Small moves help these examples cohere, but do not by themselves explain melody or guarantee a listener preference.

3Room to singFoundations2 min

How much room does a tune need?

How much room does a melody use? Measure each tune from its lowest note to its highest. The middle value is exactly an octave. of the fit within an octave, and none needs more than an octave and a fourth. Comfortable vocal range varies by person, register and training; this corpus does not define a universal limit.

At one end is Hot Cross Buns: three notes, a major third from bottom to top. At the other, Silent Night, which spans an eleventh; and the Star-Spangled Banner, whose first two lines already cover a tenth, and the whole song an octave and a fifth, which can make it challenging for group singing. Listen to the narrowest, and then to the start of the widest.

Within its range, a tune does not spread itself evenly. It lives near its middle. Measure every note from the middle note of its own tune. notes in a hundred lie within a tone or so of the middle; singers call the band where a melody mostly sits its tessitura. The extremes are visited rarely: the top note of a tune is about one note in , and it is an event. Keep this picture in mind: a small range, mostly occupied near its middle. It is about to explain the rule that we began with.

4The archFoundations2 min

What shape is a phrase?

Melodies come in phrases, often shaped as singable units, with boundaries marked here by hand. Here are two phrases of Beethoven's Ode to Joy. Watch the shape of each.

Up, and back down. And then a second, smaller arch, which stops one step short of home.

Is that typical? Our tunes have phrases. Sort each one by comparing its first note, the average of its middle, and its last note. The commonest shapes are falling, , and the arch, . Then rising, . The valley, down and then up, is the rarest of the four.

Now average all the phrases together. What emerges is an arch: up by about a semitone in the first third, then down, ending half a semitone below where it began. David Huron found the same arch in 1996, in six thousand European folk songs. Speech often shows pitch declination, influenced by linguistic structure, prosody and physiology; it is not simply air running out. A phrase of melody is shaped like a breath: it rises as it sets out, and it sinks as it ends.

Here is a piece of advice that is often given with the arch: save the highest note of a melody for about two thirds of the way through. Test it. In our tunes, the top note first arrives, in the middle case, only a quarter of the way through. In of the it comes in the first fifth of the tune, and only wait until the second half. These tunes climb early, and spend the rest of their time coming down. The advice may suit a symphony. It does not describe the median first-peak position of this selected corpus.

5The rule that chance obeysResearch4 min

Why do leaps turn back?

Back to the leap rule. Why would shuffled notes obey it? Forget music for a moment. Here is an urn full of notes: many from the middle of an octave, fewer from the edges, as in a real tune. Draw twenty-four of them, each with no memory of the one before.

Look at a leap in that. A big leap away from the middle has to land near an edge of the range. And from out there, where is the next note likely to be? Back toward the middle, because that is where most of the notes in the urn are. Not because of the leap. Statisticians call this regression to the mean: after an extreme value, the next is probably less extreme. Francis Galton found it in the heights of parents and children. Here it is in a melody that nobody wrote.

You can check the argument with a die, and no music at all. Roll it three times. Suppose the second roll is higher than the first by two or more: a leap up. There are ways that can happen, and on average the second roll is then a . Now the third roll. It is lower in of those cases, and higher in only . Excluding repeated third rolls, the next move turns back times in a hundred. A die has no taste and no training. It has a range, from one to six, and that is enough.

That gives a way to tell the two explanations apart. If composers turn back after leaps as a matter of craft, they should do it wherever the leap lands. If it is only regression to the mean, it should depend on where the leap lands. So, a prediction. Take a leap that lands nearer the middle of the tune's range than it started. Does the next note turn back, or carry on?

It carries on: four times in five. When a leap heads away from the middle, the tune turns back times in a hundred. When it heads toward the middle, only . And shuffled notes show exactly the same pattern. In the year 2000, Paul von Hippel and David Huron showed this in hundreds of melodies from Europe, Africa, China and native America. The textbook rule is true as a description. As advice it is unnecessary: bounded random sequences can show it without such a rule; designed melodies need not.

Notice what just happened, because it is the method of this whole part. A regularity in music is not yet a fact about composers. First ask what chance would do, under the same constraints. A residual suggests structure not captured by the control, not proof of an intention. And here the leftover points the other way: real tunes turn back times in a hundred, chance . If anything, composers resist the rule. A real melody holds its direction longer than a shuffled one would.

6Where notes want to goFull course3 min

Does each note have a direction?

Does any rule of melody survive that test? Here is a candidate. In 1956 Leonard Meyer proposed that a leap opens a gap, and that the melody then fills the gap, by steps, in the other direction. Count how often a leap of a fourth or more is followed by steps back into the gap. In our tunes: leaps in a hundred. In melodies made by chance from the same moves, confined to the same range: . So gap-fill is partly arithmetic. But only partly. Something is left over.

Two more habits pass the test. The first is momentum. After a step down, the next move is down again times in a hundred; chance would give . After a step up, the tune keeps climbing times, against . A line that is walking tends to keep walking, especially downhill. The second is where leaps land. A leap arrives on the first, third or fifth degree of the scale times in a hundred; a step, only . Tunes walk through the scale, and jump along the chord. Part 13's triad is inside the melody.

The clearest leftover is that the notes of a scale are not equal. Count where each degree goes next. The seventh rises to the first times in a hundred. The fourth falls to the third times. The sixth falls to the fifth times. The second falls to the first .

These are the tendency tones. Degrees two, four, six and seven lean toward their neighbours one, three and five: the notes of the home chord of Part 13, where our tunes spend percent of their time. Shuffling removes these sequential tendencies while retaining note frequencies. These are learned tonal tendencies in this corpus; scale membership does not physically compel resolution.

Try your ear. One phrase, with three different last notes. Which one sounds finished: A, B or C?

C. In A the phrase stayed on the second degree; in B it fell to the seventh; in C it came home to the first. In our tunes, last phrases in a hundred end on the first degree. Other endings can sound open in the tonal context illustrated here, and in the next chapter but one we will hear that used.

7Saying it twiceFoundations2 min

Why do tunes repeat themselves?

Repetition can make melodies easier to learn; literal repetition is not necessary for remembering one. Listen to how these two tunes are built: a short pattern, and then the same pattern again, one step higher or one step lower. Musicians call that a sequence.

In the first, six notes, and then the same six a step up. In the second, a longer pattern, and then the same pattern a step down. The second time you hear the shape, you already know it; only the level is new.

Repetition is everywhere in the fifty-four. of the phrases are exact repeats of an earlier phrase: more than one in five. of the tunes contain a sequence, and repeat a short pattern immediately. Here is Frère Jacques compared with itself, note against note, with a dot wherever two moments match. The stripes beside the main diagonal are repeats: every phrase of this tune is sung twice.

The psychologist Elizabeth Margulis has argued that this is what most separates music from speech. Repeated phrases can support recognition, but repetition alone does not define music. A motive is the smallest thing in a tune that can be said twice; and chance can repeat too, but recurrence beyond a suitable baseline can reveal additional structure.

Give each phrase of a tune a letter, and give a phrase you have heard before the letter it had. The Tune is A, B, C, C, A, B: it goes out, and it comes back. Frère Jacques says everything twice: A, A, B, B, C, C, D, D; though working as a round also requires compatible overlapping entries. Au clair de la lune is A, B, A, B, then something new, then A, B again. Statement, departure, return. With a handful of letters you have the plan of a tune, and in Part 21 the same letters will describe a symphony.

8Question and answerFoundations1 min

How does a tune breathe?

Phrases have a typical size. in a hundred of ours last eight beats, and most of the rest six, four or twelve: a duration that depends on tempo and the chosen beat unit. And the last note of a phrase is long: on average times as long as the others. Breathing and musical phrasing can both contribute, and a listener uses the long note to hear that a phrase has ended. Speech does the same, and linguists call it final lengthening.

And phrases come in pairs. Here is the selected paired-phrase excerpt of Beethoven’s tune: two long phrases. Listen to the last note of each.

The first phrase ends on the second degree: open, a question. The second is the same music, and ends on the first: an answer. Musicians call such a pair an antecedent and a consequent. In our tunes, a phrase in the middle may end on the fifth degree, the first, the third or the second. The final phrase ends on the first times in a hundred. This question-and-answer description is useful here, rather than a definition of all melody.

9How much news is in a note?Full course3 min

How predictable is a melody?

We can put a number on all of this. Claude Shannon's measure of information, from 1948, is the bit: the answer to one yes-or-no question. Our tunes use different notes. If every note were as likely as every other, each would carry bits. But they are not equally likely. Knowing only which notes are common brings it down to . Knowing the previous note as well: bits. So about percent less cross-entropy than the uniform baseline: it could have been predicted from the scale and the note before.

Look further back, two notes, three, and on this small library it gets no better. The model begins to memorise particular tunes, when what it needs is habits that all tunes share. With thousands of melodies to learn from, longer memories do pay; with fifty-four, one note of memory is the best we can use.

Shannon had a way to make bits concrete: a guessing game. Hide the next letter of a sentence, and count how many guesses a reader needs. Play it on melody. Show a model a tune it has never met, one note at a time, and ask it to guess the next. Its first guess is right times in a hundred. Within three guesses it is right times. Blind luck would manage in a hundred at the first attempt. That gap is what the word predictable means; and it illustrates predictive structure; singing a repeated verse also relies on learning its melody.

One more regularity. Count every pattern of two moves in a row, and rank the patterns from the commonest to the rarest. A few patterns do most of the work: the same note three times; two steps down. Most patterns are rare. On logarithmic axes, the ranks fall close to a straight line, with a slope of about minus . The frequencies of words in a language fall on such a line too; it resembles a Zipf-like rank-frequency trend; a short approximately straight plot does not establish a power law. Melodies, like languages, are made from a small common vocabulary and a long tail of rarities.

10A model that is surprisedFull course3 min

Can a machine expect the next note?

Now build the listener. Give Monochord fifty-three tunes, everything except the Tune, and let it count. After these two notes, what came next, and how often? It blends these counts with counts after the last note alone; and with overall note frequencies. Unseen contexts rely on the shorter contexts. That is a variable-order Markov model. Variable-order statistical prediction is one ingredient in Marcus Pearce’s fuller model of melodic expectation, which he called IDyOM.

Ask it what follows C, C. It says: probably another C, or a D, about one chance in three each. It has never heard of Twinkle, Twinkle, Little Star.

Now play it the Tune, and measure its surprise at every note, in bits.

The spike is the third note: the leap of a fifth, from C up to G. bits: the model gave that note about three chances in a hundred. Everything after it is cheap: repeats, and steps downward, around two bits each. The Tune spends its surprise at once, and then walks home. A great many melodies are built that way: one bold move near the start, and the rest of the phrase making sense of it.

Do the same for every tune in the library: train on the others, and score the one left out. The Tune, at bits a note, is number of fifty-four: ordinary. The most predictable is Beethoven's Ode to Joy, almost nothing but steps. The least predictable is a Russian tune in a minor key. Listen to the opening of each.

Nothing is wrong with the second tune: millions of people know it by heart. But our model grew up almost entirely on tunes in major keys, and a minor-key melody from somewhere else surprises it at every turn. This also exposes a limitation of this training distribution. It is the most important thing the method shows. A listener’s exposure helps shape expectation, alongside other perceptual and contextual factors, and a tune that is obvious in one tradition is strange in another.

A model that predicts can also invent: draw each next note from its own expectations. Here are three melodies it made up: with no memory, with one note of memory, with two.

With no memory, the notes are the right notes and the result is nonsense. With memory, it begins to step and to repeat, and for a moment it sounds like something. It has no explicit phrase, contour-plan or tonal-home representation, though some generated samples may show those features by chance. Those are shapes longer than two notes, and a model has to be built to look for them.

11Words and tunePractice2 min

What does speech do to a melody?

Many melodies carry words, and words have melodies of their own. In Mandarin Chinese the syllable ma means mother, hemp, horse or to scold, depending on the shape of its pitch: level, rising, dipping or falling. Here are those four shapes on a single vowel, from Part 8's voice.

So what happens when such a language is sung? The tune and the tones can collide, and a word can turn into another word. In Cantonese, which has six tones, songwriters avoid the collision: in a study of Cantonese songs by Patrick Wong and Randy Diehl, the melody moved in the same direction as the speech tones about nine times in ten. English text setting often coordinates lexical stress and musical accent, with deliberate exceptions: strong syllables on strong beats, as in Part 11. Every song is a negotiation between two melodies: the one in the music, and the one already in the words.

Even without tones, speech has a melody. Its pitch glides continuously, rises on the words that matter, and sinks through the sentence as the breath runs out: the same arch that we found in phrases. Song differs in two ways. Pitch may dwell near relatively stable targets, while vibrato, slides and melismas remain common, and the places where it holds are the steps of a scale. The line between the two is thin. Diana Deutsch found in 2011 that a spoken phrase, simply repeated a few times in a loop, begins to sound sung: listeners can perceive greater musical pitch organization; the original waveform is unchanged. For suitable speech excerpts, repetition can induce a speech-to-song illusion; it is not guaranteed for all speech or listeners.

12Frontier: predicting the listenerResearch3 min

What does a listener expect, and why does it matter?

How good is our model? Compare three predictors. The counting models use leave-one-tune-out evaluation; the proximity baseline is optimized on this same corpus, so its score is an optimistic in-sample reference, not an independent held-out test. One knows only which notes are common: bits a note. One knows only that the next note is probably near the last one, which is most of what the old rules of melody say: also . The counting model: . The learned model scores lower here, though this small comparison does not establish performance across traditions or datasets.

Pearce's full model learns from hundreds of melodies, and tracks scale degree and rhythm as well as pitch. Its predictions correlate with expectation judgments in reported experiments; and related measures correlate with some event-related brain responses, measured at the scalp. Expectation is not a figure of speech. It can be computed, and it can be seen.

What about memory? A few things are well established. Listeners keep contour and rhythm first, and exact pitches last. Melodies can often be recognized after transposition, with effects of register, timbre and listener experience. And in 2017 Kelly Jakubowski and colleagues compared tunes that people report getting stuck in their heads with similar tunes that do not. The sticky ones were faster, and had the most common overall shapes, the arch above all; but they also had one or two leaps that were out of the ordinary. A familiar shape, with a small surprise in it. That is very nearly a description of the Tune.

Neural networks trained on far more music now predict a little better still. But prediction is not the whole of melody. Some experiments find an intermediate-predictability preference, dependent also on uncertainty, listener and stimulus: neither obvious nor random. Experiments by Benjamin Gold and colleagues in 2019 found that liking follows an upside-down U. Predicting which tunes will be remembered remains difficult; models can explain some variance without perfectly predicting individuals. One melody lodges in the memories of millions after a single hearing, while a thousand others, equally well formed, are gone by the next morning. Our model assigns different average likelihoods to these tune and shuffled examples; we have not established a general tune-versus-noise classifier. It cannot tell a good tune from a dull one. Likelihood alone is not a complete theory of musical quality or memory.

Variation 14, recap and problemsAll tracks4 min

Every part ends by doing something to the Tune with what it has built. This part built ways to change a melody, and a model that expects. And changing this particular melody has a history: around 1781–82 Mozart wrote twelve variations for piano on Ah, vous dirai-je, maman, and his first one does what our third version does: it fills the tune with running notes. So here is the Tune's first phrase, and then that phrase decorated three ways: with neighbour notes, with its leap filled in by a run, and with turns. Then upside down, and backwards. And then the model takes over: the seven notes it most expects to follow the first phrase, and the seven it expects least. Above each version is its surprise, in bits per note.

Row fourteen of the ledger. seconds. The measurement: the continuation the model expected costs bits a note, and is a little dull. The one it expected least costs , and is nonsense. The Tune itself, at , sits between them, where tunes live.

What did we find? A melody is first a contour, and listeners keep the contour before the intervals. In this corpus about half the moves are steps, most tunes fit an octave, and notes cluster near their medians. The average of our hand-segmented phrases is an arch ending slightly lower; individual phrases take many shapes. Leaps turn back because of regression to the mean: shuffled notes do it more than real tunes. What is left over for the composer is tendency tones, repetition, and phrases that ask and answer. And a note carries about two and a half bits of news; a model that only counts has its largest early surprise at the Tune’s leap; the other notes also have nonzero surprise.

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? At once: the next part turns tendency tones into a key, with a home. Then two melodies at once, which is counterpoint. Motive and sequence grow into form. Raga and maqam give melodic organization a central role alongside rhythm, text, performance and other practices. Expectation returns as a theory of musical emotion. And the counting model of this part is the ancestor of the machines that compose.

And in practice. A songwriter keeps a tune within an octave, saves the top note for the chorus, and says the hook twice. A teacher starts children on three notes and steps. A lyricist puts strong syllables on strong beats, and in a tone language follows the tones. And an analyst, before calling anything a composer's habit, shuffles the notes and counts again.

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

One thing has been in every chapter without being explained. In this selected corpus, about ninety-six percent end on the first scale degree. Notes lean toward it. Phrases ask questions that only it can answer. The tonal tunes studied here have an identified home; not every kind of melody requires one. What makes one note out of seven the home, how does a listener find it within a few seconds, and can a piece of music leave home and come back? Next time. Part 15: Key.

Where it goes next. Part 15 turns tendency tones and the note that phrases end on into a key. Two melodies at once are Parts 16 and 20; motive and sequence grow into form in Part 21; melody is the whole art in Parts 34 and 35; expectation becomes a theory of emotion in Part 46; and the counting model is the ancestor of the composing machines of Part 65.

Key results

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

Moves in 54 tunes\(\displaystyle \text{steps } 50\%,\ \text{repeats } 25\%,\ \text{leaps } 25\%;\quad\allowbreak \overline{|\Delta|} = 2.0 \text{ semitones}\)
After a leap, turning back\(\displaystyle \text{tunes } 63\%,\quad\allowbreak \text{shuffled } 79\%;\qquad\allowbreak \text{away }\allowbreak \text{from }\allowbreak \text{the }\allowbreak \text{middle } 75\%,\ \text{toward }\allowbreak \text{it } 20\%\)
A die\(\displaystyle P(X_3 < X_2 \mid X_2 - X_1 \ge 2,\ X_3 \ne X_2) = \tfrac{4}{5}\)
Information in a note\(\displaystyle \log_2 20 = 4.3 \ \to\ H_0 = 3.2 \ \to\ H_1 = 2.6 \text{ bits}\)
Surprise\(\displaystyle h(x_t) = -\log_2 p(x_t \mid x_{t-n}, \dots, x_{t-1})\)
Zipf's law for pairs of moves\(\displaystyle f(r) \propto r^{-1.3}\)

Try it

Lab 14 · Melody, counted: steps, leaps, chance and surprise

Describe a tune by its moves, range and phrase shapes; test the rule that leaps turn back against shuffled notes and against a die; train a model of the next note on every tune but one and read that tune's surprise; and tell real, shuffled and made-up melodies apart by ear.

Figure produced by Lab 14: Melody, counted: steps, leaps, chance and surprise
Produced by the lab below, seed 0, in 0.8 s.
python -m videos.music.labs 14 needs numpy, scipy, matplotlib · download lab14.py · source on GitHub
Happy Birthday to You, two phrases, in degrees                5 5 6 5 1 7 5 5 6 5 2 1
its moves, in semitones                                       +0 +2 -2 +5 -1 -4 +0 +2 -2 +7 -2
steps, repeats, leaps                                         6, 2, 3 of 11;  range 7 semitones
the shape of each phrase                                      rising; rising
54 tunes, 1898 notes                                          steps 50%, repeats 25%, leaps 25%;  mean move 1.98 semitones
median range; phrases that are arches                         12 semitones;  79 of 275
leaps of 3+ semitones that turn back: all                     tunes 63%  (446 leaps);  shuffled 79%
leaps of 3+ semitones that turn back: departing               tunes 75%  (148 leaps);  shuffled 95%
leaps of 3+ semitones that turn back: approaching             tunes 20%  (62 leaps);  shuffled 22%
leaps of 3+ semitones that turn back: crossing                tunes 78%  (156 leaps);  shuffled 87%
a die of 6 sides: after a rise of 2 or more                   60 cases; the next roll is lower in 40, higher in 10:  4/5 = 80% turn back
   by where the leap lands (k): (k-1)/(n-1) of moves go down  3: 2/5,  4: 3/5,  5: 4/5,  6: 1
Frère Jacques: bits a note (order 2)                          2.18;  most surprising: note 21, G after E C  (7.2 bits)
cross-entropy, each tune predicted from the rest              order 0: 3.20;  order 1: 2.56;  order 2: 2.59;  order 3: 2.80 bits a note
ear problem, the eight melodies (listen first)                made up by the model;  real (Joy to the World);  real (Ode to Joy);  real (Oh! Susanna);  made up by the model;  shuffled (She'll Be Coming Round the Mountain);  real (The First Noel);  shuffled (Lightly Row (Hänschen klein))

Leaps turn back more often in shuffled tunes than in real ones: the rule is regression to the mean, which a die shows exactly. What chance does not produce is repetition, tendency tones and phrase endings; and a model that only counts what follows what is already surprised where a listener is.
The code (115 lines; it asserts its own result)
"""Lab 14: count what tunes do, shuffle them and count again, prove the leap rule for a die, and train a model that is surprised."""

from fractions import Fraction

import numpy as np

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

TITLE = "Melody, counted: steps, leaps, chance and surprise"
GOAL = ("Describe a tune by its moves, range and phrase shapes; test the rule that leaps turn back against shuffled notes "
        "and against a die; train a model of the next note on every tune but one and read that tune's surprise; and tell "
        "real, shuffled and made-up melodies apart by ear.")
TASKS = [
    "Set SKIP to 5 (a fourth or more) and to 7. Does the gap between real and shuffled tunes grow or shrink? Why would larger leaps land further from the middle?",
    "Set LEFT_OUT to 'Frère Jacques', then to 'Greensleeves'. Which note surprises the model most in each, and why is the second tune so much harder for it?",
    "Set ORDER to 0, 1, 2 and 3. Where is the cross-entropy lowest? Remove half of the corpus (CORPUS = CORPUS[::2] in run) and look again.",
]
TUNE = "Happy Birthday to You"      # Problem 1
SKIP = 3                            # a leap is this many semitones or more
SIDES = 6                           # Problem 2: a die of this many sides
LEFT_OUT = "Frère Jacques"          # Problem 4
ORDER = 2
SR = 48_000
NAMES = {-12: "C,", -10: "D,", -8: "E,", -7: "F,", -5: "G,", -3: "A,", -1: "B,", 0: "C", 2: "D", 4: "E", 5: "F", 7: "G", 9: "A", 11: "B", 12: "C'", 14: "D'", 16: "E'", 17: "F'"}


def run(seed=0):
    rng = np.random.default_rng(seed)
    lab = labs.Lab()
    corpus = M.corpus()
    by = {m.name: m for m in corpus}

    # 1. Problem 1: one tune, described
    m = by[TUNE]
    two = M.Melody(m.name, m.pitches[:m.phrase_ends[1]], m.beats[:m.phrase_ends[1]], m.phrase_ends[:2])
    iv = M.intervals(two)
    lab.row(f"{TUNE}, two phrases, in degrees", " ".join(str(d) for d in two.degrees()))
    lab.row("its moves, in semitones", " ".join(f"{i:+d}" for i in iv))
    lab.row("steps, repeats, leaps", f"{sum(1 <= abs(i) <= 2 for i in iv)}, {sum(i == 0 for i in iv)}, {sum(abs(i) >= 3 for i in iv)} of {len(iv)};  range {M.span(two)} semitones")
    lab.row("the shape of each phrase", "; ".join(M.contour_shape(p) for p in two.phrases))

    # 2. the whole corpus
    s = M.shares(corpus)
    lab.row(f"{len(corpus)} tunes, {sum(len(t) for t in corpus)} notes", f"steps {100 * s['step']:.0f}%, repeats {100 * s['repeat']:.0f}%, leaps {100 * s['leap']:.0f}%;  mean move {s['mean_size']:.2f} semitones")
    lab.row("median range; phrases that are arches", f"{np.median([M.span(t) for t in corpus]):.0f} semitones;  "
            f"{sum(M.contour_shape(p) == 'arch' for t in corpus for p in t.phrases)} of {sum(len(t.phrases) for t in corpus)}")

    # 3. the leap rule against chance
    real = M.post_skip(corpus, SKIP)
    chance = [M.post_skip(M.shuffled(corpus, k), SKIP) for k in range(100)]
    for kind in ("all", "departing", "approaching", "crossing"):
        lab.row(f"leaps of {SKIP}+ semitones that turn back: {kind}", f"tunes {100 * real[kind]['share']:.0f}%  ({real[kind]['n']} leaps);  shuffled {100 * np.mean([c[kind]['share'] for c in chance]):.0f}%")
    assert real["all"]["share"] < np.mean([c["all"]["share"] for c in chance])

    # 4. Problem 2: a die, exactly
    up = [(a, b, c) for a in range(1, SIDES + 1) for b in range(1, SIDES + 1) for c in range(1, SIDES + 1) if b - a >= 2]
    fall, rise = sum(c < b for _, b, c in up), sum(c > b for _, b, c in up)
    lab.row(f"a die of {SIDES} sides: after a rise of 2 or more", f"{len(up)} cases; the next roll is lower in {fall}, higher in {rise}:  {Fraction(fall, fall + rise)} = {100 * fall / (fall + rise):.0f}% turn back")
    by_landing = {k: Fraction(k - 1, SIDES - 1) for k in range(3, SIDES + 1)}
    lab.row("   by where the leap lands (k): (k-1)/(n-1) of moves go down", ",  ".join(f"{k}: {v}" for k, v in by_landing.items()))

    # 5. Problem 4: a model trained on every tune but one
    others = [t for t in corpus if t.name != LEFT_OUT]
    model = M.NGram(ORDER).fit(others)
    target = by[LEFT_OUT]
    bits = model.surprise(target)
    k = int(np.argmax(bits[1:])) + 1
    lab.row(f"{LEFT_OUT}: bits a note (order {ORDER})", f"{bits.mean():.2f};  most surprising: note {k + 1}, {NAMES.get(target.pitches[k], target.pitches[k])} after "
            f"{' '.join(NAMES.get(p, str(p)) for p in target.pitches[max(k - 2, 0):k])}  ({bits[k]:.1f} bits)")
    lab.row("cross-entropy, each tune predicted from the rest", ";  ".join(f"order {o}: {M.cross_entropy(corpus, o):.2f}" for o in range(4)) + " bits a note")

    # 6. Problem 3, for the ear: real, shuffled and made-up melodies
    full = M.NGram(2).fit(corpus)
    kinds, clips = [], []
    c4 = 261.6255653005986
    for _ in range(8):
        kind = ("real", "shuffled", "model")[int(rng.integers(0, 3))]
        src = corpus[int(rng.integers(0, len(corpus)))]
        n = min(src.phrase_ends[1], 16)
        if kind == "real":
            p, b = src.pitches[:n], src.beats[:n]
        elif kind == "shuffled":
            idx = rng.permutation(n)
            p, b = [src.pitches[i] for i in idx], [src.beats[i] for i in idx]
        else:
            p, b = full.generate(n, start=(0,), seed=int(rng.integers(0, 10_000))), src.beats[:n]
        y, t = np.zeros(int((sum(b) * 0.36 + 1.0) * SR)), 0.0
        for pitch, beats in zip(p, b):
            tone = organ_tone(c4 * 2 ** (pitch / 12), beats * 0.36 + 0.25, partials=5, decay=4.0)
            i = int(t * SR)
            y[i:i + len(tone)] += tone[: len(y) - i]
            t += beats * 0.36
        clips.append(Clip(y, SR).fade(0.01, 0.1).at_level(-20.0))
        kinds.append(f"{kind} ({src.name})" if kind != "model" else "made up by the model")
    lab.audio = concat(clips, gap=1.0)
    lab.row("ear problem, the eight melodies (listen first)", ";  ".join(kinds))

    fig, (a, b) = labs.figure(2)
    hist = M.interval_histogram(corpus)
    a.bar(list(hist), list(hist.values()), color=[labs.GOLD if 1 <= abs(i) <= 2 else "#888" for i in hist])
    a.set_title("Every move in the corpus")
    a.set_xlabel("semitones from one note to the next")
    a.set_ylabel("how often")
    b.bar(range(len(bits)), bits, color=[labs.GOLD if i == k else "#888" for i in range(len(bits))])
    b.set_title(f"Surprise, note by note: {LEFT_OUT}")
    b.set_xlabel("note")
    b.set_ylabel("bits")
    lab.fig = fig
    lab.note = ("Leaps turn back more often in shuffled tunes than in real ones: the rule is regression to the mean, which a die "
                "shows exactly. What chance does not produce is repetition, tendency tones and phrase endings; and a model that only "
                "counts what follows what is already surprised where a listener is.")
    return lab

Now change it

  1. Set SKIP to 5 (a fourth or more) and to 7. Does the gap between real and shuffled tunes grow or shrink? Why would larger leaps land further from the middle?
  2. Set LEFT_OUT to 'Frère Jacques', then to 'Greensleeves'. Which note surprises the model most in each, and why is the second tune so much harder for it?
  3. Set ORDER to 0, 1, 2 and 3. Where is the cross-entropy lowest? Remove half of the corpus (CORPUS = CORPUS[::2] in run) and look again.

Problems, with solutions

Try each problem before opening its solution.

  1. One tune, described. Write the first two phrases of Happy Birthday as scale degrees. Give every move in semitones, the share that are steps, the range, and the shape of each phrase.

    Solution

    5 5 6 5 1 7 / 5 5 6 5 2 1, where the 5s, 6s and the 7 lie below the tonic (the tune begins on the fifth degree below it). The moves are 0, +2, −2, +5, −1, then −4 across the phrase break, then 0, +2, −2, +7, −2. Of eleven moves six are steps, two are repeats and three are leaps; the range is a perfect fifth below the tonic to a major second above: seven semitones in these two phrases (the whole tune spans an octave). Each phrase begins on its lowest note and ends above its average: both are "rising" in Huron's nine shapes. The lab prints all of this.

  2. The leap rule for a die. Notes are drawn independently and uniformly from 1, 2, …, n. Given that a leap has just gone up and landed on k, what is the chance that the next note is lower? Average over where upward leaps land, and explain the leap rule.

    Solution

    The next note is independent of everything before it, so it is lower than k with probability (k − 1)/n, higher with (n − k)/n and equal with 1/n; among the notes that move, the share that go down is (k − 1)/(n − 1), which is more than half as soon as k is above the middle. An upward leap of two or more can only land on 3, …, n, and lands high more often than low (there are k − 2 ways to arrive at k). For a six-sided die: 60 ways to rise by two or more; afterwards 40 falls, 10 rises and 10 repeats, so 4/5 of the moves turn back. Nothing here knows about leaps: a leap is evidence that the note is far from the middle, and a note far from the middle is usually followed by one nearer to it.

  3. Ear. The lab plays eight melodies: some are from the corpus, some have the same notes shuffled, some were made by the model. Say which is which.

    Solution

    The lab prints the answers. Shuffled melodies give themselves away by leaps in both directions and no repeated pattern; the model's by plausible steps that go nowhere: no arch, no long note at a phrase end, no return. Real tunes repeat themselves within a few seconds.

  4. Build. With melody.NGram, train on every tune but one and plot that tune's surprise. Which note of Frère Jacques surprises the model most? Then let the model also see rhythm, and see whether phrase endings get cheaper.

    Solution

    In the lab, with LEFT_OUT = "Frère Jacques" and a memory of two notes, the peak (7.2 bits) is the G that begins the third pair of phrases after "E, C": a leap of a fifth, as in the Tune. The second largest is the drop to the low G in "ding, dang, dong". To add rhythm, make the model's symbols pairs (pitch, duration) or run a second model on durations and add the bits; long notes at phrase ends then become predictable from the long note before them, and with a feature for position in the bar (as IDyOM's "viewpoints" have) the final tonic becomes cheap.

  5. ★ Which tunes stick? Among melodies of equal average surprise, which are remembered after one hearing? Propose a measurement that needs no listeners' opinions of quality.

    Where the frontier is. Recognition experiments (Halpern and Bartlett's reviews; Müllensiefen and Halpern 2014) find that tunes with rare motifs are recognised better and that familiarity ratings follow common features; involuntary recall ("earworms", Jakubowski and others 2017) favours fast tunes with common overall contours and unusual intervals; the Hooked on Music experiment (Burgoyne and others 2013) measured how fast listeners recognise a hook. A measurement without opinions: play each melody once, and after a delay test recognition against lures matched for surprise (the model's own samples). What predicts the hit rate once average surprise is held fixed: where in the phrase the surprise falls, how much is repeated, or how singable the range is, is not settled.

Notes and sources

Sources

Books: D. Huron, Sweet Anticipation: Music and the Psychology of Expectation (2006), chs. 5–6; D. Temperley, Music and Probability (2007); L. B. Meyer, Emotion and Meaning in Music (1956) and Explaining Music (1973); E. Narmour, The Analysis and Cognition of Basic Melodic Structures (1990); A. S. Bregman, Auditory Scene Analysis (1990); E. H. Margulis, On Repeat: How Music Plays the Mind (2014); D. Parsons, The Directory of Tunes and Musical Themes (1975); Y. R. Chao, "A system of tone letters", Le Maître Phonétique 45 (1930).

Papers: C. E. Shannon, "A mathematical theory of communication", Bell System Technical Journal 27 (1948), and "Prediction and entropy of printed English", 30 (1951); D. Deutsch, "Octave generalization and tune recognition", Perception & Psychophysics 11 (1972); W. J. Dowling, "Scale and contour: two components of a theory of memory for melodies", Psychological Review 85 (1978); P. G. Vos and J. M. Troost, "Ascending and descending melodic intervals: statistical findings and their perceptual relevance", Music Perception 6 (1989); D. Huron, "The melodic arch in Western folksongs", Computing in Musicology 10 (1996); P. von Hippel and D. Huron, "Why do skips precede reversals? The effect of tessitura on melodic structure", Music Perception 18 (2000); P. von Hippel, "Redefining pitch proximity: tessitura and mobility as constraints on melodic intervals", Music Perception 17 (2000); P. C. M. Wong and R. L. Diehl, "How can the lyrics of a song in a tone language be understood?", Psychology of Music 30 (2002); M. T. Pearce, The Construction and Evaluation of Statistical Models of Melodic Structure in Music Perception and Composition (PhD thesis, City University London, 2005), and "Statistical learning and probabilistic prediction in music cognition", Annals of the New York Academy of Sciences 1423 (2018); D. Deutsch, T. Henthorn and R. Lapidis, "Illusory transformation from speech to song", Journal of the Acoustical Society of America 129 (2011); K. Jakubowski, S. Finkel, L. Stewart and D. Müllensiefen, "Dissecting an earworm: melodic features and song popularity predict involuntary musical imagery", Psychology of Aesthetics, Creativity, and the Arts 11 (2017); B. P. Gold, M. T. Pearce, E. Mas-Herrero, A. Dagher and R. J. Zatorre, "Predictability and uncertainty in the pleasure of music: a reward for learning?", Journal of Neuroscience 39 (2019).

About this partfrom its README

Part 14 of a sixty-eight-part course in music (see the series plan and the syllabus). Part 13 stacked notes into chords; this part puts them in a line. It asks, of each thing melodies are said to do, whether they do it, and whether any string of notes in a small range would do it anyway. It counts the moves, ranges and phrase shapes of fifty-four selected, hand-entered tunes; shows that the old rule "after a leap, turn back" is obeyed more faithfully by shuffled notes than by real tunes, and why; finds what chance does not explain (tendency tones, momentum, repetition, phrases that ask and answer); measures the information in a note; and trains a model whose predictions illustrate learned melodic expectation. The melody module is Monochord's (explainer/music/monochord/melody.py), the corpus is explainer/music/monochord/tunes.py, the pictures are in explainer/music/melodyviz.py, and every sound is computed in compute.py. Published findings are the ones listed under Sources.

  • A rule that noise obeys. "After a leap, turn back": in 54 tunes there are 446 leaps of a minor third or more, and 63 in a hundred are followed by a turn back; the Tune and the same fourteen notes shuffled, heard; in shuffled tunes the figure is 79; the plan.
  • 1. The shape of a tune. An ear question: one famous tune with its octaves scrambled (every note right, the shape gone) and with its intervals doubled (nonzero intervals changed, the shape kept); contour first, then intervals, then rhythm (Deutsch 1972; Dowling 1978); the Tune on C and on F♯: no note in common, the same tune; Parsons's code of ups, downs and repeats: eight moves tell all 54 tunes apart.
  • 2. Small steps. 1,844 moves: half steps, a quarter repeats, a quarter leaps; mean two semitones; 99 in a hundred within a fifth; steps mostly fall (396 whole tones down, 313 up), fourths mostly rise (63 to 37); why: the voice, and the ear: a gallop that splits into two streams when its middle note is far away (heard); an ear question: notes drawn at random against moves drawn at random.
  • 3. Room to sing. Ranges: the median is an octave; 42 of 54 fit in one; Hot Cross Buns and the opening of The Star-Spangled Banner, heard; notes crowd the middle of a tune's range: 59 in a hundred within a tone or so of its median, the top note one note in eleven.
  • 4. The arch. Two phrases of the Ode to Joy, heard; 275 phrases sorted by shape: falling 87, arch 79, rising 60, valley 36; their average is an arch that ends half a semitone below where it began (Huron 1996); speech does the same; where a tune's highest note first arrives: a quarter of the way through in the median, not two thirds.
  • 5. The rule that chance obeys. Twenty-four notes from an urn, heard; a leap away from the middle lands near an edge, and most of the urn lies back the way it came: regression to the mean; a die: after a rise of two or more, the next roll falls in 40 of 60 cases and rises in 10; a predict-pause (a leap toward the middle); by where the leap lands: away from the middle 75 in a hundred turn back (shuffled: 95), across it 78 (87), toward it 20 (22) (von Hippel and Huron 2000); the method: ask what chance would do under the same constraints.
  • 6. Where notes want to go. Meyer's gap-fill: 38 leaps in a hundred are filled, against 22 by chance from the same moves in the same range; momentum: after a step down the next move is down 70 times in a hundred (chance 55), after a step up, up 57 (47); leaps land on degrees 1, 3 or 5, 77 in a hundred; where each degree goes: 7 to 1, 4 to 3, 6 to 5, 2 to 1; an ear question (one phrase, three last notes).
  • 7. Saying it twice. Sequences in two tunes, heard; 60 of 275 phrases repeat an earlier phrase exactly; 13 tunes contain a sequence; Frère Jacques against itself; the plan of a tune in letters (the Tune is ABCCAB).
  • 8. Question and answer. Phrases of eight beats; last notes 2.2 times as long as the others; the Ode to Joy's two phrases, heard: one ends on the second degree, the other on the first; a final phrase ends on the first degree 96 times in a hundred.
  • 9. How much news is in a note? Twenty notes: 4.3 bits each if nothing is known; 3.2 given which are common; 2.6 given the note before; longer memories do not help on 54 tunes; the guessing game: right first time 33 in a hundred, within three guesses 77; patterns of two moves show a Zipf-like rank-frequency trend (slope −1.3).
  • 10. A model that is surprised. A variable-order Markov model (the core of Pearce's IDyOM) trained on 53 tunes; the Tune's surprise note by note, heard: 5.1 bits at the leap of a fifth, about two elsewhere; every tune scored by a model trained on the rest: the Ode to Joy is easiest (1.9 bits a note), a minor-key Russian tune hardest (5.5), heard; three melodies made up by the model, heard.
  • 11. Words and tune. Mandarin's four tones on Part 8's voice, heard; Cantonese songs follow their tones about nine times in ten (Wong and Diehl 2002); speech glides, song holds; a spoken phrase repeated becomes song (Deutsch and others 2011).
  • 12. Frontier: predicting the listener. Three predictors (counting models leave-one-out; proximity optimized in-sample): common notes 3.2 bits, nearness 3.2, the counting model 2.6; IDyOM and what listeners and their brains report; memory for melody and the tunes that stick (Jakubowski and others 2017); medium surprise is liked best (Gold and others 2019). ★ research problem: which tunes will be remembered.
  • Variation 14, recap and problems. Mozart's K. 265; the Tune's first phrase as it is, with neighbour notes, with its leap filled in, with turns, upside down, backwards, and continued as the model expects (1.1 bits a note) and as it expects least (7.8); the ledger; what we found; five problems; where it comes back; in practice; references; Part 15.
What is computed and built

python -m videos.music.music14.compute (under a minute) fills .cache/music14/.

Item What it computes Checked against
hook leaps and what follows them in 54 tunes and in 200 shufflings 63 against 79 in a hundred
contour Frère Jacques with scrambled octaves and with doubled intervals the first keeps every note name; the second every direction
steps every move; shares of steps, repeats, leaps; two random melodies; the streaming demonstration Huron's counts for the Essen collection have the same shape
range each tune's span; how its notes lie about its median —
arch nine shapes of phrase; the average of 275 phrases Huron (1996): an arch
leaps turns back after leaps, by where the leap lands: tunes, shuffled tunes, an urn von Hippel and Huron (2000)
tendency gap-fill against three kinds of chance; where each degree goes; three endings 7→1, 4→3, 6→5
motive repeats and sequences; a tune against itself —
phrase phrase lengths, final lengthening, the degrees phrases end on —
info entropy; leave-one-out cross-entropy for orders 0 to 5; Zipf's law for pairs of moves —
model the Tune's information content under a model trained on the other 53; melodies sampled at orders 0, 1, 2 the peak is the leap of a fifth
tone four pitch contours (Chao's 55, 35, 214, 51) on one vowel —
frontier bits a note for three predictors —
more transposition; contour codes; a die; where the top note comes; momentum; plans in letters; the guessing game; the easiest and hardest tunes the die: 40, 10 and 10 of 60, exactly
tune Variation 14 the ledger row

Monochord's melodies are held against these in tests/music/test_melody.py; this part's claims and clips in tests/music/test_music14.py.

Sounds. Eighteen clips. Melodies are on Part 7's piano (physical model), in twelve-tone equal temperament; the streaming demonstration is organ tones (synthesized); the four tones are Part 8's source-filter voice on the vowel ah. There are no recordings.

The corpus. Fifty-four traditional or long-out-of-copyright tunes, most of them from western Europe and North America, with one each from China, Russia and Mexico. They were written out from memory for this series, in scale degrees, in the versions most often sung; they are not a scholarly edition, the rhythms of some are simplified, a few stop after their first strain, and phrase ends were marked by hand. Fifty-four tunes is a small sample, and a sample of one kind of music: every count in the film is a count of these tunes. Where the film says a pattern has been found more widely, the source is a published study of a far larger collection (chiefly the Essen folksong collection).

What the models are, and are not. Shuffling a tune keeps its notes and loses their order; it is the control that von Hippel and Huron used. The urn draws notes independently from a bell-shaped spread over an octave. The random walks draw each move from the corpus's histogram of moves, inside an octave, on the notes of the major scale: they have the tunes' step sizes and range and nothing else. Gap-fill is counted by one simple rule (at least two of the four moves after a leap of a fourth or more are steps back into the gap); other definitions give other numbers, and larger studies (von Hippel 2000) find less left over than we do. The counting model is a variable-order Markov model on pitch alone, with PPM-style escape; it knows nothing of rhythm, metre, scale degree as such, or phrase position, which is why it cannot tell a final note from any other. It is the core of IDyOM, not IDyOM. Bits per note are leave-one-out on 54 tunes, so longer contexts are starved of data. The hardest tune for the model is hard because the corpus is mostly in major keys: the number measures the model's upbringing, not the tune. The four tones are idealised contours on a synthetic vowel, without consonants or the durations and voice quality of real speech. The inverted U of the frontier chapter is drawn as a sketch of a published finding, not from data of ours.

Notes

Reversal percentages exclude cases where the next note repeats; the die reverses in 40/60 qualifying triples, or 40/50 (80%) after excluding repeats. The degree-transition and chord-tone duration analyses use major-mode tunes. Shuffling permutes pitch-duration pairs, preserving their multiset and assigned phrase-boundary indices rather than the original rhythm order. The proximity baseline is fitted and scored on the same corpus, unlike the leave-one-tune-out counting models. A near-linear rank-frequency plot is not proof of a power law. Vocal range, phrase length, tonal closure, speech prosody and listener preferences vary. Correlation between model surprise and responses does not equate model and human expectation.

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Hook: the leap rule holds in 54 tunes; shuffled, they obey it more; the plan.
  2. The shape of a tune: two disguises (an ear question); contour, intervals, rhythm; one tune in two keys; contour codes.
  3. Small steps: every move counted; steps fall, fourths rise; one stream or two; notes at random against moves at random (an ear question).
  4. Room to sing: ranges; the narrowest and the widest tune; notes crowd the middle.
  5. The arch: the shapes of 275 phrases and their average; where the highest note comes.
  6. The rule that chance obeys: an urn; a die; a predict-pause; leaps by where they land; the method.
  7. Where notes want to go: gap-fill; momentum; leaps land on the chord; tendency tones; three endings (an ear question).
  8. Saying it twice: sequences; repeats counted; a tune against itself; the plan of a tune in letters.
  9. Question and answer: phrase lengths; long last notes; antecedent and consequent.
  10. How much news is in a note: bits; the guessing game; Zipf's law.
  11. A model that is surprised: counting what follows what; the Tune's surprise; the easiest and hardest tunes; melodies made up.
  12. Words and tune: four tones; Cantonese song; speech becoming song.
  13. Frontier: three predictors; expectation in listeners and brains; memory; which tunes stick.
  14. Variation 14: the Tune's first phrase eight ways. Outro: problems, payoffs.

Covers: contour; the predominance of steps; the arch; range and tessitura; gap-fill; tendency tones; motive and sequence; phrase and breath; entropy and Zipf's law; n-gram and variable-order models of expectation; text and tone. Built and computed: an n-gram model on public-domain folk tunes (monochord/melody.py, on the corpus in monochord/tunes.py); step and leap statistics; the regression argument run as a simulation and proved for a die; the Tune's surprise curve; the pictures of melodies (explainer/music/melodyviz.py). Variation 14: the Tune ornamented, inverted, and with its least and most expected continuations. Frontier: IDyOM and neural predictors of expectation; memory for melody. Reading: Huron, Sweet Anticipation; von Hippel & Huron (2000); Temperley, Music and Probability.

Build the film

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

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

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