Cubase-MCP-GAJ3T.MusicGen.R.../tests/unit/test_articulations.py

530 lines
18 KiB
Python

"""Synthetic compiler tests; numbers here are not vendor instrument mappings."""
from fractions import Fraction
from pathlib import Path
from typing import Literal
import pytest
from riff_groove_builder.articulations import ArticulationCompileError, compile_score
from riff_groove_builder.errors import SerializationError, UnsupportedArticulationError
from riff_groove_builder.midi import validate_event_plan
from riff_groove_builder.profiles import (
CCAction,
InstrumentProfile,
InvalidProfileError,
KeyswitchAction,
parse_profile,
)
from riff_groove_builder.schemas import (
ControlChangeEvent,
DrumNote,
EventPlan,
MusicalIntent,
NoteOffEvent,
NoteOnEvent,
Part,
PitchedNote,
PositiveBeat,
RationalBeat,
Score,
ScoreTrack,
TimeSignature,
)
FIXTURES = Path(__file__).resolve().parents[1] / "fixtures" / "profiles"
def profile(part: Part = "lead") -> InstrumentProfile:
return parse_profile((FIXTURES / f"synthetic-{part}.json").read_bytes())
def beat(value: Fraction | int) -> RationalBeat:
value = Fraction(value)
return RationalBeat(numerator=value.numerator, denominator=value.denominator)
def note(
start: Fraction | int = 0,
duration: Fraction | int = 1,
*,
pitch: int = 60,
art: str = "normal",
intensity: float = 0.5,
part: Literal["lead", "bass"] = "lead",
) -> PitchedNote:
return PitchedNote(
part=part,
pitch=pitch,
articulation=art,
intensity=intensity,
start=beat(start),
duration=PositiveBeat.model_validate(beat(duration).model_dump()),
)
def score(notes: list[PitchedNote], *, origin: Fraction | int = 0) -> Score:
part: Part = notes[0].part if notes else "lead"
return Score(
intent=MusicalIntent(
description="SYNTHETIC compiler test",
parts=[part],
tempo_bpm=120,
bars=1,
time_signature=TimeSignature(numerator=4, denominator=4),
key="C major",
seed=0,
),
start=beat(origin),
end=beat(Fraction(origin) + 4),
tracks=[ScoreTrack(part=part, notes=[*notes])],
)
def controls(plan: EventPlan) -> list[tuple[int, str, int, int]]:
return [
(
e.tick,
e.kind,
e.controller if isinstance(e, ControlChangeEvent) else e.note,
e.value if isinstance(e, ControlChangeEvent) else e.velocity,
)
for e in plan.tracks[0].events
if isinstance(e, ControlChangeEvent) or e.role == "keyswitch"
]
def test_combined_latched_dedup_polyphony_and_restore() -> None:
source = score(
[
note(0, 1, art="Palm Mute", intensity=0),
note(Fraction(1, 2), 1, pitch=64, art="pm", intensity=1),
note(2, 1, art="normal"),
note(3, 1, art="sustain"),
]
)
plan = compile_score(source, {"lead": profile()})
assert (plan.musical_start_tick, plan.musical_end_tick, plan.end_tick) == (120, 3960, 3960)
assert controls(plan) == [
(0, "note_on", 2, 64),
(0, "control_change", 20, 64),
(60, "note_off", 2, 0),
(1920, "note_on", 1, 64),
(1920, "control_change", 20, 0),
(1980, "note_off", 1, 0),
]
assert [
e.velocity
for e in plan.tracks[0].events
if isinstance(e, NoteOnEvent) and e.role == "musical_note"
] == [30, 100, 64, 64]
assert source.tracks[0].notes[0].articulation == "Palm Mute"
validate_event_plan(plan)
@pytest.mark.parametrize("mechanism", ["keyswitch", "cc", "velocity"])
def test_individual_action_mechanisms(mechanism: str) -> None:
selected = profile()
for art in selected.articulations:
art.actions = [a for a in art.actions if a.kind == mechanism]
plan = compile_score(score([note(art="pm")]), {"lead": selected})
assert plan.musical_start_tick == (0 if mechanism == "velocity" else 120)
observed = controls(plan)
if mechanism == "keyswitch":
assert observed == [(0, "note_on", 2, 64), (60, "note_off", 2, 0)]
elif mechanism == "cc":
assert observed == [(0, "control_change", 20, 64)]
else:
assert observed == []
def test_momentary_reference_counted_hold_and_resets() -> None:
source = score(
[
note(0, 1, pitch=40, art="slide", part="bass"),
note(Fraction(1, 2), 1, pitch=43, art="legato slide", part="bass"),
]
)
plan = compile_score(source, {"bass": profile("bass")})
# Normal is explicitly established before the first momentary control.
assert plan.musical_start_tick == 180
assert controls(plan) == [
(0, "note_on", 3, 60),
(0, "control_change", 21, 0),
(60, "note_off", 3, 0),
(60, "note_on", 4, 60),
(60, "control_change", 21, 90),
(540, "control_change", 21, 90),
(1680, "note_off", 4, 0),
(1680, "control_change", 21, 0),
(1680, "note_on", 3, 60),
(1680, "control_change", 21, 0),
(1740, "note_off", 3, 0),
]
assert not any(
e.tick == 1140 and isinstance(e, NoteOffEvent) and e.note == 4
for e in plan.tracks[0].events
)
def test_momentary_pulse_preserves_per_note_retrigger() -> None:
plan = compile_score(
score(
[
note(0, 1, pitch=40, art="trigger", part="bass"),
note(Fraction(1, 2), 1, pitch=43, art="trigger", part="bass"),
]
),
{"bass": profile("bass")},
)
pulses = [e.tick for e in plan.tracks[0].events if isinstance(e, NoteOnEvent) and e.note == 5]
assert pulses == [60, 540]
assert (
len(
[
e
for e in plan.tracks[0].events
if isinstance(e, ControlChangeEvent) and e.value == 70
]
)
== 2
)
def test_overlapping_physical_switch_retriggers_rejected() -> None:
with pytest.raises(SerializationError) as error:
compile_score(
score(
[
note(0, 1, pitch=40, art="trigger", part="bass"),
note(Fraction(1, 32), 1, pitch=43, art="trigger", part="bass"),
]
),
{"bass": profile("bass")},
)
assert error.value.details["reason"] == "same_pitch_overlap"
def test_exact_physical_switch_boundary_retrigger_is_preserved() -> None:
plan = compile_score(
score(
[
note(0, 1, pitch=40, art="trigger", part="bass"),
note(Fraction(1, 16), 1, pitch=43, art="trigger", part="bass"),
]
),
{"bass": profile("bass")},
)
at_boundary = [
(e.kind, e.note)
for e in plan.tracks[0].events
if isinstance(e, NoteOnEvent | NoteOffEvent) and e.tick == 120 and e.note == 5
]
assert at_boundary == [("note_off", 5), ("note_on", 5)]
validate_event_plan(plan)
def test_boundary_retrigger_causal_order() -> None:
selected = profile()
for art in selected.articulations:
for action in art.actions:
action.lead = beat(0)
plan = compile_score(score([note(0, 1, art="pm"), note(1, 1)]), {"lead": selected})
at_boundary = [e for e in plan.tracks[0].events if e.tick == 960]
assert [(e.kind, e.role) for e in at_boundary] == [
("note_off", "musical_note"),
("note_on", "keyswitch"),
("control_change", "articulation_control"),
("note_on", "musical_note"),
]
validate_event_plan(plan)
def test_boundary_momentary_reset_then_normal_actions_then_onset() -> None:
selected = profile("drums")
source = Score(
intent=MusicalIntent(
description="SYNTHETIC drums",
parts=["drums"],
tempo_bpm=120,
bars=1,
time_signature=TimeSignature(numerator=4, denominator=4),
key="C major",
seed=0,
),
start=beat(0),
end=beat(4),
tracks=[
ScoreTrack(
part="drums",
notes=[
DrumNote(
part="drums",
start=beat(0),
duration=PositiveBeat(numerator=1),
intensity=1,
articulation="accent",
voice="low",
),
DrumNote(
part="drums",
start=beat(1),
duration=PositiveBeat(numerator=1),
intensity=0,
articulation="normal",
voice="low",
),
],
)
],
)
for action in selected.articulations[1].actions:
action.release_offset = beat(0)
plan = compile_score(source, {"drums": selected})
assert [
(e.kind, e.value if isinstance(e, ControlChangeEvent) else e.note)
for e in plan.tracks[0].events
if e.tick == 960
] == [
("note_off", 36),
("control_change", 0),
("control_change", 0),
("note_on", 36),
]
@pytest.mark.parametrize(
("notes", "reason"),
[
([note(0, 2), note(1, 1, pitch=64, art="pm")], "incompatible_articulation_overlap"),
([note(0, 1), note(1, 1, art="pm")], "control_lead_overlaps_active_notes"),
],
)
def test_incompatible_state_and_lead(notes: list[PitchedNote], reason: str) -> None:
with pytest.raises(ArticulationCompileError) as error:
compile_score(score(notes), {"lead": profile()})
assert error.value.details == {"reason": reason}
def test_momentary_tail_cannot_corrupt_following_note() -> None:
with pytest.raises(ArticulationCompileError) as error:
compile_score(
score(
[
note(0, 1, pitch=40, art="slide", part="bass"),
note(1, 1, pitch=43, art="normal", part="bass"),
]
),
{"bass": profile("bass")},
)
assert error.value.details["reason"] == "restoration_overlaps_next_note"
def test_normal_initialization_requires_gap_after_other_latched_state() -> None:
selected = profile("bass")
# Introduce another fully explicit latched state for this synthetic case.
other = selected.articulations[0].model_copy(deep=True)
other.name, other.aliases = "other", []
switch = other.actions[0]
assert isinstance(switch, KeyswitchAction)
switch.note = 6
selected.articulations.append(other)
selected.summary.supported_articulations.append("other")
with pytest.raises(ArticulationCompileError) as error:
compile_score(
score(
[
note(0, 1, pitch=40, art="other", part="bass"),
note(Fraction(9, 8), 1, pitch=43, art="slide", part="bass"),
]
),
{"bass": selected},
)
assert error.value.details["reason"] == "normal_setup_overlaps_active_notes"
def test_nonzero_origin_not_extra_preroll_and_empty_track() -> None:
plan = compile_score(score([note(2, 1, art="pm")], origin=2), {"lead": profile()})
assert plan.musical_start_tick == 120
assert plan.musical_end_tick == 3960
empty = compile_score(score([], origin=7), {"lead": profile()})
assert empty.musical_start_tick == 0 and empty.end_tick == 3840
assert empty.tracks[0].events == []
@pytest.mark.parametrize("field", ["lead", "gate", "release_offset"])
def test_all_profile_timing_must_be_on_grid_even_unused(field: str) -> None:
selected = profile("bass")
switch = selected.articulations[1].actions[0]
assert isinstance(switch, KeyswitchAction)
setattr(switch, field, PositiveBeat(numerator=1, denominator=7))
with pytest.raises(SerializationError) as error:
compile_score(score([note(part="bass", pitch=40)]), {"bass": selected})
assert error.value.details["reason"] == "off_grid_beats"
def test_score_grid_and_ppq_rejection() -> None:
for source in [
score([note(0, Fraction(1, 7))]),
score([note(Fraction(1, 7), 1)]),
]:
with pytest.raises(SerializationError):
compile_score(source, {"lead": profile()})
for ppq in [0, 32768, True]:
with pytest.raises(SerializationError):
compile_score(score([note()]), {"lead": profile()}, ppq=ppq)
assert compile_score(score([note()]), {"lead": profile()}, ppq=480).musical_start_tick == 60
@pytest.mark.parametrize("pitch", [47, 85])
def test_playable_range_rejection(pitch: int) -> None:
with pytest.raises(ArticulationCompileError) as error:
compile_score(score([note(pitch=pitch)]), {"lead": profile()})
assert error.value.details["reason"] == "pitch_outside_profile_range"
@pytest.mark.parametrize("pitch", [48, 84])
def test_playable_range_endpoints(pitch: int) -> None:
assert compile_score(score([note(pitch=pitch)]), {"lead": profile()})
def test_missing_unsupported_mutated_and_wrong_part_content() -> None:
with pytest.raises(UnsupportedArticulationError) as error:
compile_score(score([note(art="private unsupported text")]), {"lead": profile()})
assert "private" not in str(error.value.details)
with pytest.raises(ArticulationCompileError):
compile_score(score([note()]), {})
with pytest.raises(ArticulationCompileError):
compile_score(score([note()]), {"lead": profile("bass")})
selected = profile()
selected.playable_range = None
with pytest.raises(InvalidProfileError):
compile_score(score([note()]), {"lead": selected})
source = score([note()])
source.tracks[0].notes[0].intensity = float("nan")
with pytest.raises(ArticulationCompileError):
compile_score(source, {"lead": profile()})
def test_no_silent_same_pitch_polyphony_merge() -> None:
with pytest.raises(SerializationError) as error:
compile_score(score([note(0, 2), note(1, 1)]), {"lead": profile()})
assert error.value.details["reason"] == "same_pitch_overlap"
def test_deterministic_note_order_and_no_input_mutation() -> None:
source = score([note(1, 1, pitch=64, art="pm"), note(0, 1, art="pm")])
selected = profile()
before = source.model_dump_json(), selected.model_dump_json()
plan = compile_score(source, {"lead": selected})
assert plan == compile_score(source, {"lead": selected})
source.tracks[0].notes.reverse()
reverse = compile_score(source, {"lead": selected})
assert reverse.tracks == plan.tracks
source.tracks[0].notes.reverse()
assert (source.model_dump_json(), selected.model_dump_json()) == before
def test_hold_gate_rejects_short_notes_without_clamping() -> None:
selected = profile("bass")
hold = selected.articulations[1].actions[0]
assert isinstance(hold, KeyswitchAction)
hold.gate = PositiveBeat(numerator=2)
with pytest.raises(ArticulationCompileError) as error:
compile_score(score([note(0, 1, art="slide", part="bass", pitch=40)]), {"bass": selected})
assert error.value.details["reason"] == "hold_shorter_than_declared_gate"
def test_event_budget_boundary_and_overflow() -> None:
selected = profile()
for art in selected.articulations:
art.actions = []
# 50,000 positive-duration adjacent notes: exactly 100,000 events.
source = score([note(Fraction(index, 12500), Fraction(1, 12500)) for index in range(50_000)])
# 25,000 PPQ makes each note exactly two ticks.
plan = compile_score(source, {"lead": selected}, ppq=25000)
assert len(plan.tracks[0].events) == 100_000
source.tracks[0].notes.append(note(0, Fraction(1, 12500), pitch=64))
with pytest.raises(ArticulationCompileError) as error:
compile_score(source, {"lead": selected}, ppq=25000)
assert error.value.details["reason"] == "event_budget_exceeded"
def test_compiler_calls_reviewed_validator(monkeypatch: pytest.MonkeyPatch) -> None:
def reject(_: EventPlan) -> None:
raise SerializationError(details={"reason": "validator_probe"})
monkeypatch.setattr("riff_groove_builder.articulations.validate_event_plan", reject)
with pytest.raises(SerializationError) as error:
compile_score(score([note()]), {"lead": profile()})
assert error.value.details["reason"] == "validator_probe"
def test_release_tail_and_exact_common_end() -> None:
plan = compile_score(
score([note(3, 1, part="bass", art="slide", pitch=40)]), {"bass": profile("bass")}
)
assert plan.musical_start_tick == 0
assert plan.musical_end_tick == 3840
assert plan.end_tick == 3960
assert controls(plan)[-1] == (3960, "note_off", 3, 0)
def test_cc_only_velocity_only_polyphony_without_control_state() -> None:
selected = profile()
for art in selected.articulations:
art.actions = []
plan = compile_score(
score(
[
note(0, 2),
note(1, 1, pitch=64, art="pm"),
]
),
{"lead": selected},
)
assert controls(plan) == []
assert len(plan.tracks[0].events) == 4
def test_release_reset_offset_is_explicit() -> None:
selected = profile("bass")
action = selected.articulations[1].actions[1]
assert isinstance(action, CCAction)
action.release_offset = beat(Fraction(1, 4))
plan = compile_score(
score([note(3, 1, part="bass", art="slide", pitch=40)]), {"bass": selected}
)
assert plan.end_tick == 4140
def test_control_tail_can_extend_after_musical_end_for_latched_pulse() -> None:
selected = profile()
for art in selected.articulations:
for action in art.actions:
action.lead = beat(0)
if isinstance(action, KeyswitchAction):
action.gate = PositiveBeat(numerator=2)
plan = compile_score(score([note(3, 1, art="pm")]), {"lead": selected})
assert plan.musical_start_tick == 0
assert plan.musical_end_tick == 3840 and plan.end_tick == 4800
def test_normal_restoration_leads_add_exact_tail() -> None:
selected = profile("bass")
for action in selected.articulations[0].actions:
action.lead = beat(Fraction(1, 8))
plan = compile_score(
score([note(3, 1, part="bass", pitch=40, art="slide")]), {"bass": selected}
)
# The reset is at 3900; normal starts there and is ready 120 ticks later.
# EOT includes readiness at 4020, not only the last physical release at 3960.
assert plan.musical_end_tick == 3840
assert plan.end_tick == 4020
def test_fractional_origin_is_not_an_absolute_tick_requirement() -> None:
origin = Fraction(1, 7)
plan = compile_score(score([note(origin, 1, art="pm")], origin=origin), {"lead": profile()})
assert plan.musical_start_tick == 120