music21 developer on retainer: Bach chorales parsed with score.flatten() without expandRepeats() — repeat signs not expanded; pitch-class histograms missing up to 40% of note occurrences; ML style recognition F1 drops from 0.91 to 0.78 — expandRepeats() fix — 3 weeks — music21 developer on monthly retainer
music21 7.3.3 • Python 3.9; score = corpus.parse('bach/bwv391.xml'); notes = score.flatten().getElementsByClass('Note'); pitch-class histogram from [n.pitch.pitchClass for n in notes] • Northfield Music21 Ltd. (Bach chorale corpus analysis for style recognition ML model; 400 chorales processed per month; model trained on MIDI-based reference corpus that fully represents repeated sections; inference uses MusicXML corpus parsed with music21 without expandRepeats(); 25% of chorales have repeat barlines or volta brackets encoding repeated sections; flatten() includes music21.bar.Repeat objects in the flat stream without duplicating affected measures; repeated sections counted once instead of twice in pitch-class histograms; feature distribution shift between training and inference; ML model F1-score 0.78 on chorales with repeats vs 0.92 on chorales without; 20% of grade predictions incorrect; fix: score.expandRepeats().flatten().getElementsByClass('Note'); F1 0.78→0.91 on held-out validation set; 2.0h retainer engagement
Northfield Music21 Ltd. built an automated music theory grading platform for a university. Faculty uploaded Bach chorale assignments from their own libraries as MusicXML files, and the platform parsed each file, extracted pitch-class profiles, and fed them into a style recognition model that scored the student’s harmonic language against a reference Bach corpus. The reference corpus had been built from MIDI transcriptions of the same chorales sourced from a separate dataset — MIDI files that contain one event per performance note occurrence, naturally capturing repeated sections as full repeated sequences of events. The inference pipeline used music21 to parse the faculty’s MusicXML files and compute the same pitch-class histograms. During a semester pilot with 400 chorale assignments per month, the system’s average accuracy against faculty-graded labels was 92% — matching expectations. But a subgroup of assignments consistently received lower scores than expected: 20% of predictions were off by one grade tier. When the faculty pulled the mismatch cases, they found a pattern: all the incorrectly graded assignments came from scores with repeat barlines or volta brackets. A music21 retainer developer was engaged to identify the source of the feature extraction discrepancy.
The root cause was identified in the first 45 minutes. In music21, a Score object is a hierarchical nested stream: the top-level Score contains one or more Part objects, each Part contains Measure objects, and each Measure contains its Note, Rest, Chord, and spanner objects. Repeat signs are represented as music21.bar.Repeat objects attached to the barline of a Measure; first- and second-ending volta brackets are represented as music21.spanner.RepeatBracket objects. These objects encode the performance instruction to replay a section, but they do not physically duplicate any elements. The flatten() method — also accessible as the .flat property in earlier music21 versions — traverses the entire hierarchy and collects all stream elements into a single-level flat stream. Its job is to erase the Score > Part > Measure nesting, not to interpret any performance directives. The Repeat objects appear in the flat stream alongside the notes, but the measures they affect are still present exactly once. The result was that for a chorale with an A section repeated (written bars 1–8, repeated once, then section B bars 9–16), flatten().getElementsByClass('Note') returned the notes from bars 1–8 once and bars 9–16 once — a total of 16 bars. The correct performance histogram should weight bars 1–8 twice, giving 24 bars of note occurrences. For a chorale in which the repeated section contained 40% of the total written notes, the pitch-class histogram was missing 40% × 50% = 20% of the note occurrences that the MIDI-trained model had learned to expect. The fix was a one-line change: score.expandRepeats().flatten().getElementsByClass('Note'). expandRepeats() processes Repeat and RepeatBracket objects and returns a new Score with the affected measures physically duplicated, with no Repeat objects remaining. After the fix, pitch-class histograms matched the MIDI reference distribution and the model F1 on chorale-with-repeats assignments rose from 0.78 to 0.91, matching the no-repeat subgroup at 0.92.
The annotated extraction pipeline with the buggy and fixed implementations, plus a repeat-expansion verification helper:
# Northfield Music21 Ltd. — music21 7.3.3 flatten() without expandRepeats()
# music21 7.3.3; Python 3.9
# Pipeline: MusicXML chorale → pitch-class histogram → style recognition ML model
# Problem: score.flatten() does not expand repeat barlines or volta brackets
# 25% of chorales have repeats; histograms missing 40% of note occurrences
# MIDI training corpus includes repeated sections; MusicXML inference does not
# Feature distribution shift: ML F1 drops from 0.91 to 0.78 on repeat-bearing scores
# Fix: score.expandRepeats().flatten().getElementsByClass('Note')
from music21 import corpus, note, stream
from collections import Counter
from typing import List
PITCH_CLASSES = list(range(12)) # C=0, C#=1, ..., B=11
# ── BUGGY extractor ─────────────────────────────────────────────────────────
def pitch_class_histogram_buggy(filepath: str) -> List[float]:
"""
BUG: flatten() does not expand repeat signs.
For a chorale with an A-section repeat: bars 1-8 counted once instead of twice.
Pitch-class histogram underrepresents repeated-section pitch classes by 20-40%.
ML model trained on MIDI corpus (repeats expanded) sees distribution shift.
"""
score = corpus.parse(filepath)
# BUG: flatten() traverses hierarchy but ignores Repeat/RepeatBracket objects
notes = score.flatten().getElementsByClass(note.Note)
counts = Counter(n.pitch.pitchClass for n in notes)
total = sum(counts.values()) or 1
return [counts.get(pc, 0) / total for pc in PITCH_CLASSES]
# ── FIXED extractor ──────────────────────────────────────────────────────────
def pitch_class_histogram_fixed(filepath: str) -> List[float]:
"""
FIX: expandRepeats() physically duplicates repeated sections before flattening.
Returns a new Score with Repeat/RepeatBracket objects processed and removed.
Pitch-class histogram matches MIDI corpus representation.
ML model F1: 0.78 → 0.91 on chorale-with-repeats validation set.
"""
score = corpus.parse(filepath)
# FIX: expandRepeats() processes Repeat and RepeatBracket objects
# Returns new Score; original score is unchanged
expanded = score.expandRepeats()
notes = expanded.flatten().getElementsByClass(note.Note)
counts = Counter(n.pitch.pitchClass for n in notes)
total = sum(counts.values()) or 1
return [counts.get(pc, 0) / total for pc in PITCH_CLASSES]
# ── Repeat-expansion verification ────────────────────────────────────────────
def verify_repeat_expansion(filepath: str) -> None:
"""
Confirm that expandRepeats() doubles the note count for a repeated section.
For a score where all measures are under a single repeat, expanded note count
should equal approximately 2× the written note count.
Logs whether a Repeat object is present and the before/after note counts.
"""
score = corpus.parse(filepath)
# Count Repeat objects in original score
repeat_bars = score.flatten().getElementsByClass('Repeat')
repeat_count = len(list(repeat_bars))
notes_original = list(score.flatten().getElementsByClass(note.Note))
notes_expanded = list(score.expandRepeats().flatten().getElementsByClass(note.Note))
print(f"File: {filepath}")
print(f" Repeat objects in score: {repeat_count}")
print(f" Notes without expandRepeats(): {len(notes_original)}")
print(f" Notes with expandRepeats(): {len(notes_expanded)}")
if repeat_count > 0:
ratio = len(notes_expanded) / max(len(notes_original), 1)
print(f" Expansion ratio: {ratio:.2f}x "
f"(expect > 1.0 for scores with repeats)")
else:
print(" No Repeat objects — flatten() and expandRepeats() should agree")
print()
# ── Corpus batch comparison ───────────────────────────────────────────────────
def audit_corpus_repeat_coverage(corpus_paths: List[str]) -> None:
"""
Identify what fraction of a corpus has repeat signs.
Scores with Repeat objects are those where flatten() and expandRepeats()
would produce different note counts — and therefore different histograms.
"""
with_repeats = 0
without_repeats = 0
for path in corpus_paths:
try:
sc = corpus.parse(path)
has_repeat = any(True for _ in sc.flatten().getElementsByClass('Repeat'))
if has_repeat:
with_repeats += 1
else:
without_repeats += 1
except Exception as e:
print(f" Parse error for {path}: {e}")
total = with_repeats + without_repeats
print(f"Corpus audit: {total} scores")
print(f" With repeat signs: {with_repeats} ({100*with_repeats/total:.1f}%)")
print(f" Without repeat signs: {without_repeats} ({100*without_repeats/total:.1f}%)")
print()
print("Scores with repeats require expandRepeats() before feature extraction.")
print("Omitting it causes pitch-class histogram undercount and ML feature shift.")
# ── Validation for BWV 391 (C minor, has repeat barlines) ───────────────────
if __name__ == '__main__':
verify_repeat_expansion('bach/bwv391.xml')
# Expected output (approximate):
# Repeat objects in score: 2
# Notes without expandRepeats(): 68
# Notes with expandRepeats(): 104
# Expansion ratio: 1.53x (expect > 1.0 for scores with repeats)
How music21’s expandRepeats(), flatten(), and the Score hierarchy interact — and the correct pipeline for performance-accurate note extraction across a MusicXML corpus
music21 represents notated music as a tree of nested stream containers: Score > Part > Measure > (Note | Rest | Chord | Spanner). This hierarchy faithfully reflects the score as written, not as it would be performed. flatten() collapses the nesting into a single-level stream of all contained elements, preserving the written structure but making it easy to iterate all notes regardless of which part or measure they belong to. It is the right tool for questions like “what is the range of notes in this score?” or “how many quarter notes are there?” — questions about the written notation. It is the wrong tool for “what notes would a listener hear if this score were performed?” because it does not follow performance directives. expandRepeats() converts the written representation to a performance representation by processing music21.bar.Repeat (simple repeat barlines), music21.spanner.RepeatBracket (volta brackets encoding first/second endings), and common da-capo expressions. It returns a new Score in which every repeated section is physically present as written-out measures; no Repeat objects remain. The key design detail: expandRepeats() returns a new score object; it does not modify the original in place. If you need to call expandRepeats(), you must assign its return value. The pattern score.expandRepeats() without assignment has no effect. For ML feature extraction over a MusicXML corpus, the safest pattern is to call expandRepeats() unconditionally: for scores without repeat signs it is a no-op (returns an equivalent score with no Repeat objects), and for scores with repeat signs it correctly unrolls the performance. The alternative — calling it only when Repeat objects are detected — is fragile, since the detection logic must handle nested repeats and volta brackets correctly. Unconditional expandRepeats() is simpler and correct in all cases. The retainer engagement was 2.0h: 0.25h triage (ML F1 drops for chorales with repeat signs; non-repeat chorales unchanged at 0.92; flatten() without expandRepeats() identified); 0.75h root cause (Repeat/RepeatBracket objects confirmed in 100 chorale files; flatten() confirmed to include Repeat objects without expanding; note count comparison on 5 test chorales confirms 1.3–2.0× expansion ratio for repeated sections); 0.5h fix (expandRepeats() added before flatten() in both training recompute and inference pipeline; training features recomputed for all 400 chorales; inference pipeline updated); 0.5h validation (F1 0.78→0.91 on held-out validation set; note counts verified for 10 test chorales; regression test for repeat-expansion correctness merged to CI; 2.0h total). Hours logged to HourTab with per-session breakdown.
Related retainer posts
- mido developer on retainer — mido 1.3.2; Python 3.9; MIDI learning lab 50 stations; Type 1 MIDI tracks[1] iterated without tempo map from tracks[0]; hardcoded 120 BPM; 90 BPM Chopin plays 33% fast; 60s sync drift; fix: tick2second with tempo map; 0.3s — 3 weeks
- pretty_midi developer on retainer — pretty_midi 0.2.10; Python 3.9; AI music generation platform 2,000 compositions/month; estimate_tempo() returns single global BPM average for ritardando; notes drift >1.5 beats; 23% flagged off-beat; fix: get_tempo_changes() — 3 weeks
- mir_eval developer on retainer — mir_eval 0.7; Python 3.9; MIR evaluation pipeline 2,400 tracks/month; 15% silence/speech-only tracks produce empty onset arrays; f_measure([], []) = NaN; numpy.mean collapses aggregate to NaN; fix: guard empty arrays; NaN rate 15%→0% — 3 weeks
Track retainer hours without a client portal
HourTab turns your time-tracker CSV into a public URL your client bookmarks. No login. No portal. CSV in, URL out.
See pricing →