Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use griff_core::{
SourceRef, StyleCohort, SwancoreTag, SCHEMA_VERSION,
},
event::{NoteMarks, NotePosition, Pitch, TechniqueSource, Ticks},
generate, gesture,
generate, gesture, harmony,
import::{self, ImportError},
midi::{self, MidiError},
score::{AtomEvent, Score, Track, Voice},
Expand Down Expand Up @@ -1051,6 +1051,11 @@ fn build_chunk_meta(
let derived = track_index
.map(|idx| technique::derive_techniques(score, idx))
.unwrap_or_default();
// Auto-derive chord-quality tags from the same notation (#75); they merge
// additively too, like the technique tags.
let derived_harmony = track_index
.map(|idx| harmony::derive_harmony(score, idx))
.unwrap_or_default();

let now = "2026-05-20T00:00:00Z".to_owned();
ChunkMeta {
Expand All @@ -1065,7 +1070,12 @@ fn build_chunk_meta(
ticks_per_quarter: score.ticks_per_quarter,
time_signature,
tuning: inputs.tuning.clone(),
tags: technique::merge_tags(&inputs.tags, &derived.tags),
tags: {
// Additive: curator choices first, then derived technique tags, then
// derived chord-quality tags (#75) — none overrides the others.
let with_techniques = technique::merge_tags(&inputs.tags, &derived.tags);
technique::merge_tags(&with_techniques, &derived_harmony)
Comment thread
PhysShell marked this conversation as resolved.
},
boundaries,
techniques: derived.names,
quality_flags: inputs.quality_flags.clone(),
Expand Down
136 changes: 136 additions & 0 deletions core/src/harmony.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
//! Deriving chord-quality evidence from a track's notation (#75).
//!
//! The harmony tags (`maj7`/`min7`/`sus2`/`add9`/`power_chord`) name chord
//! *voicings*. Guitar Pro records a chord as simultaneous notes in one
//! [`EventGroup`](crate::score::EventGroup) of kind
//! [`Chord`](crate::score::EventGroupKind::Chord); rather than ask a curator to
//! name what the tab already spells out, [`derive_harmony`] reads each chord's
//! pitch-class set and matches it against the voicing templates.
//!
//! Like [`derive_techniques`](crate::technique::derive_techniques) it is
//! **presence-only** and template-exact — a pure function of the score with no
//! thresholds (SPEC §6). Inversions are tagged by their quality (the voicing is
//! present whichever tone is in the bass); dedicated **slash-chord** detection is
//! a deliberate follow-up (see `docs/decisions.log.md`), because the common
//! plain-triad slash (e.g. `G/B`) is not expressible with the seventh/sus/add
//! templates and would need its own bass-vs-root model.

use std::collections::HashSet;

use crate::corpus::SwancoreTag;
use crate::event::Pitch;
use crate::score::{AtomEvent, EventGroup, EventGroupKind, Score};

/// Chord-quality tags in canonical (taxonomy-declaration) order.
const HARMONY_TAGS: [SwancoreTag; 5] = [
SwancoreTag::Maj7,
SwancoreTag::Min7,
SwancoreTag::Sus2,
SwancoreTag::Add9,
SwancoreTag::PowerChord,
];

/// Root-anchored pitch-class templates (root = 0) for the seventh/sus/add
/// voicings, each sorted ascending. Power chords are matched separately as a
/// bare-fifth dyad, so they are not listed here.
const TEMPLATES: [(&[u8], SwancoreTag); 4] = [
(&[0, 4, 7, 11], SwancoreTag::Maj7),
(&[0, 3, 7, 10], SwancoreTag::Min7),
(&[0, 2, 7], SwancoreTag::Sus2),
(&[0, 2, 4, 7], SwancoreTag::Add9),
];

/// Derives the chord-quality tags present in `track_index`.
///
/// Scans every voice's chord-bearing groups, classifies each chord's
/// pitch-class set, and returns the matched [`SwancoreTag`]s in canonical order,
/// deduplicated. Empty when the track index is out of range or nothing matches.
#[must_use]
pub fn derive_harmony(score: &Score, track_index: usize) -> Vec<SwancoreTag> {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
let Some(track) = score.tracks.get(track_index) else {
return Vec::new();
};

// Every voice — some importers split one track into several voices, so a
// chord in a secondary voice must still be seen (cf. the technique deriver).
let mut found: HashSet<SwancoreTag> = HashSet::new();
for voice in &track.voices {
for group in &voice.event_groups {
if let Some(tag) = classify_group(group) {
found.insert(tag);
}
}
}

HARMONY_TAGS
.into_iter()
.filter(|tag| found.contains(tag))
.collect()
}

/// Classifies the chord borne by a group, if it is a chord-bearing group with a
/// recognisable voicing.
fn classify_group(group: &EventGroup) -> Option<SwancoreTag> {
// Only genuinely simultaneous groups are chords; melody (`Single`) and
// rhythmic/ornamental groupings are not. Arpeggios and chords split across
// voices are a deliberate follow-up.
if !matches!(group.kind, EventGroupKind::Chord | EventGroupKind::Strum) {
return None;
}
classify(&pitch_classes(group))
}

/// The distinct pitch classes (0–11) sounding in a group, sorted ascending.
fn pitch_classes(group: &EventGroup) -> Vec<u8> {
let mut classes: Vec<u8> = group
.atoms
.iter()
.filter_map(|atom| match atom {
AtomEvent::Note(note) => Some(pitch_class(note.pitch)),
AtomEvent::Rest(_) => None,
})
.collect();
classes.sort_unstable();
classes.dedup();
classes
}

/// Matches a sorted, distinct pitch-class set against the voicing templates.
fn classify(classes: &[u8]) -> Option<SwancoreTag> {
// A power chord is the bare perfect-fifth dyad (root + fifth, any octave):
// two distinct classes a fifth (7) — or its inversion, a fourth (5) — apart.
if let &[low, high] = classes {
let interval = high.wrapping_sub(low);
return (interval == 5 || interval == 7).then_some(SwancoreTag::PowerChord);
}
// Otherwise try each chord tone as the root — the root of a maj7/min7/sus2/
// add9 is always a chord tone — so inversions match their quality too.
classes
.iter()
.find_map(|&root| match_templates(classes, root))
}

/// The template tag whose interval set, rooted at `root`, equals `classes`
/// reduced to root-relative intervals.
fn match_templates(classes: &[u8], root: u8) -> Option<SwancoreTag> {
let mut intervals: Vec<u8> = classes.iter().map(|&pc| interval_above(root, pc)).collect();
intervals.sort_unstable();
TEMPLATES
.into_iter()
.find_map(|(template, tag)| (intervals.as_slice() == template).then_some(tag))
}

/// The pitch class `pc` expressed as an interval above `root`, in `0..12`. Both
/// arguments are pitch classes in `0..12`, so `pc + 12 - root` lies in `1..24`
/// and the reduction never underflows.
fn interval_above(root: u8, pc: u8) -> u8 {
pc.wrapping_add(12)
.wrapping_sub(root)
.checked_rem(12)
.unwrap_or(0)
}

/// The pitch class (0–11) of a MIDI pitch.
fn pitch_class(pitch: Pitch) -> u8 {
pitch.0.checked_rem(12).unwrap_or(0)
}
1 change: 1 addition & 0 deletions core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ pub mod generate;
pub mod gesture;
#[cfg(feature = "gp")]
pub mod gp;
pub mod harmony;
pub mod import;
pub mod midi;
pub mod novelty;
Expand Down
178 changes: 178 additions & 0 deletions core/tests/harmony_tags.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
//! Red → tests for auto-derived chord-quality tags (#75). The harmony tags
//! (`maj7`/`min7`/`sus2`/`add9`/`power_chord`) already exist in the taxonomy but
//! were curator-only; griff should read the voicings the tab already spells out.
//! References `griff_core::harmony`, which does not exist yet, so the suite fails
//! to compile until the green step.

#![allow(
clippy::expect_used,
clippy::unwrap_used,
clippy::panic,
clippy::missing_assert_message,
clippy::indexing_slicing
)]

use griff_core::corpus::SwancoreTag;
use griff_core::event::{NoteMarks, Pitch, Ticks, Tuning, Velocity};
use griff_core::harmony::derive_harmony;
use griff_core::score::{
AtomEvent, AtomNote, EventGroup, EventGroupKind, LossReport, Score, Track, Voice,
};

/// A chord-bearing [`EventGroup`] whose notes sound `pitches` (MIDI) together.
fn chord_group(pitches: &[u8]) -> EventGroup {
let atoms = pitches
.iter()
.map(|&p| {
AtomEvent::Note(AtomNote {
absolute_start: Ticks(0),
duration: Ticks(480),
pitch: Pitch(p),
velocity: Velocity(90),
marks: NoteMarks::empty(),
position: None,
})
})
.collect();
EventGroup {
kind: EventGroupKind::Chord,
atoms,
technique_spans: Vec::new(),
}
}

/// A one-track, one-voice score built from `groups`.
fn score_with_groups(groups: Vec<EventGroup>) -> Score {
Score {
ticks_per_quarter: 480,
master_bars: Vec::new(),
tracks: vec![Track {
name: Some("g".to_owned()),
channel: 0,
voices: vec![Voice {
id: 0,
event_groups: groups,
}],
tuning: Tuning::standard_e(),
}],
source_meta: None,
loss: LossReport::new(),
}
}

/// A one-track score whose single chord sounds `pitches` together.
fn chord_score(pitches: &[u8]) -> Score {
score_with_groups(vec![chord_group(pitches)])
}

#[test]
fn power_chord_fifth_dyad_derives_power_chord() {
// E5 = E2 + B2, a bare perfect fifth — the defining swancore voicing.
assert_eq!(
derive_harmony(&chord_score(&[40, 47]), 0),
vec![SwancoreTag::PowerChord]
);
}

#[test]
fn power_chord_ignores_octave_doubling() {
// Root + fifth + octave root still reduces to the {root, fifth} dyad.
assert_eq!(
derive_harmony(&chord_score(&[40, 47, 52]), 0),
vec![SwancoreTag::PowerChord]
);
}

#[test]
fn maj7_voicing_derives_maj7() {
// C E G B = {0, 4, 7, 11}.
assert_eq!(
derive_harmony(&chord_score(&[60, 64, 67, 71]), 0),
vec![SwancoreTag::Maj7]
);
}

#[test]
fn min7_voicing_derives_min7() {
// A C E G = {0, 3, 7, 10} rooted on A.
assert_eq!(
derive_harmony(&chord_score(&[57, 60, 64, 67]), 0),
vec![SwancoreTag::Min7]
);
}

#[test]
fn sus2_voicing_derives_sus2() {
// C D G = {0, 2, 7}.
assert_eq!(
derive_harmony(&chord_score(&[60, 62, 67]), 0),
vec![SwancoreTag::Sus2]
);
}

#[test]
fn add9_voicing_derives_add9() {
// C E G D = {0, 2, 4, 7} (the 9th folds to a 2nd by pitch class).
assert_eq!(
derive_harmony(&chord_score(&[60, 64, 67, 74]), 0),
vec![SwancoreTag::Add9]
);
}

#[test]
fn inverted_maj7_still_derives_maj7() {
// Cmaj7 with E in the bass: the voicing is present regardless of inversion,
// so presence-only derivation still tags Maj7. (Dedicated slash-chord
// detection is a deliberate follow-up — see docs/decisions.log.md.)
assert_eq!(
derive_harmony(&chord_score(&[52, 55, 59, 60]), 0),
vec![SwancoreTag::Maj7]
);
}

#[test]
fn lone_note_and_plain_triad_derive_nothing() {
// A single note is no chord…
assert!(derive_harmony(&chord_score(&[60]), 0).is_empty());
// …and a plain major triad has no tag in the taxonomy.
assert!(derive_harmony(&chord_score(&[60, 64, 67]), 0).is_empty());
}

#[test]
fn presence_only_dedupes_and_is_deterministic() {
// The same quality across groups is counted once; a pure fn of the score
// (SPEC §6).
let score = score_with_groups(vec![
chord_group(&[60, 64, 67, 71]),
chord_group(&[60, 64, 67, 71]),
]);
let first = derive_harmony(&score, 0);
assert_eq!(first, derive_harmony(&score, 0));
assert_eq!(first, vec![SwancoreTag::Maj7]);
}

#[test]
fn output_follows_canonical_taxonomy_order() {
// A power chord then a maj7 → output in enum order (Maj7 before PowerChord).
let score = score_with_groups(vec![chord_group(&[40, 47]), chord_group(&[60, 64, 67, 71])]);
assert_eq!(
derive_harmony(&score, 0),
vec![SwancoreTag::Maj7, SwancoreTag::PowerChord]
);
}

#[test]
fn out_of_range_track_is_empty() {
assert!(derive_harmony(&chord_score(&[60, 64, 67, 71]), 9).is_empty());
}

#[test]
fn derives_from_every_voice() {
// A chord in a secondary voice is still derived (the track is measured whole).
let mut score = chord_score(&[60]); // voice 0: a lone note
score.tracks[0].voices.push(Voice {
id: 1,
event_groups: vec![chord_group(&[40, 47])],
});
assert_eq!(derive_harmony(&score, 0), vec![SwancoreTag::PowerChord]);
}
20 changes: 20 additions & 0 deletions docs/decisions.log.md
Original file line number Diff line number Diff line change
Expand Up @@ -1262,3 +1262,23 @@ Architectural decisions go to [`adr/`](adr/) instead.
optional-field pattern, not a tag counter — accepting that a pinned pre-tag
build hard-rejects a chunk carrying a newer tag (a curation-tooling concern,
since griff's reader and writer ship together).

- 2026-06-19 — In the context of auto-deriving the chord-quality tags
(`maj7`/`min7`/`sus2`/`add9`/`power_chord`, #75's next taxonomy ask after
`let_ring`), facing that Guitar Pro records only notes — never chord labels —
and that these tags were curator-only despite the voicing being spelled out in
the tab, we decided for a presence-only `harmony::derive_harmony` that matches
each chord group's pitch-class set against exact root-relative templates (power
chord = a bare perfect-fifth dyad; maj7/min7/sus2/add9 = fixed interval sets,
tried from every chord tone so inversions tag their quality), mirroring
`technique::derive_techniques`. Prior art: pitch-class-set / chord-template
matching is the standard MIR approach, reimplemented natively (no dependency).
Against a confidence-thresholded recogniser — it would forfeit the "pure
function of the score, no thresholds" property (SPEC §6) the technique deriver
set — and against reusing `complement::estimate_harmony`, which answers "what
key?" (Krumhansl–Kessler key-fit), not "what voicing?". We defer `slash_chord`:
its common case is a plain triad over a non-root bass (e.g. G/B), which the
seventh/sus/add templates cannot express and which needs its own bass-vs-root
pass. Accepting that extended/altered chords and arpeggiated or cross-voice
voicings go unclassified in this first cut (under-tagging, never mis-tagging),
and that slash chords carry no tag until that follow-up lands.
Loading
Loading