Skip to main content

music21/chord/
quality.rs

1//! What kind of chord it is: the chord steps above the root, the triad
2//! and seventh predicates, the augmented sixths and the quality they add
3//! up to.
4
5use super::*;
6
7impl Chord {
8    /// Returns the first pitch lying at the given chord step above the root,
9    /// so `3` is the third and `7` the seventh. Steps of eight and above are
10    /// folded down by an octave, so `9` finds a second.
11    pub fn chord_step(&self, step: u8) -> Option<&Pitch> {
12        self.chord_step_from(step, self.root()?)
13    }
14
15    /// Returns the third above the root, if the chord has one.
16    pub fn third(&self) -> Option<&Pitch> {
17        self.chord_step(3)
18    }
19
20    /// Returns the fifth above the root, if the chord has one.
21    pub fn fifth(&self) -> Option<&Pitch> {
22        self.chord_step(5)
23    }
24
25    /// Returns the seventh above the root, if the chord has one.
26    pub fn seventh(&self) -> Option<&Pitch> {
27        self.chord_step(7)
28    }
29
30    /// Returns the semitones from the root to the given chord step, within an
31    /// octave, if the chord has that step.
32    pub fn semitones_from_chord_step(&self, step: u8) -> Option<u8> {
33        self.semitones_from_chord_step_with_root(step, self.root()?)
34    }
35
36    /// Returns whether the chord has the given step spelled two different
37    /// ways, such as both `E` and `E-` above `C`.
38    pub fn has_repeated_chord_step(&self, step: u8) -> bool {
39        let Some(root) = self.root() else {
40            return false;
41        };
42
43        self.has_repeated_step_from(step, root)
44    }
45
46    /// [`Self::has_repeated_chord_step`] above a root already found, so a
47    /// caller asking about several steps finds the root only once.
48    fn has_repeated_step_from(&self, step: u8, root: &Pitch) -> bool {
49        let step = fold_chord_step(step);
50        let Some(first) = self
51            .chord_step_from(step, root)
52            .map(|pitch| semitones_above(root, pitch))
53        else {
54            return false;
55        };
56        self.pitch_refs().any(|pitch| {
57            diatonic_steps_above(root, pitch) == step && semitones_above(root, pitch) != first
58        })
59    }
60
61    /// Returns whether two pitches share a pitch class under different names,
62    /// such as `C#` and `D-`.
63    pub fn has_any_enharmonic_spelled_pitches(&self) -> bool {
64        self.pitch_class_cardinality() != self.unique_pitch_name_count()
65    }
66
67    /// Returns whether the chord is exactly three distinct pitch names with a
68    /// third and a fifth above the root, of any quality.
69    pub fn is_triad(&self) -> bool {
70        self.root().is_some_and(|root| self.is_triad_from(root))
71    }
72
73    /// Returns whether the chord is exactly four distinct pitch names with a
74    /// third, fifth and seventh above the root, of any quality.
75    pub fn is_seventh(&self) -> bool {
76        self.root().is_some_and(|root| self.is_seventh_from(root))
77    }
78
79    /// [`Self::is_triad`] above a root already found.
80    pub(super) fn is_triad_from(&self, root: &Pitch) -> bool {
81        self.unique_pitch_name_count() == 3 && self.has_steps_from(root, &[3, 5])
82    }
83
84    /// [`Self::is_seventh`] above a root already found.
85    pub(super) fn is_seventh_from(&self, root: &Pitch) -> bool {
86        self.unique_pitch_name_count() == 4 && self.has_steps_from(root, &[3, 5, 7])
87    }
88
89    /// Returns whether the chord is a correctly spelled major triad.
90    pub fn is_major_triad(&self) -> bool {
91        self.is_triad_of_type((3, 11, -1), TriadQuality::Major)
92    }
93
94    /// Returns whether the chord is a correctly spelled minor triad.
95    pub fn is_minor_triad(&self) -> bool {
96        self.is_triad_of_type((3, 11, 1), TriadQuality::Minor)
97    }
98
99    /// Returns whether the chord is a correctly spelled diminished triad.
100    pub fn is_diminished_triad(&self) -> bool {
101        self.is_triad_of_type((3, 10, 0), TriadQuality::Diminished)
102    }
103
104    /// Returns whether the chord is a correctly spelled augmented triad.
105    pub fn is_augmented_triad(&self) -> bool {
106        self.is_triad_of_type((3, 12, 0), TriadQuality::Augmented)
107    }
108
109    /// Returns whether the chord is a seventh chord whose pitches all lie at
110    /// the given semitone offsets above the root.
111    pub fn is_seventh_of_type(&self, semitones: &[u8]) -> bool {
112        // The cheap count first, so a chord that is no seventh never looks
113        // for its root.
114        if self.unique_pitch_name_count() != 4 {
115            return false;
116        }
117
118        let Some(root) = self.root() else {
119            return false;
120        };
121
122        self.seventh_of_type_from(semitones, root)
123    }
124
125    /// [`Self::is_seventh_of_type`] above a root already found, for callers
126    /// that ask a chord several questions about the same root.
127    pub(crate) fn seventh_of_type_from(&self, semitones: &[u8], root: &Pitch) -> bool {
128        if !self.is_seventh_from(root) {
129            return false;
130        }
131
132        self.pitch_refs()
133            .all(|pitch| semitones.contains(&semitones_above(root, pitch)))
134    }
135
136    /// Returns whether the chord is a dominant seventh: a major triad with a
137    /// minor seventh.
138    pub fn is_dominant_seventh(&self) -> bool {
139        self.is_seventh_of_type(&[0, 4, 7, 10])
140    }
141
142    /// Returns whether the chord is a half-diminished seventh.
143    pub fn is_half_diminished_seventh(&self) -> bool {
144        self.is_seventh_of_type(&[0, 3, 6, 10])
145    }
146
147    /// Returns whether the chord is a fully diminished seventh.
148    pub fn is_diminished_seventh(&self) -> bool {
149        self.is_seventh_of_type(&[0, 3, 6, 9])
150    }
151
152    /// Returns whether the chord is only a root and a major third above it.
153    pub fn is_incomplete_major_triad(&self) -> bool {
154        self.is_incomplete_triad_of_type((2, 4), 4)
155    }
156
157    /// Returns whether the chord is only a root and a minor third above it.
158    pub fn is_incomplete_minor_triad(&self) -> bool {
159        self.is_incomplete_triad_of_type((2, 3), 3)
160    }
161
162    /// Returns whether the chord has a third and a fifth above its root. A
163    /// dominant seventh is not a triad but contains one.
164    pub fn contains_triad(&self) -> bool {
165        self.root()
166            .is_some_and(|root| self.has_steps_from(root, &[3, 5]))
167    }
168
169    /// Returns whether the chord contains a triad and a seventh above its root.
170    pub fn contains_seventh(&self) -> bool {
171        self.root()
172            .is_some_and(|root| self.has_steps_from(root, &[3, 5, 7]))
173    }
174
175    /// Returns the quality of the triad above the root, following music21's
176    /// `Chord.quality`: incomplete triads still count, and a chord with a
177    /// repeated or missing chord step is [`TriadQuality::Other`].
178    pub fn quality(&self) -> TriadQuality {
179        // Every step below is measured from this one root, found once.
180        let Some(root) = self.root() else {
181            return TriadQuality::Other;
182        };
183
184        let Some(third) = self.semitones_from_chord_step_with_root(3, root) else {
185            return TriadQuality::Other;
186        };
187        // A third or fifth a fraction of a semitone off is neither major nor
188        // minor, as music21 reads it.
189        if [3, 5].into_iter().any(|step| {
190            self.chord_step_from(step, root)
191                .is_some_and(|pitch| ((pitch.ps() - root.ps()) * 100.0).round() % 100.0 != 0.0)
192        }) {
193            return TriadQuality::Other;
194        }
195        if self.has_repeated_step_from(1, root) || self.has_repeated_step_from(3, root) {
196            return TriadQuality::Other;
197        }
198        let Some(fifth) = self.semitones_from_chord_step_with_root(5, root) else {
199            return match third {
200                4 => TriadQuality::Major,
201                3 => TriadQuality::Minor,
202                _ => TriadQuality::Other,
203            };
204        };
205        if self.has_repeated_step_from(5, root) {
206            return TriadQuality::Other;
207        }
208        match (third, fifth) {
209            (4, 7) => TriadQuality::Major,
210            (3, 7) => TriadQuality::Minor,
211            (4, 8) => TriadQuality::Augmented,
212            (3, 6) => TriadQuality::Diminished,
213            _ => TriadQuality::Other,
214        }
215    }
216
217    /// Returns whether the chord is consonant in the common-practice sense:
218    /// one pitch name, two whose closed-position interval is consonant, or a
219    /// major or minor triad not in second inversion.
220    pub fn is_consonant(&self) -> bool {
221        let distinct = self.remove_redundant_pitch_names();
222        match distinct.notes.len() {
223            1 => true,
224            2 => {
225                let closed = self.closed_position(None, false).remove_redundant_pitches();
226                Interval::between_pitches(&closed.notes[0].pitch, &closed.notes[1].pitch)
227                    .is_ok_and(|interval| interval.is_consonant())
228            }
229            3 => (self.is_major_triad() || self.is_minor_triad()) && self.inversion() != Some(2),
230            _ => false,
231        }
232    }
233
234    /// The first pitch at the given chord step above a root the caller
235    /// decided on, rather than the one the chord infers: music21's
236    /// `getChordStep(step, testRoot)`.
237    pub fn chord_step_with_root(&self, step: u8, root: &Pitch) -> Option<&Pitch> {
238        self.chord_step_from(step, root)
239    }
240
241    /// Every chord step above `root` the chord has, each with the index of
242    /// the first pitch on it, in the order the pitches come: music21's
243    /// `chord.tools.allChordSteps`. One pass over the pitches, where asking
244    /// [`Self::chord_step_with_root`] for each step would be one per step.
245    #[must_use]
246    pub fn all_chord_steps(&self, root: &Pitch) -> Vec<(u8, usize)> {
247        let mut found: Vec<(u8, usize)> = Vec::new();
248        for (index, pitch) in self.pitch_refs().enumerate() {
249            let step = diatonic_steps_above(root, pitch);
250            if !found.iter().any(|(seen, _)| *seen == step) {
251                found.push((step, index));
252            }
253        }
254        found
255    }
256
257    /// The semitone distance from a caller-supplied root to the pitch at the
258    /// given chord step: music21's `semitonesFromChordStep(step, testRoot)`.
259    pub fn semitones_from_chord_step_with_root(&self, step: u8, root: &Pitch) -> Option<u8> {
260        let pitch = self.chord_step_from(step, root)?;
261        Some(semitones_above(root, pitch))
262    }
263
264    /// The inversion measured from a root the caller decided on: music21's
265    /// `inversion(testRoot=...)`.
266    pub fn inversion_from_root(&self, root: &Pitch) -> Option<u8> {
267        self.inversion_with_root(root)
268    }
269
270    /// Whether the chord has a pitch on every one of these steps above the
271    /// root, which is how the triad and seventh predicates ask for their
272    /// third, fifth and seventh without finding the root for each.
273    pub(super) fn has_steps_from(&self, root: &Pitch, steps: &[u8]) -> bool {
274        steps
275            .iter()
276            .all(|&step| self.chord_step_from(step, root).is_some())
277    }
278
279    pub(crate) fn chord_step_from(&self, step: u8, root: &Pitch) -> Option<&Pitch> {
280        let step = fold_chord_step(step);
281        self.pitch_refs()
282            .find(|pitch| diatonic_steps_above(root, pitch) == step)
283    }
284
285    pub(super) fn is_triad_of_type(&self, address: (u8, u8, i8), quality: TriadQuality) -> bool {
286        // The cheap count first, so a chord that is no triad never looks for
287        // its root.
288        if self.unique_pitch_name_count() != 3 {
289            return false;
290        }
291
292        let Some(root) = self.root() else {
293            return false;
294        };
295
296        let spelled = self.spelled_triad_from(root) == Some(quality);
297        // music21 asks the chord tables first. Three names with no two of
298        // them one pitch class, a third and a fifth at these distances: that
299        // *is* the set class, so the search through the tables -- the dear
300        // part of this, and one `common_name` has already made -- would only
301        // say so again. The tests hold it to that.
302        debug_assert!(!spelled || self.forte_address() == Some(address));
303        spelled
304    }
305
306    /// The quality of a correctly spelled major, minor, diminished or
307    /// augmented triad above a root already found, and `None` for any other
308    /// chord. One look at the root answers all four triad predicates.
309    pub(crate) fn spelled_triad_from(&self, root: &Pitch) -> Option<TriadQuality> {
310        if !self.is_triad_from(root) || self.has_any_enharmonic_spelled_pitches() {
311            return None;
312        }
313
314        let third = semitones_above(root, self.chord_step_from(3, root)?);
315        let fifth = semitones_above(root, self.chord_step_from(5, root)?);
316        match (third, fifth) {
317            (4, 7) => Some(TriadQuality::Major),
318            (3, 7) => Some(TriadQuality::Minor),
319            (3, 6) => Some(TriadQuality::Diminished),
320            (4, 8) => Some(TriadQuality::Augmented),
321            _ => None,
322        }
323    }
324
325    pub(super) fn is_incomplete_triad_of_type(
326        &self,
327        address: (u8, u8),
328        third_semitones: u8,
329    ) -> bool {
330        if self
331            .forte_address()
332            .is_none_or(|(card, index, _)| (card, index) != address)
333        {
334            return false;
335        }
336        let Some(root) = self.root() else {
337            return false;
338        };
339        if self.chord_step_from(3, root).is_none() {
340            return false;
341        }
342
343        self.pitch_refs()
344            .all(|pitch| [0, third_semitones].contains(&semitones_above(root, pitch)))
345    }
346
347    /// Returns whether the chord is an Italian, French, German or Swiss
348    /// augmented sixth. Each must be in its conventional inversion unless
349    /// `permit_any_inversion` is set.
350    pub fn is_augmented_sixth(&self, permit_any_inversion: bool) -> bool {
351        match self.pitch_class_cardinality() {
352            3 => self.is_italian_augmented_sixth(permit_any_inversion, false),
353            4 => {
354                // One look in the chord tables serves all three types.
355                let found = self.forte_address();
356                self.is_french_from(found, permit_any_inversion)
357                    || self.is_german_from(found, permit_any_inversion)
358                    || self.is_swiss_from(found, permit_any_inversion)
359            }
360            _ => false,
361        }
362    }
363
364    /// Returns whether the chord is an Italian augmented sixth, such as
365    /// `A- C F#`.
366    pub fn is_italian_augmented_sixth(
367        &self,
368        permit_any_inversion: bool,
369        restrict_doublings: bool,
370    ) -> bool {
371        let Some(root) = self.augmented_sixth_root(
372            self.forte_address(),
373            (3, 8, 1),
374            1,
375            permit_any_inversion,
376            &AUGMENTED_SIXTHS.italian,
377        ) else {
378            return false;
379        };
380        if !restrict_doublings {
381            return true;
382        }
383
384        // The third and fifth above the root the type check already found.
385        let (Some(third), Some(fifth)) =
386            (self.chord_step_from(3, root), self.chord_step_from(5, root))
387        else {
388            return false;
389        };
390        self.pitch_refs().all(|pitch| {
391            pitch.name() == fifth.name() || std::ptr::eq(pitch, third) || std::ptr::eq(pitch, root)
392        })
393    }
394
395    /// Returns whether the chord is a French augmented sixth, such as
396    /// `A- C D F#`.
397    pub fn is_french_augmented_sixth(&self, permit_any_inversion: bool) -> bool {
398        self.is_french_from(self.forte_address(), permit_any_inversion)
399    }
400
401    /// [`Self::is_french_augmented_sixth`] given the chord's Forte address,
402    /// so a caller testing several types looks it up once.
403    pub(super) fn is_french_from(
404        &self,
405        found: Option<(u8, u8, i8)>,
406        permit_any_inversion: bool,
407    ) -> bool {
408        self.augmented_sixth_root(
409            found,
410            (4, 25, 0),
411            2,
412            permit_any_inversion,
413            &AUGMENTED_SIXTHS.french,
414        )
415        .is_some()
416    }
417
418    /// Returns whether the chord is a German augmented sixth, such as
419    /// `A- C E- F#`.
420    pub fn is_german_augmented_sixth(&self, permit_any_inversion: bool) -> bool {
421        self.is_german_from(self.forte_address(), permit_any_inversion)
422    }
423
424    /// [`Self::is_german_augmented_sixth`] given the chord's Forte address,
425    /// so a caller testing several types looks it up once.
426    pub(super) fn is_german_from(
427        &self,
428        found: Option<(u8, u8, i8)>,
429        permit_any_inversion: bool,
430    ) -> bool {
431        self.augmented_sixth_root(
432            found,
433            (4, 27, -1),
434            1,
435            permit_any_inversion,
436            &AUGMENTED_SIXTHS.german,
437        )
438        .is_some()
439    }
440
441    /// Returns whether the chord is a Swiss augmented sixth, such as
442    /// `A- C D# F#`.
443    pub fn is_swiss_augmented_sixth(&self, permit_any_inversion: bool) -> bool {
444        self.is_swiss_from(self.forte_address(), permit_any_inversion)
445    }
446
447    /// [`Self::is_swiss_augmented_sixth`] given the chord's Forte address,
448    /// so a caller testing several types looks it up once.
449    pub(super) fn is_swiss_from(
450        &self,
451        found: Option<(u8, u8, i8)>,
452        permit_any_inversion: bool,
453    ) -> bool {
454        self.augmented_sixth_root(
455            found,
456            (4, 27, -1),
457            2,
458            permit_any_inversion,
459            &AUGMENTED_SIXTHS.swiss,
460        )
461        .is_some()
462    }
463
464    /// Returns whether the chord is five distinct pitch names with a third,
465    /// fifth, seventh and ninth above the root.
466    pub fn is_ninth(&self) -> bool {
467        self.unique_pitch_name_count() == 5
468            && self
469                .root()
470                .is_some_and(|root| self.has_steps_from(root, &[3, 5, 7, 2]))
471    }
472
473    /// Returns whether some transposition other than the octave maps the
474    /// pitch-class set onto itself. With `require_intervallic_evenness` only
475    /// the evenly spaced sets count, the way Straus defines the property.
476    pub fn is_transpositionally_symmetrical(&self, require_intervallic_evenness: bool) -> bool {
477        let Some((card, index, _)) = self.forte_address() else {
478            return self.notes.is_empty();
479        };
480        if card == 1 {
481            return require_intervallic_evenness;
482        }
483        const EVEN: [(u8, u8); 5] = [(2, 6), (3, 12), (4, 28), (6, 35), (12, 1)];
484        const UNEVEN: [(u8, u8); 10] = [
485            (4, 9),
486            (4, 25),
487            (6, 7),
488            (6, 20),
489            (6, 30),
490            (8, 9),
491            (8, 25),
492            (8, 28),
493            (9, 12),
494            (10, 6),
495        ];
496        EVEN.contains(&(card, index))
497            || (!require_intervallic_evenness && UNEVEN.contains(&(card, index)))
498    }
499
500    /// Returns whether two pitches share a letter under different
501    /// accidentals, such as `E` and `E-`.
502    pub fn has_any_repeated_diatonic_note(&self) -> bool {
503        let steps = self
504            .pitch_refs()
505            .map(Pitch::step)
506            .collect::<std::collections::BTreeSet<_>>();
507        steps.len() != self.unique_pitch_name_count()
508    }
509
510    /// The root of the chord when it is the augmented sixth these
511    /// arguments describe, and `None` when it is not. `found` is the chord's
512    /// own Forte address, passed in so a caller testing several types looks
513    /// it up once; the root is found once and handed back for the same
514    /// reason.
515    pub(super) fn augmented_sixth_root(
516        &self,
517        found: Option<(u8, u8, i8)>,
518        address: (u8, u8, i8),
519        required_inversion: u8,
520        permit_any_inversion: bool,
521        intervals: &[[Interval; 2]],
522    ) -> Option<&Pitch> {
523        if found != Some(address) || self.has_any_enharmonic_spelled_pitches() {
524            return None;
525        }
526
527        let root = self.root()?;
528        if !permit_any_inversion && self.inversion_with_root(root) != Some(required_inversion) {
529            return None;
530        }
531
532        let steps = [3, 5, 7].map(|step| self.chord_step_from(step, root));
533        let matches = intervals.iter().zip(steps).all(|(accepted, step)| {
534            step.and_then(|pitch| Interval::between_pitches(root, pitch).ok())
535                .is_some_and(|interval| {
536                    accepted.iter().any(|candidate| {
537                        candidate.directed_simple_key() == interval.directed_simple_key()
538                    })
539                })
540        });
541        matches.then_some(root)
542    }
543
544    pub(super) fn has_intervals_above_root(&self, intervals: &[u8]) -> bool {
545        let Some(root_pitch) = self.find_root_pitch() else {
546            return false;
547        };
548        let root_pc = root::pitch_class(root_pitch);
549        let chord_pcs = self.pitch_class_set();
550        intervals
551            .iter()
552            .all(|interval| chord_pcs.contains(&((root_pc + interval) % 12)))
553    }
554
555    /// Returns the interval from the root to the first pitch lying on the
556    /// given chord step, compound intervals included, so the third of
557    /// `C3 G3 E4 C5` is a major tenth. `None` when the chord has no root or
558    /// no pitch on that step.
559    pub fn interval_from_chord_step(&self, step: u8) -> Option<Interval> {
560        let root = self.root()?;
561        self.pitch_refs()
562            .filter_map(|pitch| Interval::between_pitches(root, pitch).ok())
563            .find(|interval| interval.mod7() == IntegerType::from(step))
564    }
565}
566
567/// The quality of the triad above a chord's root, as music21's
568/// `Chord.quality` reports it.
569#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
570#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
571pub enum TriadQuality {
572    /// A major third with a perfect fifth, or a major third alone.
573    Major,
574    /// A minor third with a perfect fifth, or a minor third alone.
575    Minor,
576    /// A major third with an augmented fifth.
577    Augmented,
578    /// A minor third with a diminished fifth.
579    Diminished,
580    /// Anything else, including a missing third or a repeated chord step.
581    Other,
582}
583
584impl TriadQuality {
585    /// Returns music21's lowercase name for the quality.
586    pub fn as_str(self) -> &'static str {
587        match self {
588            Self::Major => "major",
589            Self::Minor => "minor",
590            Self::Augmented => "augmented",
591            Self::Diminished => "diminished",
592            Self::Other => "other",
593        }
594    }
595}
596
597impl Display for TriadQuality {
598    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
599        f.write_str(self.as_str())
600    }
601}
602
603pub(super) fn fold_chord_step(step: u8) -> u8 {
604    if step >= 8 { step - 7 } else { step }
605}
606
607pub(super) fn diatonic_steps_above(root: &Pitch, pitch: &Pitch) -> u8 {
608    ((root::step_num(pitch) - root::step_num(root)).rem_euclid(7) + 1) as u8
609}
610
611pub(super) fn semitones_above(root: &Pitch, pitch: &Pitch) -> u8 {
612    (root::pitch_class(pitch) + 12 - root::pitch_class(root)) % 12
613}
614
615pub(super) struct AugmentedSixthIntervals {
616    italian: [[Interval; 2]; 2],
617    french: [[Interval; 2]; 3],
618    german: [[Interval; 2]; 3],
619    swiss: [[Interval; 2]; 3],
620}
621
622/// The intervals each augmented-sixth type stacks above its root, as music21
623/// spells them: the third and fifth (and seventh) may each be written either
624/// way up.
625pub(super) static AUGMENTED_SIXTHS: LazyLock<AugmentedSixthIntervals> = LazyLock::new(|| {
626    let pair = |up: &str, down: &str| {
627        [
628            Interval::from_name(up).expect("augmented sixth intervals parse"),
629            Interval::from_name(down).expect("augmented sixth intervals parse"),
630        ]
631    };
632    AugmentedSixthIntervals {
633        italian: [pair("d3", "A-6"), pair("d5", "A-4")],
634        french: [pair("M3", "m-6"), pair("d5", "A-4"), pair("m7", "M-2")],
635        german: [pair("d3", "A-6"), pair("d5", "A-4"), pair("d7", "A-2")],
636        swiss: [pair("m3", "M-6"), pair("dd5", "AA-4"), pair("d7", "A-2")],
637    }
638});