"""DTW 与移调搜索测试。""" from __future__ import annotations import numpy as np import pytest from qbh.config import DEFAULT from qbh.dtw import _cost_matrix, _dp_matrix, align, shift_candidates, subsequence_dtw from qbh.melody import Melody def _melody(midis, note_s=0.5, song_id="t") -> Melody: midis = np.asarray(midis, dtype=float) return Melody(midis, np.arange(midis.size) * note_s, np.full(midis.size, note_s * 0.9), song_id) def _naive_dp(cost: np.ndarray) -> np.ndarray: rows, cols = cost.shape D = np.full((rows, cols), np.inf) D[0, :] = cost[0, :] for i in range(1, rows): for j in range(cols): best = D[i - 1, j] if j > 0: best = min(best, D[i, j - 1], D[i - 1, j - 1]) D[i, j] = cost[i, j] + best return D def test_vectorized_dp_matches_naive(): rng = np.random.default_rng(0) cost = rng.random((9, 14)) * 3.0 assert np.allclose(_dp_matrix(cost), _naive_dp(cost)) def test_fragment_alignment_finds_correct_span(): target = _melody(list(range(60, 75))) query = target.slice(4, 12) result = subsequence_dtw(query, target, shift=0.0, cfg=DEFAULT, need_path=True) assert result.cost == pytest.approx(0.0, abs=1e-6) assert result.target_note_start == 4 assert result.target_note_end == 11 assert result.sim == pytest.approx(1.0, abs=1e-6) def test_transposed_query_needs_shift(): target = _melody(list(range(60, 75))) query = target.slice(4, 12).transpose(5) good = subsequence_dtw(query, target, shift=-5.0, cfg=DEFAULT) bad = subsequence_dtw(query, target, shift=0.0, cfg=DEFAULT) assert good.cost < bad.cost assert good.sim > 0.95 def test_shift_candidates_cover_octave_offsets(): target = _melody([60, 62, 64, 67, 69, 67, 64, 62]) query = target.transpose(17) # 跨八度的移调 candidates = shift_candidates(query, target, DEFAULT) assert -17 in candidates def test_shift_candidates_cover_plain_transposition(): target = _melody([60, 62, 64, 67, 69]) query = target.transpose(-5) candidates = shift_candidates(query, target, DEFAULT) assert 5 in candidates def test_align_picks_best_shift_automatically(): target = _melody([60, 62, 64, 67, 69, 67, 64, 62, 60, 62]) query = target.slice(1, 7).transpose(4) result = align(query, target, DEFAULT) assert result.shift == pytest.approx(-4.0) assert result.sim > 0.9 def test_duration_cost_penalizes_tempo_mismatch(): target = _melody([60, 62, 64, 67]) fast = target.scaled(0.25) # 时值全变成 1/4 cost = _cost_matrix(fast, target, 0.0, DEFAULT) assert cost.mean() > 0.0 def test_empty_melody_alignment(): target = _melody([60, 62, 64]) result = subsequence_dtw(Melody.empty(), target, cfg=DEFAULT) assert result.cost == float("inf") assert result.sim == 0.0