Files

71 lines
2.4 KiB
Python

"""倒排索引测试。"""
from __future__ import annotations
import numpy as np
from qbh.config import DEFAULT
from qbh.index import NgramIndex, quantize_direction, quantize_magnitude, quantize_rhythm
from qbh.melody import Melody
def _melody(midis, song_id="m", note_s=0.5) -> 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 test_quantizers():
assert list(quantize_magnitude(np.array([0.1, 1.0, 2.0, 4.0, 6.0, 12.0]))) == [0, 1, 2, 3, 4, 5]
assert list(quantize_direction(np.array([2.0, 0.0, -2.0]))) == [2, 1, 0]
assert list(quantize_rhythm(np.array([0.0, 0.45, -0.9]))) == [0, 1, -2]
def test_build_and_gram_count():
index = NgramIndex(cfg=DEFAULT)
index.build([_melody([60, 62, 64, 67, 69, 67, 64, 62], "a"),
_melody([72, 71, 69, 67, 65], "b")])
assert index.n_songs == 2
assert index.n_grams() > 0
def test_score_is_transposition_invariant():
index = NgramIndex(cfg=DEFAULT)
base = _melody([60, 62, 64, 67, 69, 67, 64, 62], "a")
index.build([base, _melody([72, 71, 69, 67, 65, 64, 62, 60], "b")])
score_original = index.score(base)
score_shifted = index.score(base.transpose(9))
assert score_original.get("a", 0) > 0.8
assert abs(score_original.get("a", 0) - score_shifted.get("a", 0)) < 1e-9
def test_candidates_contain_answer():
index = NgramIndex(cfg=DEFAULT)
target = _melody([60, 62, 64, 67, 69, 71, 72, 71, 69, 67, 64, 62], "target")
others = [_melody([60, 60, 67, 67, 69, 69, 67, 67], f"o{i}") for i in range(8)]
index.build([target] + others)
query = target.slice(2, 9).transpose(4)
candidates, _ = index.candidates(query)
ids = [sid for sid, _ in candidates]
assert "target" in ids
def test_empty_melody_scores_nothing():
index = NgramIndex(cfg=DEFAULT)
index.build([_melody([60, 62, 64], "a")])
assert index.score(Melody.empty()) == {}
def test_save_load_roundtrip(tmp_path):
index = NgramIndex(cfg=DEFAULT)
index.build([_melody([60, 62, 64, 67, 69], "a"), _melody([72, 71, 69, 67], "b")])
path = tmp_path / "index.json"
index.save(path)
restored = NgramIndex.load(path, DEFAULT)
assert restored.n_songs == index.n_songs
assert restored.n_grams() == index.n_grams()
query = _melody([60, 62, 64, 67], "q")
assert restored.score(query) == index.score(query)