♪Music, Built

Act VII · The Craft

Part 42 of 68

Composing

Foundationsstarts at this level34 min of film12 chaptersprerequisites: Part 14, Part 16, Part 17, Part 18, Part 20, Part 21, Part 22

Is composing search under constraints, and what would a program need in order to judge its own drafts?

Beethoven's sketchbooks of 1822 to 1824 show the Ode to Joy approached in draft after draft; what the search found has 30 notes in its first two phrases and not one leap. The part treats composing as search under constraints. It starts with the motive and the classical operations on it (inversion, retrograde, augmentation, diminution, fragmentation, interval change, new rhythm, embellishment), all diatonic and all functions from melodies to melodies; grows Schoenberg's sentence from four notes; varies the Tune four ways; plans tension bar by bar and measures it against the plan. It counts what rules do, exactly: of 2,562,890,625 eight-note melodies on fifteen white keys, five rules leave 9,252. It builds a dice game of its own in the format of Kirnberger's (1757), 176 bars with about 1.6 x 10^13 distinct minuets and 41 bits of entropy; reruns Hiller and Isaacson's generate-and-test (277 draws for a twelve-note line, most rejected at the cadence); shows a Markov chain copying more as it remembers more; evolves melodies; and builds a searcher whose critics are the series' own rules, which keeps draft 1,205 of 2,000 and shows what it threw away. The Tune's first four notes become Variation 42.

What you need. Part 14 for melody and its statistics; Part 16 for counterpoint's rules and counting; Part 18 for progressions; Part 20 for canon; Part 21 for form; Part 22 for grammars. Dynamic programming, Markov chains, entropy, search.

Ideas, mathematics and history
motive and development, variation technique, planning tension, working under constraint, dice games, the Illiac Suite, generate and test
What we build, compute and hear
a generate-and-test composer with its rejected drafts shown

What you will be able to do

Foundations

  • Hear a motive's inversion, retrograde, augmentation and fragments, and the motive inside a phrase.
  • Hear ornamental, rhythmic, harmonic and character variations of one theme.
  • Hear a late climax and an early one, and a chain that copies against one that wanders.

Full course

  • Implement diatonic operations on a motive and find the shortest chain of operations between two figures.
  • Count melodies under rules exactly by dynamic programming, and a dice game's distinct pieces and entropy.
  • Build a generate-and-test searcher with hard and soft critics, and a genetic algorithm with the same critics.

Research

  • Design a study that measures novelty and value separately for human and machine composers.

Practice

  • Sketch many drafts and judge them later; write fragments and rules that a game engine recombines.

Contents

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

  1. 0Draft after draftFoundations2 min
  2. 1The motive and its operationsFoundations3 min
  3. 2Developing variationFoundations3 min
  4. 3Kinds of variationFoundations2 min
  5. 4Planning tensionFoundations3 min
  6. 5Constraints as enginesFoundations3 min
  7. 6Dice gamesFoundations3 min
  8. 7Generate and test: the Illiac SuiteFoundations3 min
  9. 8Chains, grammars and evolutionPractice3 min
  10. 9A searcher with criticsPractice3 min
  11. 10Frontier: judging creativityResearch3 min
  12. Variation 42, recap and problemsAll tracks2 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.

Draft after draftFoundations2 min

Beethoven's sketchbooks of 1822 to 1824 show one tune approached in draft after draft. Now a program's drafts. Two eight-bar melodies, built from the same four-note idea over the same chords. A program wrote both, and then threw one of them away. Which did it keep, the first or the second?

It kept the second. The first was its very first draft, rejected at once for . The second was draft of : drafts were thrown away, and of the rest, this one scored best. By the end of this part you will know what the critics listen for, and you will have built them.

Composers have always searched. Beethoven planned to set Schiller's ode to joy from 1793, thirty years before the Ninth Symphony. His sketchbooks of 1822 to 1824 show the tune approached in draft after draft, and what survives on those pages is the search itself: ideas tried, varied, crossed out and tried again. Composing, seen this way, is search under constraints: generate, judge, keep the best. This part builds the generators and the judges.

And what did Beethoven's search find? Hear the theme's first two phrases, as the series' corpus has them.

Count its moves. Of , are steps to a neighbouring note and repeat a note. There is not a single leap. Years of search ended at the plainest material there is: a scale, walked, with one rhythmic surprise at the end of each phrase. Search does not mean complication; the hard part is the judging.

Here is the plan. The motive, the operations composers apply to it, and developing variation. The kinds of variation, and planning tension across a phrase. Constraints, counted exactly, and the dice games of the 1750s. Generate and test: the Illiac Suite, Markov chains, and evolution. A searcher with critics, and the drafts it threw away. And what creativity might mean, and how to judge a machine's.

1The motive and its operationsFoundations3 min

What can a composer do with four notes?

Composition textbooks start small. Here is a motive of ours: four notes, E, D, C, and then up a fifth to G. Its intervals are down a step, down a step, up a fifth; its rhythm is short, short, long, longer. Arnold Schoenberg, whose Fundamentals of Musical Composition is still used to teach this, defined a motive as intervals and rhythm combined to produce a memorable shape.

What can be done to it? The classical repertoire uses a short list of operations, here kept within the scale. Hear the motive and then eight of them in turn: turned upside down; played backwards; augmented, twice as slow; diminished, twice as fast; cut to a fragment; with its leap widened; in a new rhythm; and embellished.

Each keeps something and changes something. Inversion keeps the rhythm and the sizes of the steps, and flips their direction. Retrograde keeps everything and reverses time. Augmentation and diminution keep the shape and change the speed. A fragment keeps a piece, small enough to repeat and sequence. And the last three change one feature while keeping the rest recognisable.

A question for your ears. The motive, and then a changed version of it. Is the second the motive turned upside down, or played backwards?

Backwards. The long G came first, then the leap down a fifth, then C, D, E rising: the same notes in reverse order. Turned upside down, it would have started on E, risen by steps to G, and leapt down to C. Retrograde can be difficult to recognize: it reverses the order of durations and changes the opening, but recognition depends on the motive and listener.

One detail matters in practice. Inside a key, these operations are diatonic: steps are counted on the scale, not in semitones. Our motive moved up a step becomes F, E, D, A: the same steps on the scale, though some intervals change by a semitone. That keeps every version in the key, and makes the versions sound related rather than identical. Part 20's tonal answer in a fugue is the same compromise, made at one interval. In our code, every operation is a function from melodies to melodies, which is what lets a program search among them.

Motives carry whole pieces. In Beethoven's Fifth Symphony of 1808, four notes, three short and a long, carry the entire first movement. Bach's fugue subjects, from Part 20, are one line, inverted, augmented and overlapped in stretto. Wagner's leitmotifs, from Part 27, tie a motive to a character and transform it with the drama, and film and game scores, Part 44's subject, still work this way. Chapter two shows how a whole phrase grows from a motive.

2Developing variationFoundations3 min

How does a phrase grow from four notes?

How does a phrase grow from a motive? Schoenberg described a plan he called the sentence. A basic idea, then its repetition, often on another degree; in his eight-bar model each takes two bars, and since our motive is short, here each takes one. Then a continuation that breaks the idea into fragments and speeds up, liquidating it, until only the cadence is left. Beethoven's piano sonatas open this way again and again.

Here is a sentence of ours built from the motive. Bars one and two: the idea, then the idea a step higher. Bars three and four: its first three notes, falling in sequence. Bars five and six: the whole motive at twice the speed, falling again. Then a cadence. Listen for the motive in every bar.

Take stock. The sentence has notes, and every one before the cadence comes from the motive. Two operations do almost all the work, fragmentation and transposition, and then diminution. The widest leap is semitones, the motive's own fifth. The harmony moves twice a bar, chosen so that every strong beat is a chord tone. We made it by hand. The searcher of chapter nine has to find such plans for itself.

Schoenberg gave the technique a name in an essay of 1947, Brahms the Progressive: developing variation. Each new idea is a variation of an earlier one, so a piece unfolds without literal repetition. Brahms, and Beethoven before him, built long movements from a few motives this way. Unity comes from the source, and variety from the operations; the balance between them is what a composer manages. Schoenberg's own twelve-tone rows, Part 29, push the idea to its limit: everything from one ordering.

Can that balance be measured? Call unity pre-cadential figures from the motive or its first 2--3 notes, \ then up to two operations; ignore transposition and final duration, and variety unique normalized figures; \ transposed figures count as repetitions. Both are computable, because the operations are functions: a program can try them all, two deep. The draft the searcher kept in the opening question scores for unity and for variety. Critics that measure a balance are the heart of chapter nine.

3Kinds of variationFoundations2 min

What can change while a theme stays itself?

Variation is also a form of its own. In a theme and variations, a tune is stated and then varied again and again, each variation a section. Mozart wrote twelve on our Tune, about 1781. Bach's Goldberg Variations of 1741 keep the bass and the harmony, not the melody. Beethoven's Diabelli Variations of 1823 make thirty-three out of a waltz he mocked. Every variation answers one question: what is kept, and what is changed?

Hear the Tune's first two phrases, and then four variations of ours, one of each classic kind. Ornamental: a neighbour note decorating every beat. Rhythmic: every beat made long and short. Harmonic: the same melody over new chords. And a character variation: minor, slower, an octave lower.

Lay them out by feature. Each keeps most of the theme and changes one thing: the ornamental variation fills in between the beats; the rhythmic one changes only durations; the harmonic one only the chords, here starting on the sixth degree instead of the tonic; the character variation changes mode and speed, and lets the rest follow. A variation that changed everything would not be heard as a variation at all.

Some variations keep even less. The ground bass, the passacaglia and the chaconne keep only a bass line or a progression. In Purcell's Dido's Lament of 1689 the voice sings over a falling ground bass repeated eleven times. Jazz choruses, Part 39's subject, keep the changes and invent a new line each time. The more that is kept fixed, the more freedom the rest has: a constraint that frees. Chapter four plans where a phrase rises and falls.

4Planning tensionFoundations3 min

Where should a phrase reach its peak?

A phrase is also a shape in time: it tightens and relaxes. Listeners can trace that tension moment by moment, with agreement depending on the excerpts, task and listeners, as studies by Carol Krumhansl and later Morwaread Farbood illustrate. Pitch height, dissonance, tonal distance and note density can contribute, with effects that depend on context and listener expectations. Fred Lerdahl and Krumhansl predicted it from harmony in 2007; Farbood's model adds melody, loudness and tempo. Ours is crude, bar by bar: the height above middle C in octaves, plus the share of non-chord tones, plus the chord's distance from the tonic, plus notes per beat over two. A composer plans that curve: where it rises, where it peaks, and where it lets go.

Give chapter nine's searcher, which we will build, two plans for the same motive. One rises to a climax in bar six and falls to the cadence. The other is tense at once and relaxes from the middle on, with its strongest harmony, a dominant seventh, in bar two. The searcher scores each draft by how well its tension curve follows the plan: the correlation is for the first and for the second. The early plan is harder, because the motive must be stated plainly in bar one, where tension starts low.

Hear the two melodies the searcher kept, the late climax first. Listen for where each one feels most strained.

By our measure the first peaks in bar , high, over the supertonic chord before the final dominant; the second peaks in bar and then sinks for four bars. Whether your ear agreed is exactly the test a tension model has to pass.

Where should the peak go? Composition treatises put a phrase's high point late, about two-thirds of the way through or after. Part 21 tested the golden-section claims for whole movements, and found weak evidence once chance was allowed for. A late peak leaves time to fall back to the cadence; an early one needs something to sustain the rest. Planning tension is really planning expectation, which Part 46 measures in listeners. Chapter five counts what constraints do.

5Constraints as enginesFoundations3 min

Do rules make composing harder, or easier?

Count what rules do. Take melodies of notes on the white keys from middle C up two octaves. With no rules there are , about two and a half billion. Start and end on C, and remain. Allow no leap larger than a fifth: . Follow every leap with a step back: . No note three times running, and stay within an octave: . Five rules have cut the space by a factor of about a quarter of a million.

How can we count billions without listing them? A melody is built note by note, and what a rule needs to know about the past is small. Call it the state: the last note, the last move, how many repeats, the lowest and highest so far. The number of ways to finish from a state is the sum, over every allowed next note, of the ways to finish from the new state. That is a few thousand states and eight steps, under a second, instead of two and a half billion melodies. Part 16 counted Fux's counterpoint the same way.

Composers have said this for a long time. Stravinsky, in his Poetics of Music of 1942: the more constraints one imposes, the more one frees oneself. A constraint shrinks the space so that a composer can actually explore it. But a space can shrink to nothing: with too many rules, no melody obeys them all. The art is choosing constraints that leave a small but rich space. Rules, seen this way, are engines, not prohibitions.

Many styles are constraints that turned out to be engines. A canon, from Part 20, is a line that must also work against itself, delayed. Isorhythm, in Part 23, and the twelve-tone row, in Part 29, fix an order in advance. Bach's chorale preludes take a given hymn tune and invent everything else around it. And pop songwriting camps work from a title, a tempo and a deadline. Chapter six turns to the most mechanical constraint of all: a table and two dice.

6Dice gamesFoundations3 min

Can a pair of dice compose a minuet?

In 1757 Johann Philipp Kirnberger published a book whose title promises the ever-ready composer of polonaises and minuets. Carl Philipp Emanuel Bach followed in 1758, and others after him: a parlour game for people who could read music. The most famous, printed in 1792 under Mozart's name, may or may not be his. The trick is a table of bars: one column for each bar of the piece, and the dice choose the row. All the composing is in the table; the dice only choose.

Here is our own table, in the same format. Sixteen bars of a minuet across, and down the side the sums two dice can make, two to twelve: a hundred and seventy-six bars, every one ours, over a fixed plan of chords shown along the top. The eighteenth-century trick is in how the bars are made: every option for a bar starts on a tone of that bar's chord in the same register, so any option can follow any other, and the cadence bars, eight and sixteen, are the same in every row.

Throw the dice sixteen times and you have a minuet. Hear two, thrown with a seeded random generator, the first lit in gold, the second in blue.

How many minuets does the table hold? Naively, eleven choices for each of sixteen bars: eleven to the sixteenth, about forty-six million billion. But the cadence bars are the same in every row, and in some columns two sums choose the same bar. Distinct minuets are the product of each bar's distinct options: about sixteen million million, still far more than anyone could play. The two we just heard share of their sixteen bars. The 1792 table attributed to Mozart is usually quoted at about seven hundred and sixty million million, by the same reasoning.

There is a subtlety the games' printers ignored. Two dice do not choose evenly: a sum of seven comes six times in thirty-six, a two or a twelve once. So the bars in the middle row come up far more often, and some minuets are much likelier than others. Information theory gives one number for the game's variety, its entropy: bits, against if every distinct minuet were equally likely. A bit is one yes-or-no question; about forty-one bits is the entropy lower bound on its average binary description length, rather than a guarantee of an exact whole-number code length.

What is a dice game, as a method? It is a grammar with one rule per bar, and the composer wrote the grammar. The table is designed to make adjacent choices compatible within its harmonic plan, without guaranteeing every output's artistic quality, so nothing is judged after the throw: generate, and never test. The next step came two centuries later: generate freely, and then test. Chapter seven goes to a computer in Illinois, in 1957.

7Generate and test: the Illiac SuiteFoundations3 min

What did the first computer composer do?

In 1956 and 1957 Lejaren Hiller and Leonard Isaacson, at the University of Illinois, programmed the ILLIAC I computer to compose. The result, the Illiac Suite for string quartet of 1957, has four movements they called experiments, printed as a score and played by humans. The method: choose a note at random, test it against rules, and keep it or draw again. Their book, Experimental Music of 1959, describes composing as choice among possibilities. It is the dice game reversed: the generator is dumb, and the rules do the composing.

Their first experiment wrote short melodies like cantus firmi under rules from counterpoint. Ours are in the same spirit. Stay within an octave of middle C; no melodic tritone; no seventh or wider leap; no note three times running; after a leap larger than a fourth, a step back; and end on C, approached by step. Each note is drawn from the eight white keys of that octave, and after fifty failures in a row the line backs up one note.

Watch one run, draw by draw. The line starts on C. Each box is a draw: gold if the note was kept, grey with the rule it broke if not. This run needed draws for twelve notes, and most of its failures came at the very end, where only a C reached by step will do.

Here is the line that survived. It breaks no rule. It is correct, and not much more: the rules say what to avoid, and nothing about what to aim for. That gap is what the critics of chapter nine try to fill.

Run it times. On average a twelve-note line costs draws. The ending rejects the most, per cent of all rejections, then the rule that a leap must be recovered. Blind generation wastes most of its effort on the few places where the rules are tight; better generators, like the dice game's table, put the knowledge in before the draw.

The suite's four experiments climb in ambition. The first writes cantus firmi and then two and four voices in first-species counterpoint. The second builds four-part counterpoint, adding Fux's rules one at a time, so you can hear the music become more correct. The third generates rhythms, dynamics and playing techniques, and chromatic writing. And the fourth uses Markov chains: each note chosen by probabilities that depend on the notes before. Chapter eight takes up chains, grammars and evolution.

8Chains, grammars and evolutionPractice3 min

Can a program learn a style from examples?

A Markov chain learns a style from examples. Read the series' corpus of major-key folk and public-domain tunes, from Part 14. A chain of order one counts which note follows each note; a chain of order four, which note follows each run of four. To generate, start from a tune's opening and draw each next note from the counts for the last few. Order one has contexts to remember; order four has . This was Hiller and Isaacson's fourth experiment, and in the same year Brooks, Hopkins, Neumann and Wright trained chains on hymn tunes.

A question for your ears. Two melodies walked from Markov chains trained on the same tunes. One chain remembers only the last note; the other remembers the last four. Which one remembers four?

The second. The first chain makes each step plausible but wanders, with no sense of a phrase. The second sounds like real tunes over longer stretches, and the next chart shows why: because, in places, it is real tunes.

Measure the copying: the longest run of consecutive notes that appears, verbatim, in one of the corpus tunes. For order one, about notes on average over forty walks; short runs like these are just scales and repeated notes. For order four, about : whole phrases lifted from real tunes. In these walks, the higher-order chain produces longer exact corpus matches; this is not a theorem for every corpus or sampling method. This example trades local predictability against longer corpus matches; matching a passage is not by itself a legal or ethical finding of plagiarism. The same trade-off haunts today's generative models, in Parts 65 and 66.

Chains see only the last few notes. Grammars see structure. A grammar rewrites symbols into strings: a phrase into an antecedent and a consequent, a chord into a dominant and a tonic. Part 22 grew melodies from skeletons that way and parsed harmony with a probabilistic grammar. Grammars capture the nesting that chains miss: a phrase inside a period inside a section. Mark Steedman wrote one for the twelve-bar blues in 1984. But a grammar only generates; something still has to choose.

Evolution is another way to search. Keep a population of forty plans for eight bars. Score each with chapter nine's critics, zero if a hard critic refuses it. Breed the fitter: children take bars from two parents, and now and then a bar is redrawn at random. The best fitness climbs from to in generations, and the average follows it up. Genetic algorithms have composed jazz solos, in Al Biles's GenJam of 1994, among much else.

Here is the fittest melody after the last generation.

9A searcher with criticsPractice3 min

What does a program need in order to judge its own drafts?

Now the searcher itself. Its judges are the series' own rules, turned into functions. Hard critics refuse a draft outright: no forbidden leap, from Part 14; a cadence on C; a range no wider than a tenth; no parallel fifths or octaves with the bass between successive bar downbeats, a sampled check rather than every event; and at least three in four strong beats on chord tones. Soft critics score what survives, each from zero to one: leaps recovered by a step back; unity and variety, from chapter two; how well the tension follows the plan, from chapter four; chord tones, and flow.

The loop is Hiller and Isaacson's, with better parts. Generate a draft: a random developing variation, the motive stated first, then each bar a random chain of up to two operations, placed on a chord tone near where the last bar ended. Let the hard critics refuse it, and note why. Let the soft critics score it, and keep it if it beats the best so far. Two thousand times.

Of drafts, die on a forbidden leap, on parallels with the bass, on range, and on harmony. Only survive to be scored. Most deaths happen at the seams between bars: a figure moved to fit its chord leaps badly from the bar before. A composer's hand does that join without thinking; the searcher has to be told.

Hear three of the drafts it threw away, each for a different reason: .

Here is the best score so far, draft by draft, on a logarithmic axis. It improves times, the last at draft , and each improvement is smaller than the one before. Random search finds good drafts quickly and excellent ones slowly; a composer's training is, in part, a better generator.

And the draft it kept, the second melody of the opening question. Under each bar, how the critics traced it back to the motive: the motive itself in bars, on different degrees; varied in ; and the cadence.

Generate and test can be pushed much further. From 1981 David Cope's Experiments in Musical Intelligence wrote new pieces in the style of Bach, Chopin and Mozart. Its method was recombination: cut a composer's works into fragments and reassemble them where the voice leading matches, keeping intact the short patterns Cope called signatures. Some reported demonstrations found listeners had difficulty distinguishing selected outputs from historical pieces, without establishing universal indistinguishability. Its generator was the composer's own music, so it raises chapter eight's copying question by design.

10Frontier: judging creativityResearch3 min

How would we know if a machine were creative?

Is any of this creative? The most cited framework is Margaret Boden's, from The Creative Mind of 1990: creativity makes ideas that are new, surprising and valuable. It can be combinational, putting familiar ideas together in unfamiliar ways; exploratory, moving within a structured space of possibilities to find what it allows; or transformational, changing the space itself, so that ideas impossible before become possible. And an idea can be new to the one who has it, or new in history.

Place this part's programs in Boden's terms. The dice game, Cope's recombination and the order-four chain are combinational. The Illiac rules, our searcher and evolution are exploratory: they search a space someone else defined. None of ours is transformational: every program here keeps its rules fixed. History's transformations, like tonality loosened or the sampler turned into an instrument, changed what counted as music.

How should a machine's music be judged? Could a listener tell it from a human's? That is a weak test: it rewards imitation, and the answer depends on who listens. Graeme Ritchie proposed scoring outputs for novelty, typicality and quality, compared with what the system was shown. Anna Jordanous proposed fixing a definition of creativity in advance and evaluating against it, component by component. Marcus Pearce and Geraint Wiggins tested style models' outputs with expert listeners, and asked what each judgement actually measures. And copying has to be measured too; chapter eight's longest copied run is a start.

Much current research builds tools that compose with a person. They suggest a continuation, fill a gap or harmonise a line. Google's Bach Doodle of 2019 harmonised millions of melodies typed in by visitors. Bob Sturm and colleagues trained folk-rnn on folk tunes in 2016, and musicians played and edited what it wrote. Studies of such tools ask what actually helps a composer: control, steering by examples, and being surprised. Part 65 builds machines that compose, and Part 66 generative audio.

A concrete version. Let a searcher, a chain and a human composer each write melodies to the same brief. Measure every output's copying against everything its maker was shown. Collect listeners' judgements of value and of surprise, blind to who made what. Can novelty and value be measured separately, and do they trade off? An answer would turn the question, is it creative, into questions with numbers.

Variation 42, recap and problemsAll tracks2 min

Every part ends by doing something to the Tune with what it built. Here the searcher takes the Tune's first four notes, C, C, G, G, as its motive, and composes eight bars over chords of the Tune's kind. Of drafts it kept number ; below, faint, are four of the it threw away. You will hear the Tune's first phrase, and then the variation.

Row forty-two of the ledger: seconds; the measurement is the search itself: draft of kept, rejected by the critics, and scored.

What did we find? A motive and its operations are functions from melodies to melodies. Developing variation grows a phrase from four notes. Tension can be planned, and measured against the plan. Rules shrink the space of melodies, from two and a half billion to nine thousand. The dice games put the composer's knowledge in the table; generate and test puts it in the critics. And in this small corpus the higher-order chain generates longer matching passages; copying descriptors and listener judgments ask different questions.

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

Where does this come back? In performing, where the search continues on stage. In expectation and emotion. In the sequencer and the workstation. In machines that compose. And in generative audio.

And in practice. Composers keep sketchbooks, many drafts judged later with fresh ears. Songwriters write ten hooks to keep one. Game composers write rules and fragments that a program recombines during play, a dice game with a better table. And teachers set constraints: a motive, a form, a time limit.

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

Where it goes next. Performing in Part 43; expectation and emotion in Part 46; sequencers in Part 53; machines that compose in Part 65; generative audio in Part 66.

Key results

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

The funnel\(\displaystyle 15^8 = 2{,}562{,}890{,}625 \to 9{,}252 \text{ under }\allowbreak \text{five }\allowbreak \text{rules}\)
Two dice\(\displaystyle H = -\textstyle\sum_s p_s \log_2 p_s \approx 3.27 \text{ bits}\)
Our dice game\(\displaystyle \approx 1.6 \times 10^{13} \text{ minuets}, \ 41 \text{ bits}\)
Generate and test\(\displaystyle 277 \text{ draws }\allowbreak \text{for }\allowbreak \text{12 }\allowbreak \text{notes}\)
The searcher\(\displaystyle 2{,}000 \text{ drafts}: \ 164 \text{ scored}, \ \text{draft } 1{,}205 \text{ kept}\)

Try it

Lab 42 · Composing as search, computed

Write a motive and let the searcher develop it over your chords; count what your rules leave; and hear how much a Markov chain copies as its memory grows.

Figure produced by Lab 42: Composing as search, computed
Produced by the lab below, seed 0, in 3.3 s.
python -m videos.music.labs 42 needs numpy, scipy, matplotlib · download lab42.py · source on GitHub
drafts; rejected, by the first critic that refused                    1500; leaps 968, parallels 258, range 133, harmony 12
kept draft; its score                                                 1205; 0.887
unity, variety, tension fit, chord tones                              0.86, 0.50, 0.94, 0.80
how each bar derives from the motive                                  motive; motive; motive; first three notes+invert+augment; motive; first three notes+augment; -; -
8-note melodies on 15 white keys, adding RULES one at a time          2,562,890,625 -> 102,515,625 -> 800,243 -> 12,271 -> 9,872 -> 9,252
our dice game: distinct minuets; entropy (bits)                       16,203,045,600,000; 41.0
ear problem: the order of each chain melody, in order (listen first)  4 (copies 9 notes), 2 (copies 6 notes), 2 (copies 7 notes)

The generator only proposes; the critics decide. Hard critics refuse, soft critics rank, and the best survivor is kept; the funnel shows how fast rules shrink the space a generator has to search.
The code (80 lines; it asserts its own result)
"""Lab 42: composing as search, computed: operations on a motive, the constraint funnel, a dice game's count, and a
generate-and-test searcher whose critics you can change."""

import numpy as np

from videos.coursekit import labs
from explainer.music.monochord import SR, Clip, concat, mix
from explainer.music.monochord import composer as K
from explainer.music.monochord import melody as M
from videos.music.music42 import compute as C

TITLE = "Composing as search, computed"
GOAL = ("Write a motive and let the searcher develop it over your chords; count what your rules leave; and hear how "
        "much a Markov chain copies as its memory grows.")
TASKS = [
    "Edit MOTIVE (key number, onset in beats, length) and CHORDS. Does the searcher keep more drafts or fewer?",
    "Change PLAN (the tension curve, one number a bar). Does the kept melody's peak move with it?",
    "Change RULES (a subset of composer.FUNNEL_RULES) and LENGTH. Which rule cuts the most?",
]
MOTIVE = [(64, 0.0, 0.5), (62, 0.5, 0.5), (60, 1.0, 1.0), (67, 2.0, 2.0)]
CHORDS = ["I", "IV", "V", "I", "vi", "ii", "V", "I"]
PLAN = [1.0, 1.5, 2.0, 1.5, 2.5, 3.0, 2.5, 0.5]
DRAFTS = 1500
RULES = K.FUNNEL_RULES
LENGTH = 8


def run(seed=0):
    rng = np.random.default_rng(seed)
    lab = labs.Lab()
    bass = K.bass_line(CHORDS)
    r = K.compose(MOTIVE, CHORDS, bass, np.random.default_rng(seed), drafts=DRAFTS, plan=PLAN)
    assert sum(r["rejected"].values()) + r["survivors"] == DRAFTS
    lab.row("drafts; rejected, by the first critic that refused", f"{DRAFTS}; " + ", ".join(f"{k} {v}" for k, v in sorted(r["rejected"].items(), key=lambda kv: -kv[1])))
    if r["best"] is None:
        lab.row("kept", "nothing survived: loosen a rule or change the motive")
        best = None
    else:
        v = r["best"]["verdict"]
        best = r["best"]["melody"]
        lab.row("kept draft; its score", f"{r['best']['draft'] + 1}; {v['score']:.3f}")
        lab.row("unity, variety, tension fit, chord tones", f"{v['unity']:.2f}, {v['variety']:.2f}, {v['tension_fit']:.2f}, {v['harmony']:.2f}")
        lab.row("how each bar derives from the motive", "; ".join("motive" if d == () else ("-" if d is None else "+".join(d)) for d in (K.derivation(f, MOTIVE) for f in K.bar_figures(best))))
    counts = [K.count_funnel(LENGTH, rules=tuple(RULES[:k])) for k in range(len(RULES) + 1)]
    lab.row(f"{LENGTH}-note melodies on 15 white keys, adding RULES one at a time", " -> ".join(f"{c:,}" for c in counts))
    dc = K.dice_count(K.dice_table(seed + 42))
    lab.row("our dice game: distinct minuets; entropy (bits)", f"{dc['distinct']:,}; {dc['entropy_bits']:.1f}")

    # sound: the kept melody; ear problem: chains of random order
    parts = []
    if best is not None:
        parts.append(C.render(best, bass))
    seqs = {t.name: t.pitches for t in M.corpus() if t.mode == "major"}
    orders = []
    for i in range(3):
        o = int(rng.choice([1, 2, 4]))
        g = K.generate(K.markov(list(seqs.values()), o), 20, np.random.default_rng(seed * 10 + i))
        mel = [(72 + x, float(j), 1.0) for j, x in enumerate(g)]
        parts.append(C.render(mel, beat=0.3, tail=0.6))
        orders.append(f"{o} (copies {K.longest_copy(g, seqs)['run']} notes)")
    lab.audio = concat(parts, gap=1.0)
    lab.row("ear problem: the order of each chain melody, in order (listen first)", ", ".join(orders))

    fig, (ax1, ax2) = labs.figure(2)
    if best is not None:
        for m, a, d in best:
            ax1.plot([a, a + d * 0.95], [m, m], color=labs.GOLD, lw=5, solid_capstyle="butt")
        for b in range(len(CHORDS) + 1):
            ax1.axvline(4 * b, color="#3A4250", lw=0.8)
        ax1.set_title("the kept melody (bars of four beats)")
        ax1.set_xlabel("beat")
        ax2.plot(range(1, len(PLAN) + 1), PLAN, "--", color="#8A93A0", label="plan")
        ax2.plot(range(1, len(CHORDS) + 1), K.tension(best, CHORDS), "o-", color=labs.GOLD, label="kept melody")
        ax2.set_xlabel("bar")
        ax2.set_title("tension: the plan and the result")
        ax2.legend(fontsize=7)
    lab.fig = fig
    lab.note = ("The generator only proposes; the critics decide. Hard critics refuse, soft critics rank, and the best "
                "survivor is kept; the funnel shows how fast rules shrink the space a generator has to search.")
    return lab

Now change it

  1. Edit MOTIVE (key number, onset in beats, length) and CHORDS. Does the searcher keep more drafts or fewer?
  2. Change PLAN (the tension curve, one number a bar). Does the kept melody's peak move with it?
  3. Change RULES (a subset of composer.FUNNEL_RULES) and LENGTH. Which rule cuts the most?

Problems, with solutions

Try each problem before opening its solution.

  1. Compute. A dice game has 16 bars; bars 8 and 16 have one option, the rest 11 distinct ones. How many distinct pieces?

    Solution

    The choices are independent from bar to bar, so the counts multiply: 11^14 × 1 × 1 = 379,749,833,583,241, about 3.8 × 10^14. The table printed under Mozart's name is usually quoted at about 7.6 × 10^14 distinct minuets, by the same kind of count.

  2. Prove. Prove that the entropy of two dice's sum is about 3.27 bits, and that a piece's entropy is the sum over its bars.

    Solution

    The sum s has probability (6 − |s − 7|)/36 for s = 2, …, 12; −Σ p log₂ p = 3.274 bits. The bars are chosen by independent throws, and the entropy of independent choices adds: H(X₁, …, X₁₆) = Σ H(Xᵢ). When two sums choose the same bar, merge their probabilities first; that is why our game has 41.0 bits rather than 14 × 3.27 = 45.8 (the two cadence bars carry none).

  3. Ear. The lab plays melodies from chains of random order; say which order made each.

    Solution

    The lab prints the orders and how many notes each copied. Order 1 wanders with no phrase; order 2 makes short plausible turns; order 4 sounds like a real tune for long stretches, because it often is one.

  4. Build. Add a critic of your own to the searcher and compare what it keeps.

    Where to look. composer.judge collects the verdicts; add a measure (for example, the share of notes on the beat that repeat the previous note, or a penalty for the same rhythm in every bar), add it to the score or the hard list, and rerun compose with the same seed: compare the kept drafts and the rejection counts.

  5. ★ Can novelty and value be measured separately, and do they trade off?

    Where the frontier is. Have a searcher, a chain and human composers write to one brief; measure each output's copying against what its maker was shown; collect blind listener ratings of value and surprise; model value as a function of novelty, maker and listener.

Notes and sources

Sources

  • A. Schoenberg, Fundamentals of Musical Composition (1967) and "Brahms the Progressive" (1947).
  • J. P. Kirnberger, Der allezeit fertige Polonoisen- und Menuettencomponist (1757); the Musikalisches Würfelspiel attributed to Mozart (1792, K. 516f).
  • L. Hiller and L. Isaacson, Experimental Music: Composition with an Electronic Computer (1959); F. P. Brooks, A. L. Hopkins, P. G. Neumann and W. V. Wright, "An experiment in musical composition", IRE Transactions on Electronic Computers (1957).
  • C. L. Krumhansl, "A perceptual analysis of Mozart's Piano Sonata K. 282", Music Perception (1996); F. Lerdahl and C. L. Krumhansl, "Modeling tonal tension", Music Perception (2007); M. M. Farbood, "A parametric, temporal model of musical tension", Music Perception (2012).
  • I. Stravinsky, Poetics of Music (1942); M. J. Steedman, "A generative grammar for jazz chord sequences", Music Perception (1984); J. A. Biles, "GenJam: a genetic algorithm for generating jazz solos" (1994).
  • D. Cope, Experiments in Musical Intelligence (1996); M. A. Boden, The Creative Mind (1990; 2nd ed. 2004); G. Ritchie, "Some empirical criteria for attributing creativity to a computer program", Minds and Machines (2007); A. Jordanous, "A standardised procedure for evaluating creative systems", Cognitive Computation (2012); M. T. Pearce and G. A. Wiggins, "Evaluating cognitive models of musical composition" (2007).
  • C.-Z. A. Huang and others, "The Bach Doodle: approachable music composition with machine learning at scale" (2019); B. L. Sturm, J. F. Santos, O. Ben-Tal and I. Korshunova, "Music transcription modelling and composition using deep learning" (2016).
About this partfrom its README

Part 42 of a sixty-eight-part course in music (see the series plan and the syllabus), the second part of Act VII, The Craft. Beethoven's sketchbooks of 1822 to 1824 show the Ode to Joy approached in draft after draft; in 1757 Kirnberger published a way to compose minuets with dice; in 1957 a computer in Illinois wrote a string quartet by generating notes and rejecting those that broke rules. This part treats composing as search under constraints and builds a searcher: the motive and its operations, developing variation, kinds of variation, planned tension, constraints counted exactly, the dice games, generate and test, Markov chains, grammars and evolution, and a generate-and-test composer whose critics are the series' own rules, shown with the drafts it threw away. The tools are Monochord's (explainer/music/monochord/composer.py). Every motive, table and melody is ours or was generated here; the Ode to Joy (1824) and the Tune are in the public domain. Published findings are the ones listed under Sources.

  • Draft after draft. An ear question (two melodies from the same motive and chords: which did the program keep?); Beethoven's search; the Ode to Joy's first two phrases (29 moves: 20 steps, 9 repeated notes, no leap), heard; the plan.
  • 1. The motive and its operations. Schoenberg's definition; our motive (E D C G); eight operations, each heard; an ear question (upside down or backwards?); diatonic operations; motives that carry pieces.
  • 2. Developing variation. Schoenberg's sentence; a sentence of ours grown from the motive, heard (41 notes, every one before the cadence from the motive); what it is made of; "Brahms the Progressive"; unity and variety, measured.
  • 3. Kinds of variation. Theme and variations (Mozart's K. 265 on the Tune, the Goldberg and Diabelli variations); the Tune varied four ways, heard (ornamental, rhythmic, harmonic, character); what each keeps; grounds.
  • 4. Planning tension. What makes tension (Krumhansl; Farbood; Lerdahl and Krumhansl); one motive, two plans, with the searcher's results (correlation 0.94 with a late plan, 0.61 with an early one); both heard; where the peak goes.
  • 5. Constraints as engines. The funnel: 2,562,890,625 eight-note melodies on fifteen white keys, then 102,515,625, 800,243, 12,271, 9,872 and 9,252 as five rules are added, counted by dynamic programming; how; Stravinsky; constraints that made music.
  • 6. Dice games. Kirnberger (1757), C. P. E. Bach, the 1792 game printed under Mozart's name; our table of 176 bars; two minuets thrown, heard; the count (11^16 naively, about 1.6 × 10^13 distinct); what the dice favour (41.0 bits against 43.9 if every minuet were equally likely); what the dice game is.
  • 7. Generate and test: the Illiac Suite. Hiller and Isaacson; our rules; one run draw by draw; the line, heard; 200 runs (277 draws a line on average; 69% of rejections at the cadence); the four experiments.
  • 8. Chains, grammars and evolution. Markov chains over the series' 51 major-key tunes; an ear question (which chain remembers four notes?); copying measured (longest verbatim run: 6.1 notes for order 1, 11.7 for order 4); grammars; a genetic algorithm (best fitness 0.84 to 0.98 in 40 generations); its fittest melody, heard.
  • 9. A searcher with critics. Hard and soft critics from Parts 14, 16 and 18 and chapters 2 and 4; the loop; 2,000 drafts (1,312 refused for leaps, 332 for parallels, 178 for range, 14 for harmony; 164 scored); three rejected drafts, heard; the best score so far; the kept draft (number 1,205), heard; David Cope's recombination.
  • 10. Frontier: judging creativity. Boden's three kinds; this part's programs in her terms; evaluation (Ritchie; Jordanous; Pearce and Wiggins); co-creative tools; ★ research problem: can novelty and value be measured separately, and do they trade off?
  • Variation 42, recap and problems. The searcher composes eight bars from the Tune's first four notes (draft 1,554 of 3,000 kept; 2,829 rejected; 171 scored), shown with four of the drafts it threw away; the ledger; what we found; five problems; where it comes back; in practice; references; Part 43.
What is computed and built

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

Item What it computes Checked against
hook, search the searcher's 2,000 drafts, rejections, survivors and kept draft the counts add up (tests)
ode the Ode to Joy's moves steps + repeats + leaps (tests)
motive, quiz the eight operations; the quiz inverses and lengths (tests)
develop, kinds the sentence; four variations of the Tune —
tension the searcher aimed at two plans the later plan peaks later (tests)
funnel exact counts under growing rules brute force on small cases (tests)
dice the table, two minuets, distinct pieces, entropy 11^16; the entropy of two dice (tests)
illiac generate and test with backtracking every kept note obeys every rule (tests)
chains Markov chains of order 1 and 4; copying more memory copies more (tests)
evolve a genetic algorithm with the critics as fitness —
tune, variation Variation 42 the ledger (tests)

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

Sounds. Every clip is Part 7's piano (a struck string on a soundboard) with Part 38's plucked bass: physical models. There are no recordings.

What the models are, and are not. The critics are the series' rules, not a theory of what makes a good melody; they refuse and rank, and someone chose their weights. The tension measure is crude: height, non-chord tones, the chord's distance and density, bar by bar. The dice table is ours, built in the eighteenth-century format; Mozart's count is quoted. The chains learn from the series' small corpus of folk and public-domain tunes.

Notes

Unity checks pre-cadential normalized shapes from the motive or its initial fragments followed by up to two operations, ignoring transposition and the final duration. Variety counts unique normalized figures, so transpositions count as repeats. Parallel-motion checks sample consecutive bar downbeats. Tension scores, creativity labels and fitness are chosen proxies, not listener validation. Higher-order walks have longer matching runs in this small corpus, not a general law or a plagiarism determination. Dice entropy is a lower bound on average binary coding length; compatibility does not guarantee artistic quality.

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Hook: an ear question (which draft was kept?); Beethoven's search; the Ode to Joy's first two phrases heard and counted; the plan.
  2. The motive and its operations: a definition; eight operations heard; an ear question (upside down or backwards?); diatonic operations; motives that carry pieces.
  3. Developing variation: the sentence; a sentence of ours heard; what it is made of; Brahms the Progressive; unity and variety measured.
  4. Kinds of variation: theme and variations; the Tune varied four ways, heard; what each keeps; grounds.
  5. Planning tension: what makes tension; one motive, two plans; both heard; where the peak goes.
  6. Constraints as engines: the funnel counted; how; Stravinsky; constraints that made music.
  7. Dice games: Kirnberger and after; our table; two minuets heard; the count; what the dice favour; what the game is.
  8. Generate and test: Hiller and Isaacson; our rules; one run draw by draw; the line heard; 200 runs; the four experiments.
  9. Chains, grammars and evolution: Markov chains; an ear question (which remembers four?); copying measured; grammars; evolution; its best heard.
  10. A searcher with critics: the critics; the loop; 2,000 drafts and their rejections; rejected drafts heard; the climb; the kept draft heard; Cope.
  11. Frontier: Boden's three kinds; our programs in her terms; evaluation; co-creative tools; the research problem.
  12. Variation 42: composed by the searcher from the Tune's first four notes, shown with what it threw away. Outro: problems, payoffs.

Covers: the operations on a motive; developing variation; kinds of variation; planning tension and pacing; constraints as engines; dice games; the Illiac Suite; grammars, automata and evolution; Cope's experiments; what creativity might mean. Built and computed: monochord/composer.py: diatonic operations and the shortest chain between two figures; exact counts of melodies under growing rules (2,562,890,625 to 9,252 for eight notes, checked by brute force); a dice game of ours (176 bars, about 1.6 × 10^13 distinct minuets, 41.0 bits); generate and test with backtracking (277 draws a twelve-note line); Markov chains that copy more as they remember more (6.1 against 11.7 notes); a genetic algorithm; a generate-and-test composer whose critics are Act III's rules, with its rejected drafts kept (2,000 drafts, 164 scored, draft 1,205 kept). Variation 42: eight bars on the Tune's first four notes, composed by the searcher (draft 1,554 of 3,000), shown with four of the 2,829 drafts it threw away. Frontier: evaluating computational creativity (Boden, Ritchie, Jordanous, Pearce and Wiggins); co-creative tools (open: measuring novelty and value separately). Reading: Schoenberg, Fundamentals of Musical Composition; Hiller & Isaacson (1959); Boden.

Build the film

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

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

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