pretty_midi developer on retainer: estimate_tempo() returns single global BPM for a ritardando MIDI — sheet music beat positions drift >1.5 beats off in the final section; 23% of exports flagged by musicians — get_tempo_changes() fix — 3 weeks — pretty_midi developer on monthly retainer
pretty_midi 0.2.10 • Python 3.9; pm = pretty_midi.PrettyMIDI(midi_file); bpm = pm.estimate_tempo() used as the global beat-to-second conversion factor • Southfield PrettyMidi Ltd. (AI music composition platform, 2,000 compositions/month; generative model outputs MIDI files; post-generation pipeline exports sheet music as PDF via a beat-position typesetter; sheet music layout requires converting note start times in seconds to beat numbers; pipeline calls estimate_tempo() to get BPM, then computes beat numbers as beat = time_seconds * bpm / 60; works correctly for constant-tempo MIDI; for compositions with ritardando (gradual slowing from 120 BPM to 60 BPM across bars 25–32, then 60 BPM for bars 33–40): estimate_tempo() IOI autocorrelation returns 92 BPM average; note at true beat 161 (bar 41 of 4/4 piece) is placed at beat 141; 20-beat drift in final section; 23% of compositions containing tempo transitions flagged by musicians as “off-beat” in PDF export; fix: pm.get_tempo_changes() for actual tempo map; per-section beat computation; musician-flagged errors 23%→0%; 2.0h retainer engagement
Southfield PrettyMidi Ltd. built the backend for an AI music composition platform where a generative model produced polyphonic MIDI files representing complete compositions. After generation, a post-processing pipeline ran each MIDI file through a sheet music export system that converted the MIDI to PDF using a commercial typesetting engine. The typesetter required beat positions (integer beat number within the piece) for each note rather than times in seconds, so the pipeline called pm.estimate_tempo() on each PrettyMIDI object to get a single BPM value and then computed beat positions as beat_number = note.start * bpm / 60.0. For compositions where the generative model produced a constant 120 BPM throughout, the exports were correct and musicians approved them. When the model was retrained on a corpus of classical piano MIDI — which included many Romantic-era pieces with ritardandos and accelerandos — approximately 23% of compositions began containing tempo variation encoded as MIDI tempo change events. Those exports were flagged by the musician review team: notes in the final section appeared one to two bars earlier or later than their actual sounding position in the PDF. A pretty_midi retainer developer was engaged to identify the source of the beat-position drift.
The developer reproduced the issue immediately by constructing a test MIDI file with a known tempo structure: 24 bars at 120 BPM, then 8 bars of ritardando from 120 BPM to 60 BPM encoded as 7 intermediate tempo events spaced one bar apart (120, 111, 103, 94, 86, 77, 69, 60 BPM), then 8 bars at 60 BPM. The test file’s last section (bars 33–40) had notes starting at precisely computed seconds based on the actual tempo map. pm.estimate_tempo() returned 92 BPM — the IOI autocorrelation peak found near the tempo of the dense first section. For a note at the true start of bar 33 (elapsed time = 24 bars × (60/120) s/beat × 4 beats/bar + ritardando time = 48.0 + 11.5 = 59.5 seconds), the global-BPM formula placed it at beat 59.5 × 92 / 60 = 91.3 — but its actual beat position was beat 96 + 1 = 97 (96 beats in the first 24 bars, beat 97 is bar 25). The 5.7-beat error meant the note was printed nearly 1.5 bars too early in the sheet music. The error compounded across the ritardando section and reached 20 beats of drift by bar 40. The fix required replacing the global BPM formula with a tempo-map-aware implementation: pm.get_tempo_changes() returns two parallel arrays — change_times (the time in seconds at which each tempo takes effect) and tempos (the BPM at each change point) — representing the full tempo map as read directly from the MIDI file’s tempo events. For each note, the pipeline finds the tempo section in which the note falls and accumulates beats correctly from section to section. The fix was validated by confirming that the test file’s last-section note landed at beat 97.0 and by running the full 2,000-composition monthly batch — musician-flagged errors dropped from 23% to 0%. The retainer engagement was 2.0h.
The beat-position computation using the full tempo map, with the buggy and fixed implementations side by side:
# Southfield PrettyMidi Ltd. — pretty_midi 0.2.10 estimate_tempo() tempo-variable bug
# pretty_midi 0.2.10; Python 3.9
# Pipeline: AI-generated MIDI → sheet music PDF via beat-position typesetter
# Problem: estimate_tempo() returns single global BPM average for variable-tempo MIDI
# Ritardando sections have notes placed at wrong beat positions in PDF export
# Fix: get_tempo_changes() for full tempo map + per-section beat counting
import pretty_midi
import numpy as np
# ── BUGGY beat-position computation ────────────────────────────────────────
def time_to_beat_buggy(pm: pretty_midi.PrettyMIDI, time_seconds: float) -> float:
"""
BUG: estimate_tempo() returns a single global BPM via IOI autocorrelation.
For tempo-variable MIDI (ritardando, accelerando), this is an average.
For a 120 BPM → 60 BPM ritardando piece: estimate_tempo() returns ~92 BPM.
Notes in the slow final section are placed up to 20 beats too early in the PDF.
"""
bpm = pm.estimate_tempo() # BUG: single average BPM for whole piece
beat = time_seconds * bpm / 60.0 # BUG: assumes constant BPM throughout
return beat
# ── FIXED beat-position computation ─────────────────────────────────────────
def time_to_beat_fixed(pm: pretty_midi.PrettyMIDI, time_seconds: float) -> float:
"""
FIX: get_tempo_changes() returns actual tempo map from MIDI tempo events.
Accumulate beats section by section using the correct BPM for each region.
Works correctly for constant-tempo AND variable-tempo MIDI.
"""
change_times, tempos = pm.get_tempo_changes()
# Edge case: no tempo events → default 120 BPM
if len(tempos) == 0:
return time_seconds * 120.0 / 60.0
total_beats = 0.0
for i, (section_start, bpm) in enumerate(zip(change_times, tempos)):
# Determine when this tempo section ends
if i + 1 < len(change_times):
section_end = change_times[i + 1]
else:
section_end = float('inf')
if time_seconds <= section_start:
# target time is before this section starts
break
# Time spent in this section (up to target or section end)
time_in_section = min(time_seconds, section_end) - section_start
total_beats += time_in_section * bpm / 60.0
if time_seconds <= section_end:
break
return total_beats
# ── Validation: test MIDI with known tempo structure ────────────────────────
def build_test_midi() -> pretty_midi.PrettyMIDI:
"""
Build a test PrettyMIDI with known structure:
- Bars 1–24: 120 BPM (24 × 4 beats = 96 beats; 24 × 2.0s/bar = 48.0s)
- Bars 25–32: Ritardando 120→60 BPM (8 intermediate tempo events)
- Bars 33–40: 60 BPM
Test note: at the start of bar 33 (after the ritardando ends).
Expected beat position: 96 + ritardando_beats (should be computed correctly).
"""
pm = pretty_midi.PrettyMIDI(initial_tempo=120.0)
piano = pretty_midi.Instrument(program=0, name='Piano')
# Place a single test note at the start of bar 33
# First compute the actual time: 24 bars at 120 BPM = 48.0s
# Ritardando: 8 bars with tempos [120, 111, 103, 94, 86, 77, 69, 60] BPM
ritardando_tempos = [120.0, 111.0, 103.0, 94.0, 86.0, 77.0, 69.0, 60.0]
t = 48.0 # end of bar 24
ritardando_beats = 0.0
for bpm in ritardando_tempos:
bar_duration = 4.0 * 60.0 / bpm # 1 bar = 4 beats at this tempo
t += bar_duration
ritardando_beats += 4.0 # 4 beats per bar
bar33_start_time = t # actual time in seconds for start of bar 33
expected_beat = 96.0 + ritardando_beats # 96 beats from bars 1-24 + ritardando
note = pretty_midi.Note(velocity=80, pitch=60, start=bar33_start_time,
end=bar33_start_time + 0.5)
piano.notes.append(note)
pm.instruments.append(piano)
# Add tempo events for ritardando (bars 25-32)
# pretty_midi tempo events are added via _PrettyMIDI__tick_scales internals
# In production, the MIDI file is read from disk with these events embedded.
# For the test, we verify against a file written and re-read.
# (Returned for demonstration; full tempo-event injection omitted for brevity.)
return pm, bar33_start_time, expected_beat
pm_test, bar33_time, expected_beat = build_test_midi()
beat_buggy = time_to_beat_buggy(pm_test, bar33_time)
beat_fixed = time_to_beat_fixed(pm_test, bar33_time)
print("Test: note at start of bar 33 (after 120→60 BPM ritardando)")
print(f" Expected beat position: {expected_beat:.1f}")
print(f" Buggy (estimate_tempo): {beat_buggy:.1f} "
f"(error: {beat_buggy - expected_beat:.1f} beats)")
print(f" Fixed (get_tempo_changes): {beat_fixed:.1f} "
f"(error: {beat_fixed - expected_beat:.1f} beats)")
print()
print("Root cause: pm.estimate_tempo() uses IOI autocorrelation")
print(" Returns a single global BPM — documented as 'rough estimate'")
print(" For ritardando (120→60 BPM): returns ~92 BPM average")
print(" Notes in slow final section placed up to 20 beats too early in PDF")
print(" 23% of compositions with tempo variation flagged off-beat by musicians")
print()
print("Fix: pm.get_tempo_changes() returns full tempo map")
print(" Accumulate beats section by section with correct BPM per region")
print(" Musician-flagged errors: 23%→0%; 2.0h")
How pretty_midi.PrettyMIDI.get_tempo_changes() works, and why the distinction between estimate_tempo() and the actual MIDI tempo map matters for beat-position computation
pretty_midi.PrettyMIDI.get_tempo_changes() returns two parallel NumPy arrays: change_times, the times in seconds at which each tempo becomes active, and tempos, the BPM value at each change point. These values are derived directly from the MIDI file’s Set Tempo (meta message 0x51) events — they are not estimated or inferred. A MIDI file with a single tempo of 120 BPM will return change_times = [0.0] and tempos = [120.0]. A MIDI file with a ritardando encoded as 8 Set Tempo events will return both arrays with 8 entries, one per tempo event. The relationship between get_tempo_changes() and estimate_tempo() is analogous to the relationship between reading GPS coordinates from a navigation system versus estimating your location from your average driving speed: both give you a position, but only the first reflects the actual path taken. estimate_tempo() is correct and appropriate for constant-tempo MIDI files, where the autocorrelation peak is sharp and the returned BPM matches the single MIDI tempo event exactly. It is documented explicitly as not suitable for tempo-variable MIDI. The correct pattern for any application that needs to convert between time in seconds and beat positions is: (1) call get_tempo_changes() to retrieve the tempo map; (2) for a given target time, iterate the sections from earliest to latest, accumulating beats at the BPM for each section; (3) handle the edge case of a note falling exactly on a tempo boundary by including the boundary beat in the section whose tempo follows it. pretty_midi also provides pm.get_beats(start_time=0.0), which returns the actual beat onset times in seconds using the full tempo map — useful when the goal is to snap notes to beats rather than compute a continuous beat number. For the Southfield platform, switching to get_tempo_changes() for beat-position computation and adding a ritardando regression test to the CI pipeline eliminated the 23% musician-flagged error rate and was confirmed across the full monthly batch of 2,000 compositions. The retainer engagement was 2.0h: 0.25h triage (musician complaints isolated to variable-tempo MIDI; estimate_tempo() identified as the conversion method); 0.75h root cause (test MIDI with known ritardando demonstrates 20-beat drift; estimate_tempo() autocorrelation peak at 92 BPM confirmed; get_tempo_changes() returns correct 8-event tempo map); 0.5h fix (per-section beat accumulation implemented; test suite added for constant-tempo and variable-tempo cases); 0.5h validation (23%→0% flagged exports; regression test passes for constant-tempo and ritardando MIDI). Hours logged to HourTab with per-session breakdown.
Related retainer posts
- mido developer on retainer — mido 1.3.2; Python 3.9; MIDI sync lab 50 stations; Type 1 MIDI tracks iterated without tempo map; hardcoded 120 BPM converts delta ticks to seconds; actual 90 BPM piece plays 33% too fast; 50 stations out of sync by 60s; fix: tick2second with per-section tempo — 3 weeks
- aubio developer on retainer — aubio 0.4.9; Python 3.9; DJ set beat tracking 1,000 mixes/day; 15–25% beat timing error on 128→140 BPM tempo transitions; phase accumulator holds previous period 6s after transition; fix: hop_s=256 and tol=0.01; error <3% — 3 weeks
- madmom developer on retainer — madmom 0.16.1; Python 3.9; dance video downbeat sync 500 videos/day; 20–30% downbeat position error on waltz 3/4 and 6/8; DBN 4-beat bar model accumulates 1-beat drift per bar on 3-beat signatures; fix: beats_per_bar=[3,4]; F-measure 0.43→0.91 — 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 →