♪Music, Built

Act III · Voices

Part 17 of 68

Four Voices

Foundationsstarts at this level33 min of film14 chaptersprerequisites: Part 13, Part 14, Part 15, Part 16

How do four voices move from chord to chord, and can a machine learn to do it from Bach?

In 1727 the St Matthew Passion set one hymn tune five times, each harmonized anew; Bach left some 370 such four-part chorales, printed by his son in 1784-87, and they became the exercise book of harmony. Taken as data (364 chorales, 84,737 notes, 230 tunes), they show where each voice sings (inside the textbook ranges almost always), how far apart (the upper three close, the bass free), which note is doubled (the root, 87 times in a hundred in root position), and how each voice moves (by step; the inner voices nearly the shortest way). The rules of four-part writing are Part 16's for six pairs of voices, plus rules for leaning notes and for keeping the chord one sound; Bach writes parallel fifths or octaves once in 391 changes of chord, mostly between the beats, so the rules are a style's strong preferences rather than laws. On the beat, his chords follow habits (V to I, the dominant's dominant to V), his phrases end in a few cadences, his minor chorales usually end on a major chord, and more than half his beats have a passing or neighbouring note inside them. A harmonizer chooses chords and voicings together: a lattice of about 10^40 paths searched by the Viterbi algorithm, its costs the chord model learned from Bach plus the rules as penalties. On 83 chorales whose tunes it never saw, it finds Bach's chord 41 times in a hundred and his bass 35, writes no parallels where a chord-chooser writes 769, and moves its inner voices half as much as Bach: correct, and without lines. Rules can add passing notes; planning lines is what the neural harmonizers since 2016 learn. Judging a style is open. The Tune becomes a chorale, chosen chord by chord and then corrected.

What you need. Part 13 for chords and Roman numerals; Part 14 for steps and the leading note; Part 15 for keys and cadences; Part 16 for the rules between two voices. Dynamic programming; conditional probability.

Ideas, mathematics and history
the chorale, ranges and spacing, voice-leading rules and how often Bach breaks them, non-chord tones, harmonization as search
What we build, compute and hear
a harmonizer scored against Bach's own; the Tune as a chorale

What you will be able to do

Foundations

  • Write four voices under a chorale tune in range, spaced, with the root doubled.
  • Find and correct parallel fifths and octaves between any pair of voices.
  • Resolve the leading note and a chord's seventh, and name a chorale's cadences by ear.

Full course

  • Label the chords on the beats of a chorale and count how often each follows each.
  • Harmonize a tune by the Viterbi algorithm over chords and voicings, with rules as costs.
  • Evaluate a harmonizer against Bach on held-out tunes, split by tune.

Research

  • Say what agreement with Bach, likelihood, rule counts and listening tests each measure, and how each misleads.
  • Design a fair listening test for machine-written chorales.

Practice

  • Harmonize a hymn at sight: cadence chords first, then the shortest way between.
  • Balance a choir's inner voices, and keep an arrangement's upper parts close over a free bass.

Contents

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

  1. 0One tune, two harmonizersFoundations2 min
  2. 1A book of choralesFoundations2 min
  3. 2Four rangesFoundations2 min
  4. 3Every voice a lineFoundations2 min
  5. 4The rules for fourFoundations1 min
  6. 5How often Bach breaks themFull course3 min
  7. 6Chords on the beatFull course3 min
  8. 7Where phrases endPractice2 min
  9. 8Between the beatsFoundations1 min
  10. 9Harmonizing as searchFull course4 min
  11. 10Ours against BachFull course2 min
  12. 11Where we loseFull course2 min
  13. 12Frontier: machines that write choralesResearch2 min
  14. Variation 17, recap and problemsAll tracks3 min

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

Lecture

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

One tune, two harmonizersFoundations2 min

In 1727, in Leipzig, Bach's St Matthew Passion was first performed. Five times in the course of it, the choir stops the story to sing a hymn the congregation knew, and it is the same hymn tune each time, written by Hans Leo Hassler in 1601. Bach harmonized it anew for each moment of the story. Here is its last appearance, following Jesus’s death in the narrative: the tune alone, its first two phrases.

Listen to it three times: alone, then as Bach set it for four voices, and then as a simple machine sets it. The machine knows which chords Bach uses most under each note of a tune, and which chord tends to follow which, and nothing else.

The chord-chooser's chords are not wrong, one at a time. Every one is a chord Bach uses under that note. But listen to how they move. In moves it writes parallel fifths or octaves times, the red lines, and its alto and tenor mostly sit still. Bach's version is four singers, each with a line of their own, who happen to make a chord at every beat. That is the craft this part is about.

Part 16 kept two voices apart. Now there are four, and every moment is also a chord. We take Bach's chorales, three hundred and sixty-four of them, as data. We measure where each voice sings and how it moves, and state the style-specific rules that help organize four lines. We count how often Bach himself breaks them. We look at his chords, his cadences, and the notes he puts between the beats. And we build a harmonizer, a search over chords and voicings, and judge it against Bach on tunes it has never seen.

1A book of choralesFoundations2 min

What did Bach leave, and what is in it?

A chorale is a Lutheran hymn: a congregational hymn tune, often largely syllabic, a pause at the end of each line of verse. Bach wrote hundreds of four-part settings of them for his cantatas and Passions. After his death his son Carl Philipp Emanuel collected settings for the influential collection of three hundred and seventy-one printed, in four volumes, between 1784 and 1787. Composers and teachers studied them from the start, and for two centuries harmony students have been set the same exercise: here is a chorale tune, write the other three voices, then compare with Bach.

This part works from of them, encoded note by note in the music21 corpus. About half are in major keys and half in minor; nearly all have four beats to the bar. Together they hold notes. A chorale runs about beats, in about six phrases. There are different tunes among them, and of the tunes are set more than once. The tune of the hook is set times.

Here is the first phrase of that tune in two of the settings in the Passion: the first time it is sung, and the last. The last is a tone lower. Listen to the bass, the lowest line.

The same melody, and a different harmony under it: the bass takes another path and the chords change with it, from the first chord on. A chorale tune does not fix its harmony. That is what makes harmonizing one a real problem, with more than one good answer, and it is why the comparison with Bach later in this part has to be read with care.

Before taking it apart, hear one whole. This is the setting from the end of the Passion, the last time the tune is sung, complete: six phrases, each ending at a pause, the four voices in their colours.

2Four rangesFoundations2 min

Where does each voice sing, and how far apart?

First, where each voice sings. Here is how often each key is used by each of the four voices across all the chorales: soprano, alto, tenor, bass, from the top. Above them are the ranges a harmony textbook gives. Bach stays inside them almost completely: fewer than one soprano note in ten thousand falls outside, and bass notes in a hundred, most of them a low D. Each range is about an octave and a half, and neighbouring ranges overlap by about an octave, so the voices can cross, though they rarely do.

Next, the gaps between neighbouring voices. On average the soprano is about semitones above the alto, the alto about above the tenor, and almost never more than an octave. The bass is further away, nearly semitones on average, and a fifth of the time more than an octave below the tenor. This resembles a common textbook spacing guideline, with roughness and masking providing partial acoustic motivations: wide intervals sound smooth low down, close ones only higher up. So the chord is built like the harmonic series, open at the bottom and close at the top.

Four voices and a triad of three notes: one note must be sung twice. Which? When the root is in the bass, Bach doubles the root times in a hundred. Doubling the root is a common choice in this root-position subset: it reinforces the note that, in Part 13's root model, the simplified model favors. With the third in the bass, the choice is spread almost evenly: root, third and fifth each about a third of the time. There the bass already has the third, and the voices double whatever lets them move smoothly. The textbook's rule, double the root, is a description of the first case, and only a preference in the second.

3Every voice a lineFoundations2 min

How does each voice move from chord to chord?

Now follow each voice from one note to the next. The soprano, alto and tenor move by about two semitones on average, a step; the bass by about . Eight moves in ten in each upper voice are a step or less, and the alto repeats its note more often than any other voice, times in a hundred. The bass is the one voice that leaps: it jumps more than a fifth times in a hundred, the inner voices almost never. Part 14 found steps in melodies; here every voice is a melody, and the inner ones are the most careful of all.

Here is the alto of the hook's two phrases, alone, and then with the tune above it. Alone it is a modest melody of its own: small steps, a few held notes, a shape. It was written to be sung, by one person, from beginning to end.

How do the inner voices choose their notes? The old rule is to keep a note the two chords share, and move every other voice to the nearest note of the next chord. From C major to G major, the G stays, and C and E each fall a step. Teachers in Vienna called it the law of the shortest way. Measure it in Bach. Given his next chord, with its soprano and bass fixed, find the least motion the alto and tenor could make, and compare it with what they do. On average Bach's inner voices move semitones a beat, against at the least. He takes the very shortest way times in a hundred, and times in ten stays within two semitones of it. The exceptions are the interesting part: an inner voice that moves further to make a better line of its own, or to avoid a fault with another voice.

4The rules for fourFoundations1 min

What must four voices avoid?

The rules of four-part harmony, as organized in this common-practice teaching model, come in four families. Those of Part 16, to keep voices apart. More of them, because four voices make six pairs to watch at every move. Rules for the notes that lean, from Part 14 and Part 15: the leading note and the seventh. And rules that keep the chord a single sound. Here are four of them, each heard twice: first violating, then satisfying the particular guideline.

Each of these rules protects something you can hear: the independence of the voices, the direction of a leaning note, the unity of the chord. But textbooks state them as prohibitions, and students lose marks for every one. So the obvious question is how often the master breaks them. With three hundred and sixty-four chorales as data, it can be counted.

5How often Bach breaks themFull course3 min

Does the master obey the rules?

Take every moment in every chorale where any voice moves to a new note: note-change events, not necessarily changes of harmonic function. At each, check all six pairs of voices. Our detector flags parallel fifths in these encodings times and parallel octaves times. That is once in about changes of chord, or about once in every five chorales. The rule is real: by chance alone, writing four voices that move by step, you would make parallels many times in every chorale, as the chord-chooser did in the hook. And some encoded passages depart from this strict textbook detector; score context and encoding need checking.

Where do they fall? Between every pair of voices, the most often between soprano and tenor. And of the happen between the beats, often where a voice has a short intervening note; off-beat position alone does not establish passing-note function, a quick note that is not part of either chord. Most of Bach's parallels are fleeting: an eighth note long, in an inner voice.

Here are two of the few that fall on the beat, each with a beat or two around it. The red box marks the move. Listen for whether you can hear anything wrong.

They are hard to pick out. In a full texture of four voices, with the other two moving differently, brief parallels need not erase the two voice identities, although this listening demonstration does not measure fusion. The rule matters most where few voices are sounding, or where the parallel voices are the outer ones and exposed. These cases show why a detector’s flags need musical and editorial interpretation.

The other rules, counted the same way. Fifths and octaves reached in contrary motion, which some textbooks also forbid: times. Hidden fifths and octaves between soprano and bass: . A voice moving past where its neighbour just was: about one move in seventeen, the most common licence. Voices crossed: chords in a hundred. Upper voices spread wider than an octave, or notes outside the textbook ranges: about one chord in a hundred. Every rule is obeyed nearly always and broken sometimes. That is the signature of a style, not a law: a strong preference, set aside when something else matters more.

6Chords on the beatFull course3 min

Which chords, and which follows which?

To ask which chords Bach uses, name the chord on every beat. Take the four notes sounding at the beat, find the root as Part 13 did, and write it as a Roman numeral relative to the key: here the home chord, one, then the chord on the fifth degree, five, then six. About nine percent of beats receive no label from this restricted chord matcher. Nonchord tones, incomplete chords and unsupported sonorities can all cause this; it does not mean there is no harmony.

In Bach's time an organist accompanying the choir often read only the bass, with small numbers under it, the figured bass of Part 10. The numbers give the intervals above the bass, and a plain triad with its root in the bass needs none. Here is the hook's bass with its figures, computed from Bach's chords: mostly blank, a six where the chord's third is in the bass, six-five and seven for the sevenths. Across all the chorales, plain triads take nearly half the beats and sixes another sixth. The odd figures, five-four and five-two, are mostly Part 16's suspensions, and passing notes, sounding on the beat. Figured bass is the harmonizing problem upside down: the bass is given, and the player supplies the upper voices, at sight.

Here are the commonest chords, in major keys and in minor. In major, the home chord takes beats in a hundred and the dominant : between them, nearly half the music. Then the chords on six, four and two, and then a chord outside the unaltered diatonic collection, two with a major third: it is the dominant of the dominant, the applied dominant of Part 15; it is not a diatonic common-chord pivot, here borrowed for a moment. In minor the home chord is again first, but the relative major, three, comes second: minor chorales spend much of their time in the major key next door. And the dominant in minor is major, with its raised leading note, as Part 15 found.

And which chord follows which. Each row is a chord, each column the chord on the next beat, and the shading says how often. Five goes home to one more than anywhere else, apart from staying where it is. The dominant of the dominant goes to the dominant, as its name says. Four goes to one or to five. And about one beat in four keeps the same chord, while the voices move within it. This table is the first half of the harmonizer this part will build: a model of which chord comes next. Part 18 asks where the table comes from.

7Where phrases endPractice2 min

What happens at the fermatas?

Fermatas often mark chorale text-line endings, and here the encoded fermatas provide phrase markers. What chords does Bach put there? In major keys, the commonest ending is five to one, the authentic cadence of Part 15: with the seventh added, of phrase endings. Next comes an ending on five itself, a half cadence, most often approached from the dominant of the dominant: the phrase stops on a question. In minor keys the second commonest ending is seven to three: an authentic cadence in the relative major. A minor chorale's middle phrases often end in the major key next door, and come home only at the end.

Now three endings from the chorales themselves. One comes home, an authentic cadence; one stops on a question, a half cadence; and one is the end of a whole chorale in a minor key. Which is which? A, B and C.

A came home: five to one. B stopped on five, a question waiting for the next line. And C was the end of a chorale in a minor key.

Did you notice the last chord of the minor chorale? It is major. Of chorales in minor keys, end on a major home chord, and only on the minor one. The raised third in the final chord has a name, the Picardy third, and this is common in the selected minor-key settings. Historical convention contributes; harmonic-series arguments alone do not establish why a composer chose a major final chord. Other final labels can reflect modal organization, relative-key endings, metadata errors or the chord matcher’s limitations; the automated counts do not decide among those explanations.

8Between the beatsFoundations1 min

What do the quick notes do?

The chords sit on the beats; between them Bach writes quicker notes, mostly eighth notes. Count every note that begins between two beats, voice by voice, and sort it by how it moves. Most are passing notes, stepping from one chord note to the next, in one direction: Part 16's second species, now inside a chord progression. Then neighbours, a step away and back. The rest leap, usually from one note of the chord to another. The soprano, which carries the tune, has the fewest; the bass, surprisingly, has the most, walking between its chord roots. More than half of all beats have something moving inside them.

Hear what they do. The hook's two phrases, twice: once with only Bach's chords on the beats, each held for a beat, and once as he wrote them. Which is Bach's, A or B?

B is Bach's. A holds the sampled beat sonorities, on exactly the same beats, and it sounds like a hymnbook played by someone in a hurry. Many passing notes elaborate an underlying harmony, though they alter the instantaneous sonority; they turn four voices holding chords into four people singing lines. A system producing only held block chords lacks this particular between-beat activity; performance and voicing can still vary.

9Harmonizing as searchFull course4 min

Can chords and voices be chosen together?

Now the exercise itself, set to a machine. Given a tune, one note to each beat, choose at every beat a chord that contains the tune's note, and a voicing of that chord: exactly where the alto, tenor and bass sing it. Choose them so that the whole progression is likely, in the sense of chapter six's table, and so that the voices move as chapter three found and minimize its implemented voice-leading costs; only stated filters are hard constraints. Chords and voices have to be chosen together, because a rule like no parallel fifths depends on both.

Lay the choices out as a lattice: a column for each of the hook's beats, a dot for candidate chord-and-voicing groups after range limits and pruning to fourteen likely chord labels. Each displayed dot aggregates about twenty-five candidates, and the gold path is schematic, not the computed optimum. There are between and under each note. A harmonization is a path from left to right, one dot in each column, and there are about ten to the of them, too many to try. But the cost of a path is a sum of costs of single dots and of steps between neighbouring columns, so the cheapest path can be found column by column: for every dot, keep only the cheapest way to reach it. It is the Viterbi algorithm, the dynamic programming of Part 16's counting turned to finding the best. Here it takes seconds.

What goes into the cost. Two terms come from Bach's statistics: how unlikely each chord is, given the one before it, and how unlikely the tune's note is within that chord, both counted from two hundred and eighty chorales. The rest are this part's chapters turned into penalties: how far the inner voices and the bass move; a heavy penalty for parallel fifths and octaves; smaller ones for hidden fifths, overlaps and leaps; a leading note or a seventh going the wrong way; inversions and doubling; and at each fermata, how often Bach ends a phrase on that chord. The build uses fixed hand-set weights. It does not reproduce a validation search or document its full tuning history, so these should be treated as illustrative settings rather than independently validated optimal weights.

Here is the search's answer for the hook's two phrases, chord by chord, against Bach's. They agree on of the beats. One difference is a lesson: at the end of the second phrase the search chooses a major home chord, where Bach stays minor. It learned from minor chorales that end on a major chord, the Picardy third, and it cannot tell the end of a phrase from the end of a piece. And where the chord-chooser of the hook wrote parallels, the search writes none: the penalties did their work. How good is it in general? That needs tunes it has never seen.

10Ours against BachFull course2 min

How close does the search come, on tunes it never saw?

Seeing another setting of a test tune can leak melodic information, even when harmonization is not unique. So the chorales are split by tune: chorales to learn from, and to test on, with every setting of a tune on the same side of the split. The Passion Chorale, all eleven settings, is in the test set; the model never heard it. On each test chorale the search harmonizes Bach's tune, and its answer is compared with Bach's, beat by beat.

Here is the result, for the plain chord-chooser of the hook and for the full search. Both choose Bach's own chord on about beats in a hundred. That sounds low, but chapter one showed that Bach himself sets one tune in different ways; there is no single right answer to match. The search finds Bach's bass note more often, times in a hundred against . The real difference is in the rules. The chord-chooser writes parallel fifths and octaves on these chorales; Bach writes ; the search writes none. And the last row is where the search falls short: its inner voices move semitones a beat, Bach's . It plays safe, keeping notes still where Bach's singers move.

Now judge by ear. The Passion Chorale's next two phrases, harmonized twice, once by the search and once by Bach, in an order you do not know. Which is Bach's, A or B?

B is Bach's. Look at the pictures as well as listening: in A the alto and tenor hold long notes and the chords change underneath them; in B every voice is moving, with quick notes between the beats. The search’s version has no parallels under the reported detector; soft penalties do not guarantee that every textbook rule is satisfied, and it is not wrong. It is a correct exercise. What it lacks is what chapter eight showed: lines.

11Where we loseFull course2 min

What does the search not know?

Why does the search fall short? List what it does not know. It looks one chord back, so it has no plan: Bach's minor chorales travel to the relative major in the middle and come home at the end, and nothing in a table of pairs can arrange that. It cannot tell the end of a phrase from the end of the piece. It never writes a note between the beats. Its costs pay it for stillness: motion is penalized, and nothing rewards a good line. And it hears no words, while Bach sometimes chose a chord for a word.

The third of these can be patched by a rule. Where an inner voice or the bass moves by a third from one beat to the next, split its note in two and put a passing note in the gap, unless that would make parallel fifths or octaves with another voice. Here is the search's harmonization of the third and fourth phrases again, with that rule applied.

Count the notes in the lower three voices, per beat, across the test chorales. The search writes a beat: fewer than one, because it holds notes. With the rule, . Bach writes . A rule closes a little of the gap, and the passing notes help the sound. The rest is not a matter of decoration. It is the plan of each line over many beats, which is what composers mean by voice leading and what machines took decades to learn. That is the frontier.

12Frontier: machines that write choralesResearch2 min

Who writes the best Bach that is not Bach, and how would we know?

The chorales became an influential benchmark for algorithmic harmonization, alongside earlier machine-composition work. In 1988 Kemal Ebcioglu's program harmonized them with about three hundred and fifty rules, written by hand. In 2005 Moray Allan and Christopher Williams learned the harmonizer instead, as a hidden Markov model of chords under a tune, solved by the same Viterbi search as this part's. Then neural networks: BachBot in 2016, DeepBach in 2017, which rewrites one note of one voice at a time, again and again, until all four voices agree with what it has learned, and Coconet, which learned to fill in a score with holes in it, and in 2019 harmonized tunes typed in by millions of people in Google's Bach Doodle. These models write the moving inner voices this part's search could not.

And how should they be judged? This part has tried three ways, and each has a flaw. A model's likelihood measures how well it predicts Bach's notes, but a model can predict well and still write dull music. Counting faults rewards caution, and the detector also flags passages in the reference corpus. Agreement with Bach's chords punishes every other good answer. So the strongest claims rest on listening tests: play people real and generated chorales and ask which is Bach. In the tests reported by BachBot's and DeepBach's authors, many listeners, including trained musicians, often could not tell. But who listens, to how much, and what they are asked, changes the answer.

What remains open is a definition. When we say a harmonization is in Bach's style, what is being claimed, and how should it be measured, so that a teacher's judgement, a listener's ear, and Bach's own habit of setting one tune many ways all come out right? Whether a style is best described as rules, as probabilities, or as something neither captures, is still argued.

Variation 17, recap and problemsAll tracks3 min

Every part ends by doing something to the Tune with what it has built. This part built a harmonizer. So the Tune becomes a chorale tune, with a pause at the end of each phrase, and is harmonized twice: first by the chord-chooser alone, which knows Bach's chords but not his rules, and then by the full search, which corrects it. Listen for the places where the first goes wrong; they are marked in red.

Row seventeen of the ledger. seconds. The measurement: the chord-chooser's version has parallel fifths or octaves; the corrected one, none. The chords are nearly the same in both. What changed is where the voices sing them.

What did we find? Bach's chorales, as data, show where four voices sing, how far apart, which note is doubled. Each voice is a line of small steps, and the inner voices take nearly the shortest way. The rules hold almost always: Bach writes parallel fifths or octaves once in about changes of chord. His chords, cadences and passing notes can be counted too. A search over chords and voicings, learned from the chorales and constrained by the rules, finds Bach's chord about four times in ten on tunes it never saw, and produces no detected parallels in this test; other costs remain soft preferences. And what it lacks is the plan of a line over many beats, which is what the newer machines learn.

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 asks where the table of progressions comes from, and the part after it travels to distant keys with chromatic chords. Canon and fugue make four voices from one melody. The Renaissance shows harmony before Bach's. And the machines of the frontier return when this series builds composers of its own, and asks how to judge them.

And in practice. A choir director balances the inner voices, which carry the lines. An arranger keeps the upper parts close and lets the bass move. A church musician harmonizing a hymn at sight finds the cadence chords first and takes the shortest way between them. And the many auto-harmonizers use related search ideas, while architectures and objectives vary.

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

Where it goes next. Where the table of progressions comes from in Part 18; chromatic chords in Part 19; canon and fugue in Part 20; the Renaissance in Parts 23 and 24; machines that compose, and judging them, in Parts 42 and 65.

Key results

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

Bach's parallels\(\displaystyle 52 \text{ fifths} + 23 \text{ octaves }\allowbreak \text{in } 29{,}326 \text{ chord }\allowbreak \text{changes} \approx 1 \text{ in } 391\)
Doubling\(\displaystyle \text{root }\allowbreak \text{position: }\allowbreak \text{root }\allowbreak \text{doubled } 87\%; \ \text{first }\allowbreak \text{inversion: }\allowbreak \text{root, }\allowbreak \text{third, }\allowbreak \text{fifth } 32, 39, 30\%\)
The shortest way\(\displaystyle \text{alto} + \text{tenor}: \ 3.6 \text{ semitones }\allowbreak \text{a }\allowbreak \text{beat }\allowbreak \text{(least }\allowbreak \text{possible } 2.4\text{); }\allowbreak \text{exactly }\allowbreak \text{least } 68\%\)
The harmonizer\(\displaystyle \hat{c}_{1:n} = \arg\min \sum_k \big[ -\log P(c_k \mid c_{k-1}) - \log P(s_k \mid c_k) + \lambda \cdot \text{rules}(v_{k-1}, v_k) \big]\)
Held out\(\displaystyle \text{same }\allowbreak \text{chord } 41\%, \ \text{same }\allowbreak \text{bass } 35\%, \ \text{parallels } 0 \ (\text{chord-chooser } 769, \text{ Bach } 77)\)
The Picardy third\(\displaystyle 104 \text{ of } 176 \text{ minor }\allowbreak \text{chorales }\allowbreak \text{end }\allowbreak \text{on }\allowbreak \text{a }\allowbreak \text{major }\allowbreak \text{chord; } 11 \text{ on }\allowbreak \text{the }\allowbreak \text{minor}\)

Try it

Lab 17 · Four voices, counted and harmonized

Count where Bach's four voices sing and how often he breaks the rules, harmonize a chorale tune the harmonizer has never seen, compare it with Bach beat by beat, and name cadences by ear.

Figure produced by Lab 17: Four voices, counted and harmonized
Produced by the lab below, seed 0, in 1.8 s.
python -m videos.music.labs 17 needs numpy, scipy, matplotlib · download lab17.py · source on GitHub
chorales, tunes                                         364 chorales; 230 tunes; train 280, test 84 (split by tune)
some test chorales                                      bwv103.6, bwv111.6, bwv144.6, bwv244.25, bwv65.7, bwv72.6, bwv92.9, bwv113.8
changes of chord; parallel fifths and octaves           29,326; 52 and 23 (one in 391)
hidden fifths and octaves; overlaps; crossed chords     157; 1735; 733 of 29,690
chords of I, IV, V under each note                      I/IV  I/IV  I/V  I/V  IV  IV  I/V
choices of chords, before voicing                       32
bwv244.62: Bach's chords (first 12 beats)               i VI III iv III IV7 VII III V i iiø7 i
bwv244.62: the search's                                 III VI III VI III iv7 VII III V i V i
same chord / same bass as Bach: search, chord-chooser   33% / 23%;  31% / 21%
parallels: search, chord-chooser, Bach                  0, 11, 1
alto and tenor motion (semitones a beat): search, Bach  1.8, 3.7
the phrase, harmonized                                  I I V I IV IV I   72-67-64-60  72-67-64-48  79-71-62-43 ...
ear problem, the eight cadences (listen first)          picardy;  half;  authentic;  authentic;  authentic;  half;  half;  picardy

Bach's four voices move by small steps, the bass the most freely; he obeys the rules almost always and breaks them now and then; a search over chords and voicings learned from his chorales breaks none, agrees with his chords about four times in ten, and moves its inner voices too little.
The code (122 lines; it asserts its own result)
"""Lab 17: Bach's chorales as data, the rules of four-part writing counted, a harmonizer judged against Bach, and
cadences by ear."""

from itertools import product

import numpy as np

from videos.coursekit import labs
from explainer.music.monochord import Clip, concat
from explainer.music.monochord import chorales as BC
from explainer.music.monochord import fourpart as F
from explainer.music.monochord.partkit import organ_tone

TITLE = "Four voices, counted and harmonized"
GOAL = ("Count where Bach's four voices sing and how often he breaks the rules, harmonize a chorale tune the "
        "harmonizer has never seen, compare it with Bach beat by beat, and name cadences by ear.")
TASKS = [
    "Set CHORALE to another name from the test set (the lab prints some). How often does the search agree with Bach, and where do they part?",
    "Set WEIGHTS to {'parallel': 0} and then {'motion': 0.5}. What happens to the parallels, and to the inner voices?",
    "Set PHRASE to the Tune's second phrase, [65, 65, 64, 64, 62, 62, 60]. How many choices of I, IV and V are there, and which does the search pick?",
]
CHORALE = "bwv244.62"           # a chorale whose tune is in the test set (the Passion Chorale's last setting)
WEIGHTS = {}                    # changes to fourpart.DEFAULT_WEIGHTS
PHRASE = [72, 72, 79, 79, 81, 81, 79]   # the Tune's first phrase, an octave up, as a soprano
SR = 48_000
CADENCE_KINDS = ("authentic", "half", "picardy")


def run(seed=0):
    rng = np.random.default_rng(seed)
    lab = labs.Lab()
    book = BC.load()
    train, test = BC.split(book, offset=2)
    lab.row("chorales, tunes", f"{len(book)} chorales; {len(BC.tunes(book))} tunes; train {len(train)}, test {len(test)} (split by tune)")
    lab.row("some test chorales", ", ".join(c.name for c in test[:8]))

    # 1. the rules, counted in Bach
    r = F.rule_census(book)
    par = sum(r["parallel"].values())
    lab.row("changes of chord; parallel fifths and octaves", f"{r['moves']:,}; {r['parallel']['fifths']} and {r['parallel']['octaves']} (one in {r['moves'] / par:.0f})")
    lab.row("hidden fifths and octaves; overlaps; crossed chords", f"{r['hidden']}; {r['overlap']}; {r['crossing']} of {r['chords']:,}")

    # 2. Problem 1: chords of I, IV and V under a phrase
    tonic = 0                                                     # the phrase is in C major
    triads = {"I": (0, 4, 7), "IV": (5, 9, 0), "V": (7, 11, 2)}
    fits = [[n for n, pcs in triads.items() if (p - tonic) % 12 in pcs] for p in PHRASE]
    lab.row("chords of I, IV, V under each note", "  ".join("/".join(f) for f in fits))
    lab.row("choices of chords, before voicing", f"{int(np.prod([len(f) for f in fits]))}")
    assert all(fits)

    # 3. the harmonizer on a chorale it has never seen
    models = {m: F.ChordModel(train, m) for m in ("major", "minor")}
    c = next(x for x in book if x.name == CHORALE)
    B = F.bach_on_beats(c)
    full = F.harmonize(B["soprano"], c.tonic, models[c.mode], fermatas=B["fermatas"], weights=WEIGHTS)
    plain = F.harmonize(B["soprano"], c.tonic, models[c.mode], fermatas=B["fermatas"], plain=True)
    ef, ep = F.evaluate(full, B), F.evaluate(plain, B)
    m = models[c.mode]
    lab.row(f"{CHORALE}: Bach's chords (first 12 beats)", " ".join(F.roman(s + (0,), c.mode) if s else "–" for s in B["states"][:12]))
    lab.row(f"{CHORALE}: the search's", " ".join(m.name(s) for s in full["states"][:12]))
    lab.row("same chord / same bass as Bach: search, chord-chooser", f"{100 * ef['same_chord']:.0f}% / {100 * ef['same_bass']:.0f}%;  {100 * ep['same_chord']:.0f}% / {100 * ep['same_bass']:.0f}%")
    lab.row("parallels: search, chord-chooser, Bach", f"{ef['ours']['parallels']}, {ep['ours']['parallels']}, {ef['bach']['parallels']}")
    lab.row("alto and tenor motion (semitones a beat): search, Bach", f"{ef['ours']['inner_motion']:.1f}, {ef['bach']['inner_motion']:.1f}")
    if not WEIGHTS:
        assert ef["ours"]["parallels"] == 0

    # 4. Problem 1 by machine: the phrase harmonized
    ph = F.harmonize(PHRASE, 0, F.ChordModel(book, "major"), fermatas=[len(PHRASE) - 1], weights=WEIGHTS)
    lab.row("the phrase, harmonized", " ".join(F.roman(s + (0,), "major") for s in ph["states"]) + "   " + "  ".join("-".join(str(x) for x in ch) for ch in ph["chords"][:3]) + " ...")

    # 5. Problem 3, for the ear: eight cadences from the chorales, on organ tones
    picks = []
    for x in book:
        labs_ = F.beat_labels(x)
        fk = [k for k, y in enumerate(labs_) if y["fermata"]]
        for k in fk[:-1]:
            if k < 2 or not labs_[k - 1]["label"] or not labs_[k]["label"]:
                continue
            a, z = labs_[k - 1]["label"][:2], labs_[k]["label"][:2]
            if x.mode == "major" and a == (7, "major") and z == (0, "major"):
                picks.append(("authentic", [labs_[k - 1]["chord"], labs_[k]["chord"]]))
            if x.mode == "major" and z == (7, "major") and a in ((2, "major"), (0, "major")):
                picks.append(("half", [labs_[k - 1]["chord"], labs_[k]["chord"]]))
        if x.mode == "minor" and labs_[-1]["label"] and labs_[-1]["label"][:2] == (0, "major") and labs_[-2]["label"]:
            picks.append(("picardy", [labs_[-2]["chord"], labs_[-1]["chord"]]))
    by = {k: [p for p in picks if p[0] == k] for k in CADENCE_KINDS}
    answers, clips = [], []
    for _ in range(8):
        kind = CADENCE_KINDS[int(rng.integers(0, 3))]
        _, chs = by[kind][int(rng.integers(0, len(by[kind])))]
        y = np.zeros(int(3.0 * SR))
        for t, ch in enumerate(chs):
            tone = sum(organ_tone(440 * 2 ** ((p - 69) / 12), 1.3 if t else 0.95, partials=6, rolloff=0.7, decay=1.2) for p in ch)
            i = int(t * 0.95 * SR)
            y[i:i + len(tone)] += tone[: len(y) - i]
        clips.append(Clip(y, SR).fade(0.01, 0.2).at_level(-20.0))
        answers.append(kind)
    lab.audio = concat(clips, gap=0.9)
    lab.row("ear problem, the eight cadences (listen first)", ";  ".join(answers))

    fig, (a, b) = labs.figure(2)
    st = [[abs(v[k + 1][0] - v[k][0]) for x in book for v in [x.voices[j]] for k in range(len(v) - 1)] for j in range(4)]
    names = ["soprano", "alto", "tenor", "bass"]
    a.bar(range(4), [np.mean(s) for s in st], color=[labs.GOLD, "#F472B6", "#A3E635", "#7DD3FC"])
    a.set_xticks(range(4))
    a.set_xticklabels(names)
    a.set_ylabel("semitones")
    a.set_title("Bach's voices: the average move to the next note")
    keys = ["same chord", "same bass"]
    x = np.arange(2)
    b.bar(x - 0.2, [ep["same_chord"], ep["same_bass"]], width=0.4, color="#888", label="chord-chooser")
    b.bar(x + 0.2, [ef["same_chord"], ef["same_bass"]], width=0.4, color=labs.GOLD, label="search")
    b.set_xticks(x)
    b.set_xticklabels(keys)
    b.set_ylim(0, 1)
    b.set_title(f"Agreement with Bach on {CHORALE}")
    b.legend(frameon=False)
    lab.fig = fig
    lab.note = ("Bach's four voices move by small steps, the bass the most freely; he obeys the rules almost always "
                "and breaks them now and then; a search over chords and voicings learned from his chorales breaks "
                "none, agrees with his chords about four times in ten, and moves its inner voices too little.")
    return lab

Now change it

  1. Set CHORALE to another name from the test set (the lab prints some). How often does the search agree with Bach, and where do they part?
  2. Set WEIGHTS to {'parallel': 0} and then {'motion': 0.5}. What happens to the parallels, and to the inner voices?
  3. Set PHRASE to the Tune's second phrase, [65, 65, 64, 64, 62, 62, 60]. How many choices of I, IV and V are there, and which does the search pick?

Problems, with solutions

Try each problem before opening its solution.

  1. Compute. Harmonize the Tune's first phrase, C C G G A A G, one chord to a note, using only I, IV and V. How many choices of chords are there, before voicing?

    Solution

    C lies in I and IV (C E G, F A C); G in I and V (C E G, G B D); A only in IV. So the choices are 2 × 2 × 2 × 2 × 1 × 1 × 2 = 32. A sensible one, I I I I IV IV I, keeps the A–A under IV and ends the phrase on a chord that holds the G; the plain and full harmonizers of Variation 17 choose I I I I IV IV I and I I V I IV IV I.

  2. Prove. Show that if every voice moves to the nearest note of the next chord, two voices can still make parallel fifths. Give the smallest example, and the rule that prevents it.

    Solution

    Take C major root position with the soprano on G and the tenor on C (a fifth), moving to D minor: the nearest note to G in D minor is A, and to C it is D, so both voices rise a step, still a fifth apart: parallel fifths, each voice having moved as little as possible. The shortest way is a rule about each voice alone; parallels are about pairs, so a separate rule (and in the harmonizer, a separate penalty) is needed. Moving the upper voices down, against the bass (G to F, E to D, C to A over C to D), costs a little more motion and has no parallels.

  3. Ear. The lab plays eight short cadences from the chorales. Name each: authentic, half, or ending on a major chord in a minor key.

    Solution

    The lab prints the answers. An authentic cadence lands on a chord that sounds like home, the bass falling a fifth (or rising a fourth) into it. A half cadence stops on a chord that wants to go on, usually with a bass that has risen by step to it. The Picardy ending is a minor passage whose last chord is suddenly brighter: listen to the top of the final chord.

  4. Build. Change the harmonizer's chord model to look two chords back instead of one. Does it find Bach's chord more often on the test chorales? Why might it not?

    Where to look. fourpart.ChordModel counts pairs; a model of triples needs the state of the Viterbi search to be a pair of chords, which squares its size. With 280 chorales and about 25 chords in each mode, most triples are seen a few times or never, so the estimates are noisy and smoothing dominates; the gain, if any, is small unless the counts are pooled (by function, or by backing off to pairs). Different settings of one tune illustrate why agreement is not equivalent to quality; they do not establish a mathematical accuracy ceiling.

  5. ★ A fair listening test. Design a listening test that could show a machine's chorales are as good as Bach's. What would a fair test control for?

    Where the frontier is. The published tests (BachBot's, DeepBach's) asked listeners whether a short excerpt was Bach. A fair test controls the excerpt's length (short excerpts hide planning), the tune (machine and Bach on the same held-out tune), the performance (the same synthesis for both, or the same singers), the listeners' training (report results by expertise), and the question (preference, or attribution, or a teacher's grade). It should also include Bach against Bach, two settings of one tune, to measure how often listeners call real Bach machine-made. No standard test exists.

Notes and sources

Sources

Books: J. S. Bach, 371 vierstimmige Choralgesänge, ed. C. P. E. Bach (Breitkopf, 1784–87); E. Aldwell and C. Schachter, Harmony and Voice Leading (4th ed., 2011); S. Kostka and D. Payne, Tonal Harmony (8th ed., 2018); D. Huron, Voice Leading: The Science behind a Musical Art (2016); S. Sechter, Die Grundsätze der musikalischen Komposition (1853–54).

Papers: K. Ebcioğlu, "An expert system for harmonizing four-part chorales", Computer Music Journal 12 (1988); M. Allan and C. K. I. Williams, "Harmonising chorales by probabilistic inference", Advances in Neural Information Processing Systems 17 (2005); F. Liang, BachBot: Automatic composition in the style of Bach chorales, MPhil thesis, Cambridge (2016); G. Hadjeres, F. Pachet and F. Nielsen, "DeepBach: a steerable model for Bach chorales generation", ICML (2017); C.-Z. A. Huang, T. Cooijmans, A. Roberts, A. Courville and D. Eck, "Counterpoint by convolution", ISMIR (2017); C.-Z. A. Huang and others, "The Bach Doodle: approachable music composition with machine learning at scale", ISMIR (2019); M. S. Cuthbert and C. Ariza, "music21: a toolkit for computer-aided musicology and symbolic music data", ISMIR (2010).

  • J. P. Clendinning and E. W. Marvin, The Musician's Guide to Theory and Analysis (4th ed., 2021); M. Gotham and others, Open Music Theory (2nd ed., 2021, open access): the part-writing rules as taught today.
About this partfrom its README

Part 17 of a sixty-eight-part course in music (see the series plan and the syllabus), the second part of Act III. Part 16 kept two voices apart; here there are four, and every moment is also a chord. The part takes 364 of Bach's four-part chorales as data, measures where each voice sings and how it moves, states the rules of four-part writing and counts how often Bach breaks them, looks at his chords, cadences and passing notes, and builds a harmonizer, a search over chords and voicings together, which it judges against Bach on tunes the harmonizer has never seen. The chorales are Monochord's table (explainer/music/monochord/chorales.py), the rules and the harmonizer are explainer/music/monochord/fourpart.py, the choir is explainer/music/monochord/instruments/choir.py, and every sound is computed in compute.py. Published findings are the ones listed under Sources.

  • One tune, two harmonizers. The St Matthew Passion (1727) and Hassler's tune of 1601, sung five times in it; its last setting's first two phrases, alone, as Bach set them, and as a chord-chooser sets them (Bach's commonest chords under each note, nothing else): six parallel fifths or octaves in fifteen moves, and inner voices that hardly move; the plan.
  • 1. A book of chorales. C. P. E. Bach's edition (Breitkopf, 1784–87, 371 chorales); the data: 364 chorales, 185 in major and 178 in minor, 84,737 notes, 230 different tunes, 59 set more than once, the Passion Chorale eleven times; its first phrase the first and the last time it is sung in the Passion, heard; the whole of its last setting, heard.
  • 2. Four ranges. Where each voice sings, against the textbook ranges (C4–A5, G3–D5, C3–A4, E2–D4): outside them, five soprano notes in a hundred thousand and 0.76 bass notes in a hundred; spacing: soprano to alto 5.3 semitones on average, alto to tenor 5.8, tenor to bass 8.6, more than an octave 0.3, 0.9 and 19 times in a hundred; doubling: in root position the root 87 times in a hundred, with the third in the bass root, third and fifth about a third each.
  • 3. Every voice a line. Mean moves 1.9, 1.7, 2.0 and 3.1 semitones (soprano to bass); steps 85, 84, 81 and 66 in a hundred; the alto alone, heard; the law of the shortest way (Bruckner, after Sechter): Bach's alto and tenor move 3.6 semitones a beat where 2.4 would do, take the very shortest way 68 times in a hundred and come within two semitones of it 80.
  • 4. The rules for four. Four families; four rules each heard as two chords wrong and right: parallel fifths and octaves between any of six pairs; the leading note rises; a seventh falls; the upper voices within an octave.
  • 5. How often Bach breaks them. At 29,326 changes of chord, 52 parallel fifths and 23 octaves: once in 391, about once in five chorales; by pair (soprano and tenor the most); 51 of 75 between the beats, through a passing note; two on the beat, heard; contrary fifths and octaves 85, hidden 157, overlaps 1,735 (one move in 17), crossings 2.5 chords in a hundred: rules obeyed between 94 and 99.7 times in a hundred.
  • 6. Chords on the beat. Labels as Roman numerals (nine beats in a hundred carry no chord); figured bass: the hook's bass with its figures, and the figures on all the chorales' beats (5/3 45 in a hundred, 6 16, 5/4 and 5/2 six each: suspensions and passing notes); in major I, V, vi, IV, ii, then II (the dominant's dominant); in minor i, then III, iv, V; what follows what; the same chord on the next beat 23 times in a hundred.
  • 7. Where phrases end. At 1,216 fermatas in major: V–I 246, II–V 114, V7–I 80; in minor V–i 107, VII–III 98 (a cadence in the relative major); three cadences heard; 104 of 176 minor chorales end on a major chord (the Picardy third), 11 on the minor one.
  • 8. Between the beats. Notes that begin between beats, by voice and kind: passing notes the majority in every voice, the bass with the most, the soprano the fewest; 55 beats in a hundred have something moving inside them; an ear question (Bach's chords as blocks, and as he wrote them).
  • 9. Harmonizing as search. The problem; the lattice for the hook's sixteen beats (192 to 446 chord-and-voicing pairs a beat, about 10⁴⁰ paths); the Viterbi algorithm (0.4 s); the cost terms and where each comes from; the hook harmonized: the same chord as Bach on 8 of 16 beats, no parallels, and a major chord at a phrase's end where Bach stays minor.
  • 10. Ours against Bach. A split by tune (280 chorales to learn from, 83 to test, 4,438 beats, no test tune in training in any setting); the same chord as Bach 41 times in a hundred (the chord-chooser 41 too), the same bass 35 (24); parallel fifths and octaves: the chord-chooser 769, Bach 77, the search 0; inner-voice motion 1.8 semitones a beat against Bach's 3.5; an ear question (ours or Bach's).
  • 11. Where we lose. What the search does not know (a plan, the end of a piece, notes between beats, lines, words); passing notes added by rule, heard; notes a beat in the lower voices: 0.69, 0.76 with the rule, Bach 1.13.
  • 12. Frontier: machines that write chorales. CHORAL (Ebcioğlu 1988), Allan and Williams's hidden Markov model (2005), BachBot (2016), DeepBach and Coconet (2017), the Bach Doodle (2019); four ways to judge a style, each flawed. ★ research problem: what is a style, in numbers?
  • Variation 17, recap and problems. The Tune as a chorale, with a pause at each phrase end: chosen chord by chord (six parallel fifths or octaves), then corrected by the full search (none); the ledger; what we found; five problems; where it comes back; in practice; references; Part 18.
What is computed and built

python -m videos.music.music17.compute (about five minutes) fills .cache/music17/.

Item What it computes Checked against
hook the Passion Chorale's first two phrases: Bach's, the chord-chooser's, the search's fourpart.parallels
book the collection: modes, metres, notes, tunes, settings the table's tests
ranges ranges, spacing, doubling the textbook ranges
motion moves by voice; the shortest way for alto and tenor —
rules four rules, wrong and right parallels, spacing_ok
census every parallel, hidden interval, overlap, crossing in the chorales —
vocab chord frequencies and transitions on the beat —
cadences chords at the fermatas; final chords —
decoration notes between the beats, by voice and kind —
harmonizer the lattice under the hook; the search's answer —
evaluation the search and the chord-chooser on 83 held-out chorales split by tune (chorales.split)
improve passing notes added by rule —
tune Variation 17 no parallels after correction
more the hook's chorale complete; figured bass; Phrygian half cadences chords.figure_name

Monochord's chorales, rules, harmonizer and choir are held in tests/music/test_fourpart.py; this part's claims and clips in tests/music/test_music17.py.

Sounds. The chorales are sung by a model choir: Part 8's source-filter voice (Rosenberg pulses through the formants of the vowel "ah", scaled for each part), one continuous voice for each part, legato, with a little vibrato (synthesized); the rules are heard on organ tones. Equal temperament, with a pause at each fermata. There are no recordings.

What the models are, and are not. The data are 364 encodings from the music21 corpus, not a critical edition; a few have parts in unusual ranges or modes mislabelled as major or minor, and nothing here was corrected by hand. Chord labels are the plainest triad or seventh chord that fits the four notes sounding on a beat; a passing note on the beat can make a beat unlabelled or mislabelled, and inversions and sevenths are counted with their chords only where stated. The rules are textbook rules made exact (parallels need both voices to move; hidden fifths are outer voices only); other definitions give other counts. The harmonizer is a first-order model, one chord a beat, with fixed hand-set penalties; this build does not reproduce a validation sweep or its full tuning history; it does not write notes between the beats (except by the rule of chapter 11) and does not see phrase structure. Agreement with Bach is not a measure of quality: chapter 1 shows that Bach sets one tune several ways. The choir is a model, not singers.

Notes

Automated parallel flags concern the selected encodings under the implemented detector, not an edited verdict that Bach made mistakes. A note-change event need not change harmonic function. Off-beat position does not establish that a note is a passing tone. Unlabeled beats still have harmony; the chord vocabulary is restricted. A secondary dominant is not necessarily a common-chord pivot. Spacing constraints apply to adjacent upper voices, not the entire soprano-to-tenor span. The search uses soft penalties and candidate filters; zero detected parallels does not prove compliance with every textbook rule. The fixed weights are illustrative, and no reproducible validation search is included here.

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Hook: the Passion Chorale alone, as Bach set it, and as a chord-chooser sets it; the plan.
  2. A book of chorales: C. P. E. Bach's edition; the data; one tune, two settings; one whole chorale.
  3. Four ranges: where each voice sings; spacing; which note is doubled.
  4. Every voice a line: steps and leaps by voice; the alto alone; the shortest way, measured.
  5. The rules for four: parallels between six pairs, the leading note, the seventh, spacing (each heard wrong and right).
  6. How often Bach breaks them: parallels counted, by pair and by beat; two heard; the other licences.
  7. Chords on the beat: labels; figured bass; the commonest chords in major and minor; what follows what.
  8. Where phrases end: cadences at the fermatas; three heard; the Picardy third.
  9. Between the beats: passing and neighbouring notes by voice; with and without them (an ear question).
  10. Harmonizing as search: the lattice; the Viterbi algorithm; the costs; the hook harmonized.
  11. Ours against Bach: a split by tune; the scores; ours or Bach's (an ear question).
  12. Where we lose: what the search does not know; passing notes by rule; the gap.
  13. Frontier: CHORAL, hidden Markov models, BachBot, DeepBach, Coconet; how to judge a style.
  14. Variation 17: the Tune as a chorale, chosen and corrected. Outro: problems, payoffs.

Covers: ranges, spacing and doubling; the voice-leading rules; cadences; non-chord tones; harmonization as search over chords and voicings. Built and computed: the chorales as data (monochord/chorales.py, 364 chorales derived from the music21 corpus encodings); monochord/fourpart.py: the rules for six pairs of voices, chord labels on the beat, a chord model learned from Bach, a harmonizer (chords and voicings chosen together by the Viterbi algorithm), evaluation against Bach on held-out tunes; rule violations in the chorales counted; a four-part choir from Part 8's voice (instruments/choir.py); figured bass read off Bach's chords. Variation 17: the Tune as a chorale, ours and the corrected one, with the corrections shown. Frontier: DeepBach and Coconet; how to evaluate style. Reading: Aldwell & Schachter; Kostka & Payne; Allan & Williams (2005).

Build the film

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

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

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