"""Unit tests for Stage 4 pitch processing (Hz to MIDI and octave error correction).""" import numpy as np import pytest from unmix.pipeline.s4_pitch import correct_octave_errors, hz_to_midi def test_hz_to_midi_standards(): # A4 = 440 Hz -> MIDI 69 # A3 = 220 Hz -> MIDI 57 # C4 = 261.6256 Hz -> MIDI 60 hz = np.array([440.0, 220.0, 261.6256]) midi = hz_to_midi(hz) assert midi[0] == pytest.approx(69.0, abs=0.01) assert midi[1] == pytest.approx(57.0, abs=0.01) assert midi[2] == pytest.approx(60.0, abs=0.01) def test_correct_octave_errors(): # Line with an octave spike in the middle: 60, 72 (+12 jump), 61 syllables = [ {"text": "A", "midi": 60.0}, {"text": "B", "midi": 72.0}, # Isolated octave jump {"text": "C", "midi": 61.0}, ] corrected = correct_octave_errors(syllables) assert corrected[0]["midi"] == 60.0 assert corrected[1]["midi"] == pytest.approx(60.0) # Corrected from 72 down to 60 assert corrected[2]["midi"] == 61.0 def test_no_correction_for_legitimate_contour(): # Gradual rise: 60 -> 64 -> 67 (C major triad arpeggio) syllables = [ {"text": "A", "midi": 60.0}, {"text": "B", "midi": 64.0}, {"text": "C", "midi": 67.0}, ] corrected = correct_octave_errors(syllables) assert corrected[1]["midi"] == 64.0 def test_voiced_run_end_bridges_short_gaps(): import numpy as np from unmix.pipeline.s4_pitch import voiced_run_end hop = 0.01 v = np.zeros(300, dtype=bool) v[100:150] = True # 1.00-1.50 s v[155:200] = True # gap of 0.05 s, then voiced until 2.00 s v[260:290] = True # separate run after a 0.6 s gap assert voiced_run_end(v, 1.0, hop, max_gap_sec=0.1, cap_t=5.0) == pytest.approx(2.0) assert voiced_run_end(v, 1.0, hop, max_gap_sec=0.0, cap_t=5.0) == pytest.approx(1.5) # cap stops the run assert voiced_run_end(v, 1.0, hop, max_gap_sec=0.1, cap_t=1.3) <= 1.31 def test_voiced_run_end_bridges_longer_gap_only_if_voicing_resumes(): import numpy as np from unmix.pipeline.s4_pitch import voiced_run_end hop = 0.01 v = np.zeros(400, dtype=bool) v[100:150] = True # 1.00-1.50 s v[170:230] = True # gap 0.20 s, then a long run (0.60 s) until 2.30 s v[250:260] = True # gap 0.20 s, then a short run (0.10 s) kwargs = {"resume_max_gap_sec": 0.3, "resume_min_run_sec": 0.3} assert voiced_run_end(v, 1.0, hop, 0.1, 5.0, **kwargs) == pytest.approx(2.3) # without the resume rule the 0.2 s gap ends the run assert voiced_run_end(v, 1.0, hop, 0.1, 5.0) == pytest.approx(1.5)