From a5ff2c2c9a635a06c0e51336773e3a880cb28725 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Cancino-Chac=C3=B3n?= Date: Mon, 9 Nov 2026 16:37:49 +0100 Subject: [PATCH 1/3] add DPDannenberg symbolic follower --- matchmaker/dp/__init__.py | 1 + matchmaker/dp/dannenberg.py | 228 ++++++++++++++++++++++++++++++++++++ matchmaker/methods.yaml | 23 ++++ matchmaker/registry.py | 11 ++ 4 files changed, 263 insertions(+) create mode 100644 matchmaker/dp/dannenberg.py diff --git a/matchmaker/dp/__init__.py b/matchmaker/dp/__init__.py index c5ff8156..a2e12ef2 100644 --- a/matchmaker/dp/__init__.py +++ b/matchmaker/dp/__init__.py @@ -8,6 +8,7 @@ - Event: onset-level features (MIDI) """ +from .dannenberg import DPDannenberg from .oltw_arzt import ( OnlineTimeWarpingArzt, OnlineTimeWarpingArztEvent, diff --git a/matchmaker/dp/dannenberg.py b/matchmaker/dp/dannenberg.py new file mode 100644 index 00000000..a2bbb289 --- /dev/null +++ b/matchmaker/dp/dannenberg.py @@ -0,0 +1,228 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +""" +Dannenberg 1985 dynamic-programming polyphonic score follower. + +Re-implementation of the dynamic grouping matcher from: + + Bloch, J. & Dannenberg, R.B. (1985). Real-Time Computer Accompaniment + of Keyboard Performances. Proc. ICMC, 279-289. + +The matcher processes MIDI note-ons individually through a DP matrix +whose rows are score compound events (cevts = pitch sets at each onset) +and whose columns are individual performance notes. The algorithm finds +the association that maximises a rating function penalising wrong and +missing notes (Sec. 3, 6). Epsilon and epsilon-fraction tests (Sec. 5) +group incoming notes into performance cevts for confidence checking. + +Classes: + DPDannenberg -- windowed DP matcher (event-level, MIDI only) +""" + +from typing import List, Optional, Set + +import numpy as np +from numpy.typing import NDArray + +from matchmaker.base import OnlineAlignment + + +class DPDannenberg(OnlineAlignment): + """Windowed DP matcher (Bloch & Dannenberg 1985, Sec. 6). + + Rows of the DP matrix are score compound events (one pitch set per + unique onset beat); columns are individual performance MIDI notes. + Each incoming note updates one column by considering three + predecessors -- same row (extend), diagonal (advance and match), and + vertical (skip note) -- choosing the one that maximises the rating. + + Parameters + ---------- + reference_features : list of set of int + MIDI pitch set for each score onset (one per ``score_positions`` + entry). + score_positions : np.ndarray + Beat position of each score onset. + queue : optional + Input queue for streaming. + c_m : float + Cost per missing score note when advancing past a score cevt + (Sec. 8, default 0.5). + c_e : float + Cost per extra performance note not in the current score cevt + (Sec. 8, default 0.0). + epsilon : float + Absolute time threshold (seconds) for grouping notes into the + same performance cevt (Sec. 5, default 0.090 s). + epsilon_fraction : float + Fraction of predicted next-cevt time for the relative grouping + test (Sec. 5, default 0.25). + window : int + Number of score cevts ahead of the current best match to + consider (default 50). + tempo : float + Initial tempo in BPM, used to seed the epsilon-fraction test + and position interpolation (default 120.0). + smoothing : float + Exponential smoothing coefficient for tempo tracking + (default 0.5). + """ + + def __init__( + self, + reference_features, + score_positions: NDArray, + queue=None, + c_m: float = 0.5, + c_e: float = 0.0, + epsilon: float = 0.090, + epsilon_fraction: float = 0.25, + window: int = 50, + tempo: float = 120.0, + smoothing: float = 0.5, + **kwargs, + ): + super().__init__( + reference_features=reference_features, + score_positions=score_positions, + queue=queue, + ) + self.score_cevts = reference_features + self.n_states = len(reference_features) + self.c_m = c_m + self.c_e = c_e + self.epsilon = epsilon + self.epsilon_fraction = epsilon_fraction + self.window = window + self.smoothing = smoothing + + self._values = np.zeros(self.n_states, dtype=np.float64) + self._used: List[Set[int]] = [set() for _ in range(self.n_states)] + self._prev_values = np.zeros(self.n_states, dtype=np.float64) + self._prev_used: List[Set[int]] = [set() for _ in range(self.n_states)] + + self._best_value = float("-inf") + self._best_row = 0 + + self._prev_note_time: Optional[float] = None + + self._beats_per_second = tempo / 60.0 + self._anchor_beat = float(score_positions[0]) + self._anchor_time = 0.0 + self._prev_match_time: Optional[float] = None + self._prev_match_beat: Optional[float] = None + + def _is_new_cevt(self, note_time: float) -> bool: + """Epsilon and epsilon-fraction tests (Sec. 5, p. 283-284).""" + if self._prev_note_time is None: + return True + dt = note_time - self._prev_note_time + if dt > self.epsilon: + return True + if ( + self._beats_per_second > 0 + and self._best_row + 1 < self.n_states + ): + beat_gap = float( + self.score_positions[self._best_row + 1] + - self.score_positions[self._best_row] + ) + predicted_dt = beat_gap / self._beats_per_second + if predicted_dt > 0 and dt > self.epsilon_fraction * predicted_dt: + return True + return False + + def step(self, features) -> None: + pitch = int(np.atleast_1d(features)[0]) + note_time = self.current_perf_time + + if self._is_new_cevt(note_time): + pass + self._prev_note_time = note_time + + lo = max(0, self._best_row - 10) + hi = min(self.n_states, self._best_row + self.window) + + # Shift columns: save current as previous (Sec. 6, p. 285). + for r in range(lo, hi): + self._prev_values[r] = self._values[r] + for r in range(lo, hi): + self._prev_used[r] = self._used[r].copy() + + # DP update: one column per performance note (Fig. 6-2, p. 285). + for r in range(lo, hi): + B = self.score_cevts[r] + + y_val = self._prev_values[r] + y_used = self._prev_used[r] + + z_val = y_val + z_used = y_used.copy() + + if pitch not in B: + z_val -= self.c_e + + if pitch in B: + if pitch not in y_used: + z_val = y_val + 1 + z_used = y_used | {pitch} + + if r > lo: + A = self.score_cevts[r - 1] + w_val = self._prev_values[r - 1] + w_used = self._prev_used[r - 1] + missing_in_A = len(A - w_used) + d = w_val + 1 - self.c_m * missing_in_A + if d > z_val: + z_val = d + z_used = {pitch} + + if r > lo: + A = self.score_cevts[r - 1] + x_val = self._values[r - 1] + x_used = self._used[r - 1] + missing_in_A = len(A - x_used) + v = x_val - self.c_m * missing_in_A + if v >= z_val: + z_val = v + z_used = set() + + self._values[r] = z_val + self._used[r] = z_used + + best_r = lo + int(np.argmax(self._values[lo:hi])) + best_v = self._values[best_r] + + if best_v > self._best_value: + self._best_value = best_v + self._best_row = best_r + self.current_index = best_r + + beat = float(self.score_positions[best_r]) + if self._prev_match_time is not None: + elapsed = note_time - self._prev_match_time + advanced = beat - self._prev_match_beat + if elapsed > 0.05 and 0 < advanced < 16: + rate = advanced / elapsed + self._beats_per_second = ( + self.smoothing * self._beats_per_second + + (1 - self.smoothing) * rate + ) + + self._anchor_beat = beat + self._anchor_time = note_time + self._prev_match_time = note_time + self._prev_match_beat = beat + + def get_current_position(self) -> float: + drift = self._beats_per_second * ( + self.current_perf_time - self._anchor_time + ) + pos = self._anchor_beat + drift + if self.current_index + 1 < self.n_states: + cap = float(self.score_positions[self.current_index + 1]) + pos = min(pos, cap) + return pos + + def is_still_following(self) -> bool: + return self.current_index < self.n_states - 1 diff --git a/matchmaker/methods.yaml b/matchmaker/methods.yaml index cb325226..3d9c8ee3 100644 --- a/matchmaker/methods.yaml +++ b/matchmaker/methods.yaml @@ -347,6 +347,29 @@ methods: observation_type: midi num_particles: 500 + dannenberg: + class: matchmaker.dp:DPDannenberg + reference: score_cevts + event_based: true + args: + reference_features: {from: reference_features} + score_positions: {from: score_positions} + queue: {from: queue} + tempo: {from: tempo} + config_passthrough: + exclude: [piano_range, return_pitch_list] + processor_args: + return_pitch_list: true + piano_range: false + default_kwargs: + processor: pitch + c_m: 0.5 + c_e: 0.0 + epsilon: 0.090 + epsilon_fraction: 0.25 + window: 50 + smoothing: 0.5 + # --- parangonar trackers; all four differ only by the ``method`` string --- # # They read the live stream themselves rather than being fed frames, so diff --git a/matchmaker/registry.py b/matchmaker/registry.py index c83c433d..47eab2c2 100644 --- a/matchmaker/registry.py +++ b/matchmaker/registry.py @@ -211,6 +211,17 @@ def _reference_korzeniowski(mm): return score_processor(mm.score_part) +@reference_builder("score_cevts") +def _reference_score_cevts(mm): + """Score compound events: one MIDI pitch set per unique onset beat.""" + na = mm.score_part.note_array() + onset_beats = np.unique(na["onset_beat"]) + return [ + set(na["pitch"][na["onset_beat"] == ob].tolist()) + for ob in onset_beats + ] + + # --------------------------------------------------------------------------- # Argument resolution # --------------------------------------------------------------------------- From 7e27d1f6f6c441971771114019917d22f700c425 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Cancino-Chac=C3=B3n?= Date: Mon, 9 Nov 2026 17:04:32 +0100 Subject: [PATCH 2/3] add tests and typing for DPDannenberg --- matchmaker/dp/dannenberg.py | 64 ++++++--- tests/test_dannenberg.py | 279 ++++++++++++++++++++++++++++++++++++ 2 files changed, 324 insertions(+), 19 deletions(-) create mode 100644 tests/test_dannenberg.py diff --git a/matchmaker/dp/dannenberg.py b/matchmaker/dp/dannenberg.py index a2bbb289..9760a558 100644 --- a/matchmaker/dp/dannenberg.py +++ b/matchmaker/dp/dannenberg.py @@ -19,12 +19,13 @@ DPDannenberg -- windowed DP matcher (event-level, MIDI only) """ -from typing import List, Optional, Set +from typing import Any, List, Optional, Set import numpy as np from numpy.typing import NDArray from matchmaker.base import OnlineAlignment +from matchmaker.io.queue import RECVQueue class DPDannenberg(OnlineAlignment): @@ -68,11 +69,36 @@ class DPDannenberg(OnlineAlignment): (default 0.5). """ + score_cevts: List[Set[int]] + n_states: int + c_m: float + c_e: float + epsilon: float + epsilon_fraction: float + window: int + smoothing: float + + _values: NDArray[np.float64] + _used: List[Set[int]] + _prev_values: NDArray[np.float64] + _prev_used: List[Set[int]] + + _best_value: float + _best_row: int + + _prev_note_time: Optional[float] + + _beats_per_second: float + _anchor_beat: float + _anchor_time: float + _prev_match_time: Optional[float] + _prev_match_beat: Optional[float] + def __init__( self, - reference_features, - score_positions: NDArray, - queue=None, + reference_features: List[Set[int]], + score_positions: NDArray[np.floating[Any]], + queue: Optional[RECVQueue] = None, c_m: float = 0.5, c_e: float = 0.0, epsilon: float = 0.090, @@ -80,8 +106,8 @@ def __init__( window: int = 50, tempo: float = 120.0, smoothing: float = 0.5, - **kwargs, - ): + **kwargs: Any, + ) -> None: super().__init__( reference_features=reference_features, score_positions=score_positions, @@ -97,20 +123,20 @@ def __init__( self.smoothing = smoothing self._values = np.zeros(self.n_states, dtype=np.float64) - self._used: List[Set[int]] = [set() for _ in range(self.n_states)] + self._used = [set() for _ in range(self.n_states)] self._prev_values = np.zeros(self.n_states, dtype=np.float64) - self._prev_used: List[Set[int]] = [set() for _ in range(self.n_states)] + self._prev_used = [set() for _ in range(self.n_states)] self._best_value = float("-inf") self._best_row = 0 - self._prev_note_time: Optional[float] = None + self._prev_note_time = None self._beats_per_second = tempo / 60.0 self._anchor_beat = float(score_positions[0]) self._anchor_time = 0.0 - self._prev_match_time: Optional[float] = None - self._prev_match_beat: Optional[float] = None + self._prev_match_time = None + self._prev_match_beat = None def _is_new_cevt(self, note_time: float) -> bool: """Epsilon and epsilon-fraction tests (Sec. 5, p. 283-284).""" @@ -132,7 +158,7 @@ def _is_new_cevt(self, note_time: float) -> bool: return True return False - def step(self, features) -> None: + def step(self, features: Any) -> None: pitch = int(np.atleast_1d(features)[0]) note_time = self.current_perf_time @@ -153,7 +179,7 @@ def step(self, features) -> None: for r in range(lo, hi): B = self.score_cevts[r] - y_val = self._prev_values[r] + y_val = float(self._prev_values[r]) y_used = self._prev_used[r] z_val = y_val @@ -169,7 +195,7 @@ def step(self, features) -> None: if r > lo: A = self.score_cevts[r - 1] - w_val = self._prev_values[r - 1] + w_val = float(self._prev_values[r - 1]) w_used = self._prev_used[r - 1] missing_in_A = len(A - w_used) d = w_val + 1 - self.c_m * missing_in_A @@ -178,11 +204,11 @@ def step(self, features) -> None: z_used = {pitch} if r > lo: - A = self.score_cevts[r - 1] - x_val = self._values[r - 1] + A_skip = self.score_cevts[r - 1] + x_val = float(self._values[r - 1]) x_used = self._used[r - 1] - missing_in_A = len(A - x_used) - v = x_val - self.c_m * missing_in_A + missing_in_A_skip = len(A_skip - x_used) + v = x_val - self.c_m * missing_in_A_skip if v >= z_val: z_val = v z_used = set() @@ -191,7 +217,7 @@ def step(self, features) -> None: self._used[r] = z_used best_r = lo + int(np.argmax(self._values[lo:hi])) - best_v = self._values[best_r] + best_v = float(self._values[best_r]) if best_v > self._best_value: self._best_value = best_v diff --git a/tests/test_dannenberg.py b/tests/test_dannenberg.py new file mode 100644 index 00000000..7789aa12 --- /dev/null +++ b/tests/test_dannenberg.py @@ -0,0 +1,279 @@ +"""Tests for the Dannenberg 1985 DP score follower. + +Test scenario based on Figure 2.7 from: + + Bloch, J. & Dannenberg, R.B. (1985). Real-Time Computer Accompaniment + of Keyboard Performances. Proc. ICMC, 279-289. + +Score (three chords at beats 0, 1, 2): + A0 = {A3, G4, E4} = {57, 67, 64} + A1 = {G4} = {67} + A2 = {A3, B3, C4} = {57, 59, 60} + +Performance: the score notes played in order with ~30-50 ms spacing +within each chord, plus an extra D4 (62) inserted before the third +chord. +""" + +import unittest + +import numpy as np + +from matchmaker.dp.dannenberg import DPDannenberg + + +def _make_follower(**overrides): + """Build a DPDannenberg for the three-chord Figure 2.7 example.""" + score_cevts = [{57, 67, 64}, {67}, {57, 59, 60}] + score_positions = np.array([0.0, 1.0, 2.0]) + defaults = dict( + reference_features=score_cevts, + score_positions=score_positions, + tempo=120.0, + window=50, + c_m=0.5, + c_e=0.0, + epsilon=0.090, + epsilon_fraction=0.25, + smoothing=0.5, + ) + defaults.update(overrides) + return DPDannenberg(**defaults) + + +def _feed(follower, notes): + """Feed (pitch, time) pairs through __call__.""" + for pitch, t in notes: + follower(np.array([pitch]), t) + + +class TestDPDannenbergInit(unittest.TestCase): + def test_state_dimensions(self): + f = _make_follower() + self.assertEqual(f.n_states, 3) + self.assertEqual(len(f._values), 3) + self.assertEqual(len(f._used), 3) + self.assertEqual(len(f._prev_values), 3) + self.assertEqual(len(f._prev_used), 3) + + def test_initial_position(self): + f = _make_follower() + self.assertEqual(f.current_index, 0) + self.assertAlmostEqual(f.get_current_position(), 0.0) + + def test_initial_tempo(self): + f = _make_follower(tempo=60.0) + self.assertAlmostEqual(f._beats_per_second, 1.0) + + def test_is_still_following_at_start(self): + f = _make_follower() + self.assertTrue(f.is_still_following()) + + +class TestDPDannenbergStep(unittest.TestCase): + """DP update logic using the three-chord example.""" + + def test_first_chord_all_notes_matched(self): + """All three notes of chord A0 should be matched.""" + f = _make_follower() + _feed(f, [ + (57, 0.00), # A3 + (67, 0.03), # G4 + (64, 0.05), # E4 + ]) + self.assertEqual(f.current_index, 0) + self.assertAlmostEqual(f._values[0], 3.0) + self.assertEqual(f._used[0], {57, 67, 64}) + + def test_advance_to_second_chord(self): + """After chord A0 is done, a G4 at a later time advances to A1.""" + f = _make_follower() + _feed(f, [ + (57, 0.00), + (67, 0.03), + (64, 0.05), + (67, 0.50), # G4 — matches A1 + ]) + self.assertEqual(f.current_index, 1) + + def test_extra_note_no_penalty_default_c_e(self): + """With c_e=0 an extra D4 does not decrease the best value.""" + f = _make_follower(c_e=0.0) + _feed(f, [ + (57, 0.00), + (67, 0.03), + (64, 0.05), + (67, 0.50), + ]) + val_before = f._best_value + _feed(f, [(62, 0.80)]) # D4 extra + self.assertGreaterEqual(f._best_value, val_before) + + def test_extra_note_with_c_e_penalty(self): + """With c_e > 0 an extra note not in B subtracts from z_val.""" + f = _make_follower(c_e=1.0) + _feed(f, [ + (57, 0.00), + (67, 0.03), + (64, 0.05), + (67, 0.50), + ]) + val_before = float(f._values[f.current_index]) + _feed(f, [(62, 0.80)]) # D4 extra — penalty applied + val_after = float(f._values[f.current_index]) + self.assertLess(val_after, val_before + 1) + + def test_full_performance_reaches_last_chord(self): + """Play all chords; the follower should reach A2.""" + f = _make_follower() + _feed(f, [ + (57, 0.00), # A0: A3 + (67, 0.03), # A0: G4 + (64, 0.05), # A0: E4 + (67, 0.50), # A1: G4 + (62, 0.80), # extra D4 + (57, 1.00), # A2: A3 + (59, 1.03), # A2: B3 + (60, 1.05), # A2: C4 + ]) + self.assertEqual(f.current_index, 2) + + def test_is_still_following_false_at_end(self): + """Once the last score event is matched, is_still_following is False.""" + f = _make_follower() + _feed(f, [ + (57, 0.00), + (67, 0.03), + (64, 0.05), + (67, 0.50), + (57, 1.00), + (59, 1.03), + (60, 1.05), + ]) + self.assertFalse(f.is_still_following()) + + def test_missing_note_c_m_penalty(self): + """c_m penalty reduces diagonal advance value for missing notes.""" + f_no = _make_follower(c_m=0.0) + f_hi = _make_follower(c_m=1.0) + notes = [ + (57, 0.00), + (67, 0.03), + (67, 0.50), + ] + _feed(f_no, notes) + _feed(f_hi, notes) + # With c_m=0 no penalty for the missing E4 in A0; with c_m=1 + # the advance to row 1 loses 1 point for the missing note. + self.assertGreater(f_no._values[1], f_hi._values[1]) + + +class TestDPDannenbergIsNewCevt(unittest.TestCase): + """Epsilon and epsilon-fraction grouping (Sec. 5).""" + + def test_first_note_is_always_new(self): + f = _make_follower() + self.assertTrue(f._is_new_cevt(0.0)) + + def test_note_within_epsilon_is_same_cevt(self): + f = _make_follower(epsilon=0.090) + f._prev_note_time = 0.0 + self.assertFalse(f._is_new_cevt(0.05)) + + def test_note_beyond_epsilon_is_new_cevt(self): + f = _make_follower(epsilon=0.090) + f._prev_note_time = 0.0 + self.assertTrue(f._is_new_cevt(0.10)) + + def test_epsilon_fraction_triggers_new_cevt(self): + f = _make_follower(epsilon=1.0, epsilon_fraction=0.1) + f._prev_note_time = 0.0 + f._beats_per_second = 2.0 + f._best_row = 0 + # beat_gap = 1.0, predicted_dt = 0.5, threshold = 0.05 + self.assertTrue(f._is_new_cevt(0.06)) + + def test_epsilon_fraction_no_trigger_when_close(self): + f = _make_follower(epsilon=1.0, epsilon_fraction=0.5) + f._prev_note_time = 0.0 + f._beats_per_second = 2.0 + f._best_row = 0 + # beat_gap = 1.0, predicted_dt = 0.5, threshold = 0.25 + self.assertFalse(f._is_new_cevt(0.20)) + + def test_epsilon_fraction_skipped_at_last_row(self): + f = _make_follower(epsilon=1.0, epsilon_fraction=0.01) + f._prev_note_time = 0.0 + f._best_row = 2 # last row + # No next row to compute beat_gap, so only epsilon matters. + self.assertFalse(f._is_new_cevt(0.5)) + + +class TestDPDannenbergGetCurrentPosition(unittest.TestCase): + def test_position_at_anchor(self): + f = _make_follower() + f._anchor_beat = 1.0 + f._anchor_time = 0.5 + f.current_perf_time = 0.5 + self.assertAlmostEqual(f.get_current_position(), 1.0) + + def test_position_interpolated(self): + f = _make_follower(tempo=120.0) + f._anchor_beat = 0.0 + f._anchor_time = 0.0 + f.current_perf_time = 0.25 + pos = f.get_current_position() + # 120 BPM = 2 beats/s, 0.25s drift = 0.5 beats + self.assertAlmostEqual(pos, 0.5) + + def test_position_capped_at_next_beat(self): + f = _make_follower(tempo=120.0) + f._anchor_beat = 0.0 + f._anchor_time = 0.0 + f.current_index = 0 + f.current_perf_time = 5.0 # way ahead + pos = f.get_current_position() + # Capped at score_positions[1] = 1.0 + self.assertAlmostEqual(pos, 1.0) + + def test_position_not_capped_at_last_state(self): + f = _make_follower(tempo=120.0) + f._anchor_beat = 2.0 + f._anchor_time = 1.0 + f.current_index = 2 # last state + f.current_perf_time = 1.5 + pos = f.get_current_position() + # No cap since current_index + 1 == n_states + self.assertAlmostEqual(pos, 3.0) + + +class TestDPDannenbergTempoTracking(unittest.TestCase): + def test_tempo_updates_on_advance(self): + f = _make_follower(tempo=120.0, smoothing=0.0) + _feed(f, [ + (57, 0.00), + (67, 0.03), + (64, 0.05), + ]) + initial_bps = f._beats_per_second + _feed(f, [(67, 1.00)]) # advance to beat 1.0 at time 1.0 + # With smoothing=0, the tempo is purely the new rate. + # beat advance = 1.0, time elapsed ~1.0 → rate ~ 1.0 + self.assertNotAlmostEqual(f._beats_per_second, initial_bps) + + def test_smoothing_blends_old_and_new(self): + f = _make_follower(tempo=120.0, smoothing=0.5) + _feed(f, [ + (57, 0.00), + (67, 0.03), + (64, 0.05), + ]) + _feed(f, [(67, 1.00)]) + # smoothing=0.5 blends: 0.5 * 2.0 + 0.5 * new_rate + bps = f._beats_per_second + self.assertGreater(bps, 0.5) + self.assertLess(bps, 3.0) + + +if __name__ == "__main__": + unittest.main() From 342ae3dd911bd0cf0548c8362499b304b2ce1a8d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Cancino-Chac=C3=B3n?= Date: Tue, 10 Nov 2026 18:56:41 +0100 Subject: [PATCH 3/3] fix issues with initial window --- matchmaker/dp/dannenberg.py | 9 ++++++++- tests/test_dannenberg.py | 13 +++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/matchmaker/dp/dannenberg.py b/matchmaker/dp/dannenberg.py index 9760a558..84fcb9fe 100644 --- a/matchmaker/dp/dannenberg.py +++ b/matchmaker/dp/dannenberg.py @@ -122,9 +122,16 @@ def __init__( self.window = window self.smoothing = smoothing + # Initial column (before any performance note): matching must start + # at the first score cevt, so row r begins with the cost of missing + # every note in cevts 0..r-1 (rather than 0 everywhere, which would + # allow a wrong first note to lock onto any row in the window). + sizes = np.array([len(c) for c in reference_features], dtype=np.float64) self._values = np.zeros(self.n_states, dtype=np.float64) + if self.n_states > 1: + self._values[1:] = -self.c_m * np.cumsum(sizes)[:-1] self._used = [set() for _ in range(self.n_states)] - self._prev_values = np.zeros(self.n_states, dtype=np.float64) + self._prev_values = self._values.copy() self._prev_used = [set() for _ in range(self.n_states)] self._best_value = float("-inf") diff --git a/tests/test_dannenberg.py b/tests/test_dannenberg.py index 7789aa12..3382dd10 100644 --- a/tests/test_dannenberg.py +++ b/tests/test_dannenberg.py @@ -48,6 +48,19 @@ def _feed(follower, notes): class TestDPDannenbergInit(unittest.TestCase): + def test_initial_column_penalises_skipped_cevts(self): + f = _make_follower() + np.testing.assert_allclose(f._values, [0.0, -1.5, -2.0]) + + def test_wrong_first_note_does_not_jump_to_end(self): + # Score C-D-E; performance starts with a wrong E. + f = _make_follower( + reference_features=[{60}, {62}, {64}], + score_positions=np.array([0.0, 1.0, 2.0]), + ) + _feed(f, [(64, 0.0)]) + self.assertTrue(f.is_still_following()) + def test_state_dimensions(self): f = _make_follower() self.assertEqual(f.n_states, 3)