acorde-core 1.1.7

Platform-agnostic music score model and command engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
use super::notation::{ChordSymbol, KeySignature};
use super::pitch::Pitch;

/// Chord templates: sorted semitone intervals from the root (inclusive of 0).
const TEMPLATES: &[(&[u8], &str)] = &[
    (&[0, 4, 7], "major"),
    (&[0, 3, 7], "minor"),
    (&[0, 4, 7, 10], "dominant"),
    (&[0, 4, 7, 11], "major-seventh"),
    (&[0, 3, 7, 10], "minor-seventh"),
    (&[0, 3, 6], "diminished"),
    (&[0, 3, 6, 9], "diminished-seventh"),
    (&[0, 3, 6, 10], "half-diminished"),
    (&[0, 4, 8], "augmented"),
    (&[0, 2, 7], "suspended-second"),
    (&[0, 5, 7], "suspended-fourth"),
    (&[0, 4, 7, 9], "major-sixth"),
    (&[0, 3, 7, 9], "minor-sixth"),
    (&[0, 7], "power"),
    (&[0, 2, 4, 7], "major-add9"),
    (&[0, 2, 3, 7], "minor-add9"),
    (&[0, 3, 7, 11], "minor-major-seventh"),
    (&[0, 4, 6, 10], "dominant-flat-five"),
    (&[0, 4, 8, 10], "dominant-sharp-five"),
    (&[0, 2, 4, 7, 10], "dominant-ninth"),
    (&[0, 2, 4, 7, 11], "major-ninth"),
    (&[0, 2, 3, 7, 10], "minor-ninth"),
];

/// Detect the chord name from a slice of pitches.
///
/// Returns `None` when fewer than 2 pitches are provided or no template matches.
/// Octave is ignored; only pitch classes (0–11) are compared.
/// Inversions are detected by trying every pitch class as the root.
/// When the lowest-sounding pitch differs from the root, a slash-chord bass note is set.
pub fn detect_chord(pitches: &[Pitch]) -> Option<ChordSymbol> {
    if pitches.len() < 2 {
        return None;
    }

    // Collect unique pitch classes, preserving first occurrence (used for root name).
    let mut pcs: Vec<(u8, &Pitch)> = Vec::new();
    for p in pitches {
        let pc = (p.to_midi().rem_euclid(12)) as u8;
        if !pcs.iter().any(|(c, _)| *c == pc) {
            pcs.push((pc, p));
        }
    }

    let bass_pitch = pitches.iter().min_by_key(|p| p.to_midi())?;
    let bass_pc = (bass_pitch.to_midi().rem_euclid(12)) as u8;

    // Try each unique pitch class as the root.
    for &(root_pc, root_pitch) in &pcs {
        let mut intervals: Vec<u8> = pcs.iter().map(|(pc, _)| (pc + 12 - root_pc) % 12).collect();
        intervals.sort_unstable();

        for &(template, kind) in TEMPLATES {
            if intervals.as_slice() == template {
                let root = pitch_name(root_pitch);

                let bass = if bass_pc != root_pc {
                    Some(pitch_name(bass_pitch))
                } else {
                    None
                };

                return Some(ChordSymbol {
                    root,
                    kind: kind.to_string(),
                    bass,
                    placement: None,
                    extender: false,
                    harmonic_degree: None,
                    harmony_function: None,
                    harmony_type: None,
                    chord_ref: None,
                    range_end: None,
                    degrees: Vec::new(),
                });
            }
        }
    }

    None
}

/// Parse a root string like "C", "F#", "Bb" into a MIDI pitch class (0–11).
fn root_to_pc(root: &str) -> Option<u8> {
    let mut chars = root.chars();
    let base = match chars.next()? {
        'C' => 0u8,
        'D' => 2,
        'E' => 4,
        'F' => 5,
        'G' => 7,
        'A' => 9,
        'B' => 11,
        _ => return None,
    };
    let accidental: String = chars.collect();
    let offset = match accidental.as_str() {
        "" => 0,
        "#" => 1,
        "##" => 2,
        "b" => -1,
        "bb" => -2,
        _ => return None,
    };
    Some((base as i16 + offset).rem_euclid(12) as u8)
}

fn pitch_name(pitch: &Pitch) -> String {
    let accidental = match pitch.alter {
        -2 => "bb",
        -1 => "b",
        1 => "#",
        2 => "##",
        _ => "",
    };
    format!("{}{}", pitch.step.to_char(), accidental)
}

/// Returns the Roman numeral analysis string for `chord` in the context of `key`.
///
/// - Uppercase for major-quality chords (I, IV, V7, …).
/// - Lowercase for minor-quality chords (ii, iii, vi, …).
/// - Suffix: `o` for diminished, `o7` for diminished seventh, `ø7` for half-diminished,
///   `+` for augmented, `7` for dominant seventh, `maj7` for major seventh.
/// - Slash chords append `/N` where N is the Roman numeral of the bass note.
/// - Returns `None` when the chord root or bass is outside the key's scale.
pub fn roman_numeral(chord: &ChordSymbol, key: &KeySignature) -> Option<String> {
    const NUMERALS: &[&str] = &["I", "II", "III", "IV", "V", "VI", "VII"];

    // Key root pitch class and scale intervals.
    let (key_step, key_alter) = key.tonic();
    let key_root_pc = {
        let base: u8 = match key_step {
            crate::Step::C => 0,
            crate::Step::D => 2,
            crate::Step::E => 4,
            crate::Step::F => 5,
            crate::Step::G => 7,
            crate::Step::A => 9,
            crate::Step::B => 11,
        };
        ((base as i8 + key_alter).rem_euclid(12)) as u8
    };
    let scale_intervals: &[u8] = if key.mode == "minor" {
        &[0, 2, 3, 5, 7, 8, 10] // natural minor
    } else {
        &[0, 2, 4, 5, 7, 9, 11] // major
    };

    // Map a pitch class to a scale degree (0-based index into NUMERALS).
    let pc_to_degree = |pc: u8| -> Option<usize> {
        let interval = ((pc as i16 - key_root_pc as i16).rem_euclid(12)) as u8;
        scale_intervals.iter().position(|&i| i == interval)
    };

    let chord_pc = root_to_pc(&chord.root)?;
    let degree = pc_to_degree(chord_pc)?;
    let numeral = NUMERALS[degree];

    // Quality → case and suffix.
    let (upper, suffix) = match chord.kind.as_str() {
        "major" => (true, ""),
        "dominant" => (true, "7"),
        "major-seventh" => (true, "maj7"),
        "major-sixth" => (true, "6"),
        "power" => (true, "5"),
        "major-add9" => (true, "add9"),
        "minor-add9" => (false, "add9"),
        "minor-major-seventh" => (false, "maj7"),
        "dominant-flat-five" => (true, "7b5"),
        "dominant-sharp-five" => (true, "7#5"),
        "dominant-ninth" => (true, "9"),
        "major-ninth" => (true, "maj9"),
        "minor-ninth" => (false, "9"),
        "augmented" => (true, "+"),
        k if k.starts_with("suspended") => (true, ""),
        "minor" => (false, ""),
        "minor-seventh" => (false, "7"),
        "minor-sixth" => (false, "6"),
        "diminished" => (false, "o"),
        "diminished-seventh" => (false, "o7"),
        "half-diminished" => (false, "\u{00f8}7"),
        _ => (true, ""),
    };

    let rn = if upper {
        format!("{}{}", numeral, suffix)
    } else {
        format!("{}{}", numeral.to_lowercase(), suffix)
    };

    // Slash bass.
    let slash = if let Some(bass) = &chord.bass {
        let bass_pc = root_to_pc(bass)?;
        let bass_degree = pc_to_degree(bass_pc)?;
        let bass_numeral = NUMERALS[bass_degree];
        format!("/{}", bass_numeral)
    } else {
        String::new()
    };

    Some(format!("{}{}", rn, slash))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Pitch, Step};

    fn p(step: Step, octave: i8) -> Pitch {
        Pitch::new(step, octave)
    }
    fn pa(step: Step, octave: i8, alter: i8) -> Pitch {
        Pitch::with_alter(step, octave, alter)
    }

    #[test]
    fn detect_chord_c_major_root_pos() {
        let pitches = [p(Step::C, 4), p(Step::E, 4), p(Step::G, 4)];
        let cs = detect_chord(&pitches).unwrap();
        assert_eq!(cs.root, "C");
        assert_eq!(cs.kind, "major");
        assert_eq!(cs.bass, None);
    }

    #[test]
    fn detect_chord_g_dominant_seventh() {
        let pitches = [p(Step::G, 4), p(Step::B, 4), p(Step::D, 4), p(Step::F, 4)];
        let cs = detect_chord(&pitches).unwrap();
        assert_eq!(cs.root, "G");
        assert_eq!(cs.kind, "dominant");
    }

    #[test]
    fn detect_chord_d_minor() {
        let pitches = [p(Step::D, 4), p(Step::F, 4), p(Step::A, 4)];
        let cs = detect_chord(&pitches).unwrap();
        assert_eq!(cs.root, "D");
        assert_eq!(cs.kind, "minor");
    }

    #[test]
    fn detect_chord_first_inversion() {
        // E4-G4-C5 = C major first inversion; bass (E) ≠ root (C) → slash chord
        let pitches = [p(Step::E, 4), p(Step::G, 4), p(Step::C, 5)];
        let cs = detect_chord(&pitches).unwrap();
        assert_eq!(cs.root, "C");
        assert_eq!(cs.kind, "major");
        assert_eq!(cs.bass, Some("E".to_string()));
    }

    #[test]
    fn detect_chord_slash_chord() {
        // G3-C4-E4-G4 = C/G
        let pitches = [p(Step::G, 3), p(Step::C, 4), p(Step::E, 4), p(Step::G, 4)];
        let cs = detect_chord(&pitches).unwrap();
        assert_eq!(cs.root, "C");
        assert_eq!(cs.kind, "major");
        assert_eq!(cs.bass, Some("G".to_string()));
    }

    #[test]
    fn detect_chord_too_few_notes() {
        let pitches = [p(Step::C, 4)];
        assert!(detect_chord(&pitches).is_none());
    }

    #[test]
    fn detect_chord_no_template_match() {
        // Cluster: C and C#
        let pitches = [p(Step::C, 4), pa(Step::C, 4, 1)];
        assert!(detect_chord(&pitches).is_none());
    }

    #[test]
    fn detect_chord_diminished() {
        // B-D-F = B diminished
        let pitches = [p(Step::B, 3), p(Step::D, 4), p(Step::F, 4)];
        let cs = detect_chord(&pitches).unwrap();
        assert_eq!(cs.root, "B");
        assert_eq!(cs.kind, "diminished");
    }

    #[test]
    fn detect_chord_flat_root() {
        // Bb-D-F = Bb major
        let pitches = [pa(Step::B, 3, -1), p(Step::D, 4), p(Step::F, 4)];
        let cs = detect_chord(&pitches).unwrap();
        assert_eq!(cs.root, "Bb");
        assert_eq!(cs.kind, "major");
    }

    #[test]
    fn detect_chord_preserves_double_accidentals_in_root_and_bass() {
        let pitches = [pa(Step::C, 4, 2), pa(Step::E, 4, 2), pa(Step::G, 4, 2)];
        let chord = detect_chord(&pitches).expect("double-sharp chord should be detected");
        assert_eq!(chord.root, "C##");
        assert_eq!(chord.bass, None);
        assert_eq!(root_to_pc("C##"), Some(2));
        assert_eq!(root_to_pc("Abb"), Some(7));
    }

    #[test]
    fn detect_chord_common_extended_qualities() {
        let cases = vec![
            (
                vec![p(Step::C, 4), p(Step::D, 4), p(Step::E, 4), p(Step::G, 4)],
                "major-add9",
            ),
            (
                vec![
                    p(Step::G, 3),
                    p(Step::B, 3),
                    p(Step::D, 4),
                    p(Step::F, 4),
                    p(Step::A, 4),
                ],
                "dominant-ninth",
            ),
            (vec![p(Step::C, 4), p(Step::G, 4)], "power"),
        ];
        for (pitches, expected_kind) in cases {
            let chord = detect_chord(&pitches).expect("extended chord should be detected");
            assert_eq!(chord.kind, expected_kind);
        }
    }

    #[test]
    fn extended_chord_qualities_have_stable_display_and_roman_suffixes() {
        let chord = detect_chord(&[
            p(Step::G, 3),
            p(Step::B, 3),
            p(Step::D, 4),
            p(Step::F, 4),
            p(Step::A, 4),
        ])
        .expect("dominant ninth should be detected");
        assert_eq!(chord.display_text(), "G9");
        assert_eq!(
            roman_numeral(&chord, &c_major_key()),
            Some("V9".to_string())
        );
    }

    fn c_major_key() -> KeySignature {
        KeySignature {
            fifths: 0,
            mode: "major".to_string(),
        }
    }

    #[test]
    fn roman_numeral_i_major() {
        let chord = ChordSymbol {
            root: "C".to_string(),
            kind: "major".to_string(),
            bass: None,
            placement: None,
            extender: false,
            harmonic_degree: None,
            harmony_function: None,
            harmony_type: None,
            chord_ref: None,
            range_end: None,
            degrees: Vec::new(),
        };
        assert_eq!(roman_numeral(&chord, &c_major_key()), Some("I".to_string()));
    }

    #[test]
    fn roman_numeral_v7() {
        let chord = ChordSymbol {
            root: "G".to_string(),
            kind: "dominant".to_string(),
            bass: None,
            placement: None,
            extender: false,
            harmonic_degree: None,
            harmony_function: None,
            harmony_type: None,
            chord_ref: None,
            range_end: None,
            degrees: Vec::new(),
        };
        assert_eq!(
            roman_numeral(&chord, &c_major_key()),
            Some("V7".to_string())
        );
    }

    #[test]
    fn roman_numeral_ii_minor() {
        let chord = ChordSymbol {
            root: "D".to_string(),
            kind: "minor".to_string(),
            bass: None,
            placement: None,
            extender: false,
            harmonic_degree: None,
            harmony_function: None,
            harmony_type: None,
            chord_ref: None,
            range_end: None,
            degrees: Vec::new(),
        };
        assert_eq!(
            roman_numeral(&chord, &c_major_key()),
            Some("ii".to_string())
        );
    }

    #[test]
    fn roman_numeral_vii_diminished() {
        let chord = ChordSymbol {
            root: "B".to_string(),
            kind: "diminished".to_string(),
            bass: None,
            placement: None,
            extender: false,
            harmonic_degree: None,
            harmony_function: None,
            harmony_type: None,
            chord_ref: None,
            range_end: None,
            degrees: Vec::new(),
        };
        assert_eq!(
            roman_numeral(&chord, &c_major_key()),
            Some("viio".to_string())
        );
    }

    #[test]
    fn roman_numeral_out_of_key_returns_none() {
        // F# is not in C major
        let chord = ChordSymbol {
            root: "F#".to_string(),
            kind: "major".to_string(),
            bass: None,
            placement: None,
            extender: false,
            harmonic_degree: None,
            harmony_function: None,
            harmony_type: None,
            chord_ref: None,
            range_end: None,
            degrees: Vec::new(),
        };
        assert!(roman_numeral(&chord, &c_major_key()).is_none());
    }

    #[test]
    fn roman_numeral_slash_chord() {
        // C/G = I/V
        let chord = ChordSymbol {
            root: "C".to_string(),
            kind: "major".to_string(),
            bass: Some("G".to_string()),
            placement: None,
            extender: false,
            harmonic_degree: None,
            harmony_function: None,
            harmony_type: None,
            chord_ref: None,
            range_end: None,
            degrees: Vec::new(),
        };
        assert_eq!(
            roman_numeral(&chord, &c_major_key()),
            Some("I/V".to_string())
        );
    }
}