Skip to main content

music21/scale/
scaletype.rs

1//! The named scales music21 exposes as `ConcreteScale` subclasses.
2//!
3//! Each scale is a sequence of step intervals walked from the tonic (upward,
4//! except for the one descending step Rag Marwa's network contains),
5//! matching the edges of music21's `IntervalNetwork`, plus the pitch
6//! simplification that network applies. Both together are needed: the steps
7//! alone give the right pitch classes but the wrong spelling for scales that
8//! run out of reasonable accidentals, which is why a C whole-tone scale ends
9//! `A#` rather than `B-` but a B whole-tone scale does not end `A##`.
10
11use crate::error::Result;
12use crate::interval::Interval;
13use crate::pitch::Pitch;
14
15use std::collections::HashMap;
16use std::sync::LazyLock;
17
18pub use super::realized::Scale;
19
20/// How a scale respells pitches that would otherwise pile up accidentals:
21/// music21's `IntervalNetwork.pitchSimplification`.
22///
23/// Every named scale says which it uses. A scale given by its steps spells
24/// with at most one accidental unless it is told otherwise, which is what
25/// music21's interval network does; a Scala scale is told to take the most
26/// common spelling of each note.
27#[derive(Clone, Copy, Debug, Eq, PartialEq)]
28#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
29#[non_exhaustive]
30pub enum Simplification {
31    /// Spell literally, however many accidentals that takes.
32    Exact,
33    /// Cap at one accidental, respelling anything beyond it.
34    MaxAccidental,
35    /// Respell to the most common spelling of the pitch class.
36    MostCommon,
37    /// Respell any double accidental, and `E#`, `B#`, `C-` and `F-`, to a
38    /// simpler name for the same note.
39    SimplifyEnharmonic,
40}
41
42impl Simplification {
43    /// The name music21 gives this rule on a network, or `None` for spelling
44    /// exactly, which music21 writes as `None`.
45    #[must_use]
46    pub fn music21_name(self) -> Option<&'static str> {
47        match self {
48            Self::Exact => None,
49            Self::MaxAccidental => Some("maxAccidental"),
50            Self::MostCommon => Some("mostCommon"),
51            Self::SimplifyEnharmonic => Some("simplifyEnharmonic"),
52        }
53    }
54
55    /// The rule music21 names, `None` and `"none"` being [`Self::Exact`].
56    #[must_use]
57    pub fn from_music21_name(name: Option<&str>) -> Option<Self> {
58        match name {
59            None | Some("none") => Some(Self::Exact),
60            Some("maxAccidental") => Some(Self::MaxAccidental),
61            Some("mostCommon") => Some(Self::MostCommon),
62            Some("simplifyEnharmonic") => Some(Self::SimplifyEnharmonic),
63            Some(_) => None,
64        }
65    }
66}
67
68/// The step intervals the scale tables use, parsed once.
69///
70/// A scale given by its notes rather than by a name can step by anything, so
71/// this is a fast path and not the whole world: a step it does not hold is
72/// parsed on the spot.
73static STEP_INTERVALS: LazyLock<HashMap<&'static str, Interval>> = LazyLock::new(|| {
74    ["m2", "M2", "a2", "m3", "M3", "-M2"]
75        .into_iter()
76        .map(|name| {
77            let interval =
78                Interval::from_name(name).expect("scale step intervals are valid interval names");
79            (name, interval)
80        })
81        .collect()
82});
83
84pub(super) fn step_interval(name: &str) -> Result<Interval> {
85    match STEP_INTERVALS.get(name) {
86        Some(interval) => Ok(interval.clone()),
87        None => Interval::from_name(name),
88    }
89}
90
91/// Steps spanning twelve semitones with the last one spelled so that they
92/// add up to a perfect octave: music21's `_closeOnTonic`.
93///
94/// The steps before the last are walked from C4 spelling with at most one
95/// accidental, and the last step is the interval from there to C5. Steps
96/// that already land on C5 are returned unchanged.
97pub(super) fn close_on_tonic(steps: &[Interval]) -> Result<Vec<Interval>> {
98    let Some((last, leading)) = steps.split_last() else {
99        return Ok(Vec::new());
100    };
101    let octave = Pitch::from_name("C5")?;
102    let mut before_last = Pitch::from_name("C4")?;
103    for step in leading {
104        before_last = step.transpose_pitch_with_options(&before_last, false, Some(1))?;
105    }
106    let landed = last.transpose_pitch_with_options(&before_last, false, Some(4))?;
107    if landed.name_with_octave() == octave.name_with_octave() {
108        return Ok(steps.to_vec());
109    }
110    let mut closed = leading.to_vec();
111    closed.push(Interval::between_pitches(&before_last, &octave)?);
112    Ok(closed)
113}
114
115/// The steps of a cycle that comes back to its tonic within an octave,
116/// repeated to fill the octave and closed on the tonic, or `None` for a
117/// cycle that does not: music21's `AbstractCyclicalScale`, which makes such
118/// a cycle octave-duplicating.
119///
120/// A cycle comes back within an octave when every step is a whole number of
121/// semitones and together they come to 1, 2, 3, 4, 6 or 12.
122pub(super) fn cycle_within_octave(steps: &[Interval]) -> Result<Option<Vec<Interval>>> {
123    if steps.is_empty() || steps.iter().any(|step| step.semitones().fract() != 0.0) {
124        return Ok(None);
125    }
126    let span: crate::defaults::FloatType = steps.iter().map(Interval::semitones).sum();
127    if ![1.0, 2.0, 3.0, 4.0, 6.0, 12.0].contains(&span) {
128        return Ok(None);
129    }
130    let repeats = (12.0 / span) as usize;
131    let filled: Vec<Interval> = steps
132        .iter()
133        .cycle()
134        .take(steps.len() * repeats)
135        .cloned()
136        .collect();
137    close_on_tonic(&filled).map(Some)
138}
139
140/// Which set of solfège syllables [`Scale::solfeg`] uses.
141#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
142#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
143pub enum SolfegVariant {
144    /// music21's own table.
145    Music21,
146    /// The Humdrum spellings, which differ in `my`, `so` and `ty`.
147    Humdrum,
148}
149
150/// music21's `_solfegSyllables`: for each of the seven degrees, the syllable
151/// at alterations of -2, -1, 0, +1 and +2.
152pub const SOLFEG_SYLLABLES: [[&str; 5]; 7] = [
153    ["def", "de", "do", "di", "dis"],
154    ["raf", "ra", "re", "ri", "ris"],
155    ["mef", "me", "mi", "mis", "mish"],
156    ["fef", "fe", "fa", "fi", "fis"],
157    ["sef", "se", "sol", "si", "sis"],
158    ["lef", "le", "la", "li", "lis"],
159    ["tef", "te", "ti", "tis", "tish"],
160];
161
162/// music21's `_humdrumSolfegSyllables`, laid out like [`SOLFEG_SYLLABLES`].
163pub const HUMDRUM_SOLFEG_SYLLABLES: [[&str; 5]; 7] = [
164    ["def", "de", "do", "di", "dis"],
165    ["raf", "ra", "re", "ri", "ris"],
166    ["mef", "me", "mi", "my", "mish"],
167    ["fef", "fe", "fa", "fi", "fis"],
168    ["sef", "se", "so", "si", "sis"],
169    ["lef", "le", "la", "li", "lis"],
170    ["tef", "te", "ti", "ty", "tish"],
171];
172
173/// A named scale from music21's scale module.
174///
175/// Ordered as music21 defines them: the seven church modes, their plagal
176/// counterparts, the altered minors, then the symmetrical and non-Western
177/// scales.
178#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
179#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
180#[must_use]
181#[non_exhaustive]
182pub enum ScaleType {
183    /// Major (Ionian).
184    Major,
185    /// Natural minor (Aeolian).
186    Minor,
187    /// Dorian mode.
188    Dorian,
189    /// Phrygian mode.
190    Phrygian,
191    /// Lydian mode.
192    Lydian,
193    /// Mixolydian mode.
194    Mixolydian,
195    /// Locrian mode.
196    Locrian,
197    /// Hypodorian mode. Shares Dorian's pitches; the ambitus differs.
198    Hypodorian,
199    /// Hypophrygian mode. Shares Phrygian's pitches.
200    Hypophrygian,
201    /// Hypolydian mode. Shares Lydian's pitches.
202    Hypolydian,
203    /// Hypomixolydian mode. Shares Mixolydian's pitches.
204    Hypomixolydian,
205    /// Hypolocrian mode. Shares Locrian's pitches.
206    Hypolocrian,
207    /// Hypoaeolian mode. Shares natural minor's pitches.
208    Hypoaeolian,
209    /// Harmonic minor, with a raised seventh.
210    HarmonicMinor,
211    /// Ascending melodic minor.
212    MelodicMinor,
213    /// Twelve-tone chromatic scale.
214    Chromatic,
215    /// Six-tone whole-tone scale.
216    WholeTone,
217    /// Eight-tone octatonic scale, alternating tone and semitone.
218    Octatonic,
219    /// Rag Asawari, as a five-tone ascending scale.
220    RagAsawari,
221    /// Rag Marwa, as a seven-step ascending scale.
222    ///
223    /// Not monotonic: music21's ascending network dips back down a major
224    /// second from the sixth degree before rising a minor third to the octave,
225    /// so the realized pitches repeat a note and briefly descend.
226    RagMarwa,
227}
228
229impl ScaleType {
230    /// Every scale type, in declaration order.
231    pub const ALL: [ScaleType; 20] = [
232        Self::Major,
233        Self::Minor,
234        Self::Dorian,
235        Self::Phrygian,
236        Self::Lydian,
237        Self::Mixolydian,
238        Self::Locrian,
239        Self::Hypodorian,
240        Self::Hypophrygian,
241        Self::Hypolydian,
242        Self::Hypomixolydian,
243        Self::Hypolocrian,
244        Self::Hypoaeolian,
245        Self::HarmonicMinor,
246        Self::MelodicMinor,
247        Self::Chromatic,
248        Self::WholeTone,
249        Self::Octatonic,
250        Self::RagAsawari,
251        Self::RagMarwa,
252    ];
253
254    /// Returns the music21 class name for this scale.
255    pub fn music21_name(self) -> &'static str {
256        match self {
257            Self::Major => "MajorScale",
258            Self::Minor => "MinorScale",
259            Self::Dorian => "DorianScale",
260            Self::Phrygian => "PhrygianScale",
261            Self::Lydian => "LydianScale",
262            Self::Mixolydian => "MixolydianScale",
263            Self::Locrian => "LocrianScale",
264            Self::Hypodorian => "HypodorianScale",
265            Self::Hypophrygian => "HypophrygianScale",
266            Self::Hypolydian => "HypolydianScale",
267            Self::Hypomixolydian => "HypomixolydianScale",
268            Self::Hypolocrian => "HypolocrianScale",
269            Self::Hypoaeolian => "HypoaeolianScale",
270            Self::HarmonicMinor => "HarmonicMinorScale",
271            Self::MelodicMinor => "MelodicMinorScale",
272            Self::Chromatic => "ChromaticScale",
273            Self::WholeTone => "WholeToneScale",
274            Self::Octatonic => "OctatonicScale",
275            Self::RagAsawari => "RagAsawari",
276            Self::RagMarwa => "RagMarwa",
277        }
278    }
279
280    /// The words music21 puts after the tonic when it names a scale:
281    /// `"C major"`, `"C harmonic minor"`, `"C Rag Asawari"`.
282    ///
283    /// The capitalisation is upstream's and is not consistent — the modes are
284    /// lower case, the others are not — which is why this is a table rather
285    /// than something derived from the class name.
286    pub fn music21_descriptive_name(self) -> &'static str {
287        match self {
288            Self::Major => "major",
289            Self::Minor => "minor",
290            Self::Dorian => "dorian",
291            Self::Phrygian => "phrygian",
292            Self::Lydian => "lydian",
293            Self::Mixolydian => "mixolydian",
294            Self::Locrian => "locrian",
295            Self::Hypodorian => "hypodorian",
296            Self::Hypophrygian => "hypophrygian",
297            Self::Hypolydian => "hypolydian",
298            Self::Hypomixolydian => "hypomixolydian",
299            Self::Hypolocrian => "hypolocrian",
300            Self::Hypoaeolian => "hypoaeolian",
301            Self::HarmonicMinor => "harmonic minor",
302            Self::MelodicMinor => "melodic minor",
303            Self::Chromatic => "Chromatic",
304            Self::WholeTone => "Whole tone",
305            Self::Octatonic => "Octatonic",
306            Self::RagAsawari => "Rag Asawari",
307            Self::RagMarwa => "Rag Marwa",
308        }
309    }
310
311    /// The scale type music21 calls by this class name, such as
312    /// `"MajorScale"`.
313    pub fn from_music21_name(name: &str) -> Option<Self> {
314        Self::ALL
315            .into_iter()
316            .find(|scale_type| scale_type.music21_name() == name)
317    }
318
319    /// Which degree of the realized scale is its final: music21's
320    /// `tonicDegree`.
321    ///
322    /// A plagal mode — the six that music21 prefixes `Hypo` — runs from a
323    /// fourth below its final to a fifth above it, so the note the music
324    /// comes to rest on is its fourth degree and not its first. Every other
325    /// scale here starts on its own tonic.
326    pub fn tonic_degree(self) -> usize {
327        if self.is_plagal() { 4 } else { 1 }
328    }
329
330    /// Which degree is the reciting tone: music21's `dominantDegree`.
331    ///
332    /// A fifth above the final in the authentic modes. The plagal ones took
333    /// theirs a third above the authentic dominant and then moved it off any
334    /// B, which is why hypophrygian and hypomixolydian differ from the rest.
335    pub fn dominant_degree(self) -> usize {
336        match self {
337            Self::Hypophrygian | Self::Hypomixolydian => 7,
338            _ if self.is_plagal() => 6,
339            _ => 5,
340        }
341    }
342
343    /// The steps walked from the pitch the scale is *realized* from, which
344    /// for a plagal mode is not its final.
345    ///
346    /// `steps` is the collection written from the final, which is
347    /// how every one of these scales is named. A plagal mode is realized
348    /// from a fourth below that, so its walk starts three steps earlier in
349    /// the same cycle — the rotation that puts the final at the degree
350    /// [`Self::tonic_degree`] names.
351    pub fn realization_steps(self) -> Vec<&'static str> {
352        let steps = self.steps();
353        let count = steps.len();
354        let start = (count + 1 - self.tonic_degree()) % count;
355        steps[start..]
356            .iter()
357            .chain(&steps[..start])
358            .copied()
359            .collect()
360    }
361
362    /// The step a scale carries on past its own octave, where it has one.
363    ///
364    /// Rag Marwa is the only one here: its network keeps going a semitone
365    /// above the terminus, so the collection realized from `C` closes on the
366    /// octave and then sounds the `D-` above it. music21 calls it "a pitch
367    /// beyond the terminus" and gives it whenever the realization is not
368    /// bounded by a range.
369    pub fn beyond_terminus(self) -> Option<&'static str> {
370        match self {
371            Self::RagMarwa => Some("m2"),
372            _ => None,
373        }
374    }
375
376    /// The collection this scale uses coming down, where that is not the
377    /// one it uses going up.
378    ///
379    /// The melodic minor is the familiar case — it raises its sixth and
380    /// seventh degrees ascending and lets them fall descending, which is the
381    /// natural minor — and Rag Asawari's avaroha is that same collection.
382    /// Every other scale here descends through the notes it ascends
383    /// through, and answers `None`.
384    pub fn descending_form(self) -> Option<Self> {
385        match self {
386            Self::MelodicMinor | Self::RagAsawari => Some(Self::Minor),
387            _ => None,
388        }
389    }
390
391    /// The degrees the notes of this scale's ascent stand on, where they are
392    /// not simply counted off one to a note.
393    ///
394    /// Rag Asawari's aroha leaves out the third and the seventh, so its five
395    /// notes stand on the first, second, fourth, fifth and sixth degrees. It
396    /// has no third going up at all — which is what music21 answers when
397    /// asked for one — and its fourth degree is its third note.
398    pub fn ascending_degrees(self) -> Option<&'static [u8]> {
399        match self {
400            Self::RagAsawari => Some(&[1, 2, 4, 5, 6]),
401            _ => None,
402        }
403    }
404
405    /// The steps this scale is walked by coming down, where coming down is
406    /// not simply the ascending pattern read backwards and no other named
407    /// scale is that pattern.
408    ///
409    /// Rag Marwa's avarohana is the one: from its tonic it rises a semitone
410    /// to the flat second *above* the octave and falls from there, which is
411    /// music21's network edge from the high terminus upward before anything
412    /// descends. Written as a rising list from the tonic it closes by falling
413    /// back onto it, so the flat second is both the second degree and the
414    /// seventh — which is what music21 answers when asked which degree a
415    /// `D-` is coming down.
416    pub fn descending_steps(self) -> Option<&'static [&'static str]> {
417        match self {
418            Self::RagMarwa => Some(&["m2", "A2", "M2", "m3", "M2", "d3", "-m2"]),
419            _ => None,
420        }
421    }
422
423    /// Whether this is a plagal mode, whose range sits below its final.
424    pub fn is_plagal(self) -> bool {
425        matches!(
426            self,
427            Self::Hypodorian
428                | Self::Hypophrygian
429                | Self::Hypolydian
430                | Self::Hypomixolydian
431                | Self::Hypolocrian
432                | Self::Hypoaeolian
433        )
434    }
435
436    /// Returns the step intervals walked from the tonic.
437    ///
438    /// Almost every scale ascends throughout; Rag Marwa is the exception, and
439    /// carries one descending step (`-M2`), matching its network edge.
440    ///
441    /// These are music21's `IntervalNetwork` edges, not the intervals between
442    /// the pitches it finally reports — the two differ wherever simplification
443    /// respells a degree.
444    pub(super) fn steps(self) -> &'static [&'static str] {
445        match self {
446            Self::Major => &["M2", "M2", "m2", "M2", "M2", "M2", "m2"],
447            Self::Minor | Self::Hypoaeolian => &["M2", "m2", "M2", "M2", "m2", "M2", "M2"],
448            Self::Dorian => &["M2", "m2", "M2", "M2", "M2", "m2", "M2"],
449            Self::Phrygian => &["m2", "M2", "M2", "M2", "m2", "M2", "M2"],
450            Self::Lydian => &["M2", "M2", "M2", "m2", "M2", "M2", "m2"],
451            Self::Mixolydian => &["M2", "M2", "m2", "M2", "M2", "m2", "M2"],
452            Self::Locrian => &["m2", "M2", "M2", "m2", "M2", "M2", "M2"],
453            Self::Hypodorian => &["M2", "m2", "M2", "M2", "M2", "m2", "M2"],
454            Self::Hypophrygian => &["m2", "M2", "M2", "M2", "m2", "M2", "M2"],
455            Self::Hypolydian => &["M2", "M2", "M2", "m2", "M2", "M2", "m2"],
456            Self::Hypomixolydian => &["M2", "M2", "m2", "M2", "M2", "m2", "M2"],
457            Self::Hypolocrian => &["m2", "M2", "M2", "m2", "M2", "M2", "M2"],
458            Self::HarmonicMinor => &["M2", "m2", "M2", "M2", "m2", "a2", "m2"],
459            Self::MelodicMinor => &["M2", "m2", "M2", "M2", "M2", "M2", "m2"],
460            // The last step lands on the tonic's octave by name, as music21's
461            // `_closeOnTonic` spells it: eleven minor seconds spelled with one
462            // accidental reach C- from C, and C- to C is an augmented unison.
463            Self::Chromatic => &[
464                "m2", "m2", "m2", "m2", "m2", "m2", "m2", "m2", "m2", "m2", "m2", "a1",
465            ],
466            Self::WholeTone => &["M2", "M2", "M2", "M2", "M2", "d3"],
467            Self::Octatonic => &["M2", "m2", "M2", "m2", "M2", "m2", "M2", "m2"],
468            Self::RagAsawari => &["M2", "m3", "M2", "m2", "M3"],
469            // The sixth step is music21's `M-2` edge: a descending major
470            // second inside an otherwise ascending network.
471            Self::RagMarwa => &["m2", "a2", "M2", "m3", "M2", "-M2", "m3"],
472        }
473    }
474
475    /// Returns how this scale respells pitches, matching music21's network.
476    pub(super) fn simplification(self) -> Simplification {
477        match self {
478            Self::WholeTone | Self::Octatonic | Self::RagMarwa => Simplification::MaxAccidental,
479            Self::Chromatic | Self::RagAsawari => Simplification::MostCommon,
480            _ => Simplification::Exact,
481        }
482    }
483
484    /// Returns the number of distinct degrees in one octave.
485    pub fn degree_count(self) -> usize {
486        self.steps().len()
487    }
488}
489
490/// The tonics music21's `IntervalNetwork.find` tries, in its order. Ties in
491/// the ranking fall back to this order reversed.
492pub(super) const SCALE_STARTS: [&str; 15] = [
493    "C", "C#", "Db", "D", "D#", "Eb", "E", "F", "F#", "G", "G#", "A", "Bb", "B", "Cb",
494];
495
496impl ScaleType {
497    /// Ranks every candidate tonic by how many of `pitches` fall in this
498    /// scale type built on it, best first, as music21's `deriveRanked` does.
499    /// Pitches are compared by pitch class and duplicates count separately.
500    ///
501    /// Each candidate is realized between the lowest and the highest of
502    /// `pitches`, so what is compared is the scale where the pitches are: a
503    /// scale that comes down differently from how it goes up, or changes from
504    /// one octave to the next, is compared as it stands there.
505    pub fn derive_ranked(
506        self,
507        pitches: &[Pitch],
508        limit: Option<usize>,
509    ) -> Result<Vec<(usize, Scale)>> {
510        self.derive_ranked_by(pitches, limit, DegreeComparison::PitchClass)
511    }
512
513    /// The same, saying how a pitch is matched against a scale degree.
514    ///
515    /// By pitch class an `E#` is in C major, since the scale has an `F`; by
516    /// name it is not. music21 offers both, and its `deriveRanked` defaults
517    /// to the first.
518    pub fn derive_ranked_by(
519        self,
520        pitches: &[Pitch],
521        limit: Option<usize>,
522        comparison: DegreeComparison,
523    ) -> Result<Vec<(usize, Scale)>> {
524        rank_on_every_start(pitches, limit, comparison, |tonic| Scale::new(self, tonic))
525    }
526
527    /// Returns this scale type on the tonic that fits `pitches` best.
528    pub fn derive(self, pitches: &[Pitch]) -> Result<Scale> {
529        self.derive_ranked(pitches, Some(1))?
530            .pop()
531            .map(|(_, scale)| scale)
532            .ok_or_else(|| crate::error::Error::Scale("no candidate tonics".to_string()))
533    }
534
535    /// Returns every tonic on which this scale type contains all of `pitches`,
536    /// best-ranked first.
537    pub fn derive_all(self, pitches: &[Pitch]) -> Result<Vec<Scale>> {
538        Ok(self
539            .derive_ranked(pitches, None)?
540            .into_iter()
541            .filter(|(matched, _)| *matched == pitches.len())
542            .map(|(_, scale)| scale)
543            .collect())
544    }
545}
546
547/// `place` put on every tonic `SCALE_STARTS` names, each counted by how many
548/// of `pitches` it holds between their lowest and highest, best first:
549/// music21's `deriveRanked`, ties going to the higher tonic.
550pub(super) fn rank_on_every_start(
551    pitches: &[Pitch],
552    limit: Option<usize>,
553    comparison: DegreeComparison,
554    place: impl Fn(Pitch) -> Scale,
555) -> Result<Vec<(usize, Scale)>> {
556    let targets = pitches
557        .iter()
558        .map(|pitch| comparison.key(pitch))
559        .collect::<Vec<_>>();
560    let Some((lowest, highest)) = target_range(pitches) else {
561        return Ok(Vec::new());
562    };
563    let mut ranked = Vec::with_capacity(SCALE_STARTS.len());
564    for start in SCALE_STARTS {
565        let scale = place(Pitch::from_name(start)?);
566        let degrees = scale
567            .pitches_between(lowest, highest)?
568            .iter()
569            .map(|pitch| comparison.key(pitch))
570            .collect::<Vec<_>>();
571        let matched = targets
572            .iter()
573            .filter(|target| degrees.contains(target))
574            .count();
575        ranked.push((matched, scale));
576    }
577    ranked.sort_by(|left, right| {
578        left.0
579            .cmp(&right.0)
580            .then_with(|| left.1.tonic().ps().total_cmp(&right.1.tonic().ps()))
581    });
582    ranked.reverse();
583    if let Some(limit) = limit {
584        ranked.truncate(limit);
585    }
586    Ok(ranked)
587}
588
589/// The lowest and the highest of some pitches, which is the range music21's
590/// `filterPitchList` realizes a candidate scale over; `None` for no pitches.
591pub(super) fn target_range(pitches: &[Pitch]) -> Option<(&Pitch, &Pitch)> {
592    let lowest = pitches.iter().min_by(|a, b| a.ps().total_cmp(&b.ps()))?;
593    let highest = pitches.iter().max_by(|a, b| a.ps().total_cmp(&b.ps()))?;
594    Some((lowest, highest))
595}
596
597/// How many octaves of a scale [`Scale::pitches_between`] will walk, which
598/// is the whole of music21's pitch space and then some.
599pub(super) const MAX_RANGE_OCTAVES: usize = 12;
600
601/// How a pitch is matched against a scale degree: music21's
602/// `comparisonAttribute`.
603#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
604#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
605#[non_exhaustive]
606pub enum DegreeComparison {
607    /// By sounding note, so `E#` matches the `F` of C major.
608    PitchClass,
609    /// By written note, so it does not.
610    Name,
611    /// By letter alone, so an `E-` matches the `E` of C major.
612    Step,
613    /// By sounding pitch, octave included: music21's `ps`.
614    Ps,
615    /// By written note and octave.
616    NameWithOctave,
617}
618
619impl DegreeComparison {
620    /// What two pitches have to share to count as the same degree.
621    #[must_use]
622    pub fn key(self, pitch: &Pitch) -> String {
623        match self {
624            Self::PitchClass => pitch.pitch_class().number().to_string(),
625            Self::Name => pitch.name(),
626            Self::Step => pitch.name().chars().take(1).collect(),
627            Self::Ps => pitch.ps().to_string(),
628            Self::NameWithOctave => pitch.name_with_octave(),
629        }
630    }
631
632    /// The comparison music21 names by attribute, such as `"pitchClass"`.
633    #[must_use]
634    pub fn from_music21_name(name: &str) -> Option<Self> {
635        match name {
636            "pitchClass" => Some(Self::PitchClass),
637            "name" => Some(Self::Name),
638            "step" => Some(Self::Step),
639            "ps" => Some(Self::Ps),
640            "nameWithOctave" => Some(Self::NameWithOctave),
641            _ => None,
642        }
643    }
644}
645
646/// Transposes one scale step, applying the scale's simplification.
647pub(super) fn advance(
648    pitch: &Pitch,
649    interval: &Interval,
650    simplification: Simplification,
651) -> Result<Pitch> {
652    match simplification {
653        Simplification::MaxAccidental => {
654            interval.transpose_pitch_with_options(pitch, false, Some(1))
655        }
656        // music21 transposes with its default cap of four accidentals when it
657        // is not told to spell with one, and respells past that.
658        Simplification::Exact => interval.transpose_pitch_with_options(pitch, false, Some(4)),
659        Simplification::MostCommon | Simplification::SimplifyEnharmonic => {
660            let mut transposed = interval.transpose_pitch_with_options(pitch, false, Some(4))?;
661            if transposed.accidental().alter() != 0.0 {
662                let most_common = simplification == Simplification::MostCommon;
663                transposed.simplify_enharmonic_in_place(most_common)?;
664            }
665            Ok(transposed)
666        }
667    }
668}
669
670/// Returns the maximum accidental count used by a scale, for tests.
671#[cfg(test)]
672fn max_alter(pitches: &[Pitch]) -> crate::defaults::IntegerType {
673    pitches
674        .iter()
675        .map(|pitch| pitch.accidental().alter().abs() as crate::defaults::IntegerType)
676        .max()
677        .unwrap_or(0)
678}
679
680#[cfg(test)]
681mod tests {
682    use crate::defaults::{FloatType, IntegerType};
683    #[test]
684    fn a_scala_scale_is_a_cycle_walked_from_its_tonic() {
685        use super::Scale;
686        use crate::Pitch;
687        use crate::tuningsystem::scala::ScalaScale;
688
689        // music21: `scale.ScalaScale('c4', 'slendro').getPitches('c3', 'c5')`.
690        // Below the tonic the notes are reached coming down and spelled for
691        // it, so the fifth degree is B-3 forty cents flat under the tonic
692        // and A~4 ten cents sharp over it.
693        let slendro = ScalaScale::parse(
694            "! slendro.scl
695!
696Observed Javanese Slendro scale, Helmholtz/Ellis p. 518, nr.94
697 5
698!
699 228.00000
700 484.00000
701 728.00000
702 960.00000
703 2/1
704",
705        )
706        .unwrap();
707        let scale = Scale::from_scala(Pitch::from_name("C4").unwrap(), &slendro).unwrap();
708        let spelled: Vec<String> = scale
709            .pitches_between(
710                &Pitch::from_name("C3").unwrap(),
711                &Pitch::from_name("C5").unwrap(),
712            )
713            .unwrap()
714            .iter()
715            .map(|pitch| match pitch.microtone() {
716                Some(microtone) if microtone.cents() != 0.0 => {
717                    format!("{}{microtone}", pitch.name_with_octave())
718                }
719                _ => pitch.name_with_octave(),
720            })
721            .collect();
722        assert_eq!(
723            spelled,
724            [
725                "C3",
726                "D~3(-22c)",
727                "F3(-16c)",
728                "G~3(-22c)",
729                "Bb3(-40c)",
730                "C4",
731                "D~4(-22c)",
732                "F4(-16c)",
733                "G~4(-22c)",
734                "A~4(+10c)",
735                "C5"
736            ]
737        );
738        assert!(!scale.octave_duplicating());
739    }
740
741    #[test]
742    fn degrees_are_found_by_pitch_class_name_or_step() {
743        use super::{DegreeComparison, Scale, ScaleType};
744        use crate::Pitch;
745
746        let major = Scale::new(ScaleType::Major, Pitch::from_name("C").unwrap());
747        let e_sharp = Pitch::from_name("E#").unwrap();
748        assert_eq!(
749            major
750                .degree_of_by(&e_sharp, DegreeComparison::PitchClass)
751                .unwrap(),
752            Some(4)
753        );
754        assert_eq!(
755            major
756                .degree_of_by(&e_sharp, DegreeComparison::Name)
757                .unwrap(),
758            None
759        );
760        assert_eq!(
761            major
762                .degree_of_by(&e_sharp, DegreeComparison::Step)
763                .unwrap(),
764            Some(3)
765        );
766        let e_flat = Pitch::from_name("Eb").unwrap();
767        let (degree, accidental) = major.degree_and_accidental_of(&e_flat).unwrap();
768        assert_eq!(degree, 3);
769        assert_eq!(accidental.as_ref().map(|a| a.name()), Some("flat"));
770        let whole_tone = Scale::new(ScaleType::WholeTone, Pitch::from_name("C").unwrap());
771        assert!(
772            whole_tone
773                .degree_and_accidental_of(&Pitch::from_name("B").unwrap())
774                .is_err()
775        );
776
777        // Rag Marwa names its A twice, as the fifth degree and the seventh.
778        let marwa = Scale::new(ScaleType::RagMarwa, Pitch::from_name("C4").unwrap());
779        assert_eq!(
780            marwa
781                .degrees_of_by(&Pitch::from_name("A").unwrap(), DegreeComparison::Name)
782                .unwrap(),
783            [5, 7]
784        );
785    }
786
787    #[test]
788    fn a_scale_moves_to_its_relatives_parallels_and_a_new_tonic() {
789        use super::{Scale, ScaleType};
790        use crate::Pitch;
791
792        let tonic = |scale: &Scale| scale.tonic().name();
793        let c_minor = Scale::new(ScaleType::Minor, Pitch::from_name("C").unwrap());
794        assert_eq!(tonic(&c_minor.parallel_major()), "C");
795        assert_eq!(c_minor.parallel_major().scale_type(), ScaleType::Major);
796        assert_eq!(tonic(&c_minor.relative_major().unwrap()), "Eb");
797        let c_major = Scale::new(ScaleType::Major, Pitch::from_name("C").unwrap());
798        assert_eq!(tonic(&c_major.relative_minor().unwrap()), "A");
799        assert_eq!(c_major.parallel_minor().scale_type(), ScaleType::Minor);
800        let mut moved = c_major.clone();
801        moved.set_tonic(Pitch::from_name("D").unwrap());
802        assert_eq!(tonic(&moved), "D");
803        assert_eq!(moved.pitches().unwrap()[1].name(), "E");
804        assert!(c_major.octave_duplicating());
805        assert!(c_major.is_realizable());
806        assert_eq!(
807            ScaleType::from_music21_name("MajorScale"),
808            Some(ScaleType::Major)
809        );
810        assert_eq!(ScaleType::from_music21_name("NoSuchScale"), None);
811    }
812
813    #[test]
814    fn a_range_is_walked_from_where_music21_starts_it() {
815        // Every answer read off music21 11.0.0b9.
816        use super::Scale;
817        use crate::Pitch;
818        let pitch = |name: &str| Pitch::from_name(name).unwrap();
819        let named = |pitches: Vec<Pitch>| -> Vec<String> {
820            pitches.iter().map(Pitch::name_with_octave).collect()
821        };
822        let between = |scale_type: ScaleType, tonic: &str, low: &str, high: &str| {
823            named(
824                Scale::new(scale_type, pitch(tonic))
825                    .pitches_between(&pitch(low), &pitch(high))
826                    .unwrap(),
827            )
828        };
829        let coming_down = |scale_type: ScaleType, tonic: &str| {
830            named(
831                Scale::new(scale_type, pitch(tonic))
832                    .pitches_descending()
833                    .unwrap(),
834            )
835        };
836
837        // A whole-tone scale repeats at the octave, walked up from the octave
838        // of its tonic below the range (music21 11.0.0b19).
839        assert_eq!(
840            between(ScaleType::WholeTone, "Bb4", "C#4", "G#4"),
841            ["D4", "E4", "F#4", "G#4"]
842        );
843        // An octave-repeating scale starts from the octave of its tonic just
844        // below the range, however far below the range the tonic is.
845        assert_eq!(
846            between(ScaleType::Octatonic, "G#2", "C#4", "G#4"),
847            ["C#4", "D4", "E4", "F4", "G4", "G#4"]
848        );
849        // And stops at the first note at or past the top, so Rag Marwa's
850        // turn back down to G4 is not counted twice.
851        assert_eq!(
852            between(ScaleType::RagMarwa, "Bb3", "C#4", "G#4"),
853            ["D4", "E4", "G4"]
854        );
855        // Coming down, a scale is walked down, and spells as it goes.
856        assert_eq!(
857            coming_down(ScaleType::RagAsawari, "Bb3"),
858            ["Bb4", "Ab4", "F#4", "F4", "Eb4", "C#4", "C4", "Bb3"]
859        );
860        assert_eq!(
861            coming_down(ScaleType::RagMarwa, "C4"),
862            ["Db5", "C5", "Db5", "B4", "A4", "F#4", "E4", "Db4", "C4"]
863        );
864    }
865
866    #[test]
867    fn a_scale_is_derived_from_where_the_pitches_are() {
868        use super::DegreeComparison;
869        use crate::Pitch;
870        // music21 realizes each candidate between the lowest and highest
871        // pitch it is given, so a spelling the scale only has elsewhere does
872        // not count. Read off music21 11.0.0b19.
873        let pitches: Vec<Pitch> = ["F#", "A", "C#", "E#"]
874            .iter()
875            .map(|name| Pitch::from_name(*name).unwrap())
876            .collect();
877        let ranked: Vec<(usize, String)> = ScaleType::WholeTone
878            .derive_ranked_by(&pitches, Some(2), DegreeComparison::Name)
879            .unwrap()
880            .into_iter()
881            .map(|(matched, scale)| (matched, scale.tonic().name()))
882            .collect();
883        assert_eq!(ranked, [(3, "B".to_string()), (3, "A".to_string())]);
884    }
885
886    #[test]
887    fn a_scale_walks_down_as_well_as_up() {
888        use super::{Scale, ScaleType};
889        use crate::Pitch;
890
891        let names = |pitches: Vec<Pitch>| -> Vec<String> {
892            pitches.iter().map(Pitch::name_with_octave).collect()
893        };
894        let major = Scale::new(ScaleType::Major, Pitch::from_name("C4").unwrap());
895        assert_eq!(
896            names(major.pitches_descending().unwrap()),
897            ["C5", "B4", "A4", "G4", "F4", "E4", "D4", "C4"]
898        );
899        let low = Pitch::from_name("C3").unwrap();
900        let high = Pitch::from_name("C5").unwrap();
901        assert_eq!(
902            names(
903                major
904                    .pitches_between_descending(&Pitch::from_name("G4").unwrap(), &high)
905                    .unwrap()
906            ),
907            ["C5", "B4", "A4", "G4"]
908        );
909        assert_eq!(
910            names(
911                major
912                    .pitches_from_scale_degrees_between(&[1, 5], &low, &high)
913                    .unwrap()
914            ),
915            ["C3", "G3", "C4", "G4", "C5"]
916        );
917
918        // A pitch off the scale comes onto it first: below C#4 in C major
919        // is B3 from the lower neighbour and C4 from the upper.
920        let c_sharp = Pitch::from_name("C#4").unwrap();
921        assert_eq!(
922            major
923                .next_pitch_below(&c_sharp, 1)
924                .unwrap()
925                .name_with_octave(),
926            "C4"
927        );
928        assert_eq!(
929            major
930                .next_pitch_beside(&c_sharp, -1, true)
931                .unwrap()
932                .name_with_octave(),
933            "B3"
934        );
935        assert_eq!(
936            major
937                .next_pitch_beside(&c_sharp, -1, false)
938                .unwrap()
939                .name_with_octave(),
940            "C4"
941        );
942        assert_eq!(
943            major
944                .next_pitch_beside(&c_sharp, 1, false)
945                .unwrap()
946                .name_with_octave(),
947            "E4"
948        );
949
950        // Rag Marwa stands D- in two places, as the note above its tonic and
951        // the one it passes through coming down from the octave, and each
952        // has its own neighbour.
953        let marwa = Scale::new(ScaleType::RagMarwa, Pitch::from_name("C4").unwrap());
954        let d_flat = Pitch::from_name("D-4").unwrap();
955        assert_eq!(marwa.places_of(&d_flat).unwrap(), 1);
956        assert_eq!(
957            marwa
958                .next_pitch_above_from(&d_flat, 1, 0)
959                .unwrap()
960                .name_with_octave(),
961            "E4"
962        );
963        assert_eq!(
964            marwa
965                .next_pitch_below_from(&Pitch::from_name("C5").unwrap(), 1, 0)
966                .unwrap()
967                .name_with_octave(),
968            "A4"
969        );
970    }
971
972    #[test]
973    fn a_custom_scale_ranks_the_tonics_that_fit_a_set_of_pitches() {
974        use super::{DegreeComparison, Scale};
975        use crate::Pitch;
976
977        let pitches: Vec<Pitch> = ["C4", "D4", "E4", "F4", "G4", "A4", "B4", "C5"]
978            .iter()
979            .map(|name| Pitch::from_name(*name).unwrap())
980            .collect();
981        let custom = Scale::from_pitches(&pitches).unwrap();
982        assert!(custom.is_custom());
983        let targets: Vec<Pitch> = ["G4", "B4", "D5"]
984            .iter()
985            .map(|name| Pitch::from_name(*name).unwrap())
986            .collect();
987        let ranked = custom
988            .derive_ranked_by(&targets, Some(2), DegreeComparison::PitchClass)
989            .unwrap();
990        assert_eq!(ranked.len(), 2);
991        assert_eq!(ranked[0].0, 3);
992        assert!(ranked[0].1.is_custom());
993    }
994
995    /// A scale carrying its own tuning retunes the notes it names, in their
996    /// own octaves and spellings, and leaves the notes it does not name
997    /// where they are.
998    #[test]
999    fn a_stream_is_tuned_onto_a_scale() {
1000        use super::Scale;
1001        use crate::stream::StreamElement;
1002        use crate::{Chord, Note, Pitch, Stream};
1003
1004        let tuned: Vec<Pitch> = [
1005            ("C4", 0.0),
1006            ("D4", 20.0),
1007            ("E4", 0.0),
1008            ("F4", 0.0),
1009            ("G4", 0.0),
1010            ("A4", -15.0),
1011            ("B4", 0.0),
1012            ("C5", 0.0),
1013        ]
1014        .iter()
1015        .map(|(name, cents)| {
1016            let mut pitch = Pitch::from_name(*name).unwrap();
1017            pitch.set_microtone_cents(*cents).unwrap();
1018            pitch
1019        })
1020        .collect();
1021        let scale = Scale::from_pitches(&tuned).unwrap();
1022        let mut stream = Stream::new();
1023        for name in ["D5", "F#4", "A3", "B#4", "Gb5"] {
1024            stream.push(Note::from_pitch(Pitch::from_name(name).unwrap()));
1025        }
1026        stream.push(Chord::new("C5 E5 G5").unwrap());
1027        scale.tune(&mut stream).unwrap();
1028        let sounding: Vec<(String, FloatType)> = stream
1029            .events()
1030            .iter()
1031            .flat_map(|event| match event.element() {
1032                StreamElement::Note(note) => {
1033                    vec![(note.pitch().name_with_octave(), note.pitch().ps())]
1034                }
1035                StreamElement::Chord(chord) => chord
1036                    .pitches()
1037                    .iter()
1038                    .map(|pitch| (pitch.name_with_octave(), pitch.ps()))
1039                    .collect(),
1040                _ => Vec::new(),
1041            })
1042            .collect();
1043        let expected: Vec<(String, FloatType)> = [
1044            ("D5", 74.2),
1045            ("F#4", 66.0),
1046            ("A3", 56.85),
1047            ("B#4", 72.0),
1048            ("Gb5", 78.0),
1049            ("C5", 72.0),
1050            ("E5", 76.0),
1051            ("G5", 79.0),
1052        ]
1053        .iter()
1054        .map(|(name, ps)| (name.to_string(), *ps))
1055        .collect();
1056        assert_eq!(sounding.len(), expected.len());
1057        for ((name, ps), (wanted_name, wanted_ps)) in sounding.iter().zip(&expected) {
1058            assert_eq!(name, wanted_name);
1059            assert!(
1060                (ps - wanted_ps).abs() < 1e-9,
1061                "{name} sounds at {ps}, not {wanted_ps}"
1062            );
1063        }
1064    }
1065
1066    /// music21's own `romanNumeral` example, and the Scala reading of a
1067    /// major scale.
1068    #[test]
1069    fn a_scale_carries_numerals_and_writes_itself_as_scala() {
1070        use super::{Scale, ScaleType};
1071        use crate::Pitch;
1072        use crate::tuningsystem::scala::ScalaDegree;
1073
1074        let scale = Scale::new(ScaleType::Major, Pitch::from_name("Ab4").unwrap());
1075        let tonic = scale.roman_numeral(1).unwrap();
1076        assert_eq!(tonic.to_chord().unwrap().root().unwrap().to_string(), "Ab4");
1077        let dominant = scale.roman_numeral(5).unwrap();
1078        assert_eq!(
1079            dominant.to_chord().unwrap().root().unwrap().to_string(),
1080            "Eb5"
1081        );
1082        assert_eq!(dominant.figure_and_key(), "V in Ab major");
1083        assert!(scale.roman_numeral(8).is_err());
1084
1085        let scala = scale.scala_data().unwrap();
1086        assert_eq!(scala.len(), 7);
1087        assert!(matches!(scala.degrees()[0], ScalaDegree::Ratio(_)));
1088        let cents: Vec<i64> = scala
1089            .degrees()
1090            .iter()
1091            .map(|degree| degree.cents().round() as i64)
1092            .collect();
1093        assert_eq!(cents, [0, 200, 400, 500, 700, 900, 1100]);
1094        assert_eq!(scala.period().cents().round() as i64, 1200);
1095        assert_eq!(scala.description(), "Ab major");
1096    }
1097
1098    #[test]
1099    fn a_scale_can_be_given_by_its_notes() {
1100        // music21's own example: a scale of four notes, which repeats at the
1101        // octave like any other.
1102        let given: Vec<Pitch> = ["C4", "Eb4", "Gb4", "A4"]
1103            .iter()
1104            .map(|name| Pitch::from_name(*name).expect("valid pitch"))
1105            .collect();
1106        let scale = Scale::from_pitches(&given).expect("a scale");
1107        assert!(scale.is_custom());
1108        assert_eq!(scale.degree_count(), 4);
1109        let realized: Vec<String> = scale
1110            .pitches()
1111            .expect("realizes")
1112            .iter()
1113            .map(Pitch::name_with_octave)
1114            .collect();
1115        assert_eq!(realized, ["C4", "Eb4", "Gb4", "A4", "C5"]);
1116        assert_eq!(scale.pitch_at_degree(4).unwrap().name_with_octave(), "A4");
1117        // The fifth degree of a four-note scale is the first again, in the
1118        // octave the scale stands in — music21 reads a degree within the one
1119        // octave its network holds.
1120        assert_eq!(scale.pitch_at_degree(5).unwrap().name_with_octave(), "C4");
1121        assert_eq!(
1122            scale.degree_of(&Pitch::from_name("G-").unwrap()).unwrap(),
1123            Some(3)
1124        );
1125
1126        // And it walks a range the way a named scale does.
1127        let range: Vec<String> = scale
1128            .pitches_between(
1129                &Pitch::from_name("Eb5").unwrap(),
1130                &Pitch::from_name("C6").unwrap(),
1131            )
1132            .expect("a range")
1133            .iter()
1134            .map(Pitch::name_with_octave)
1135            .collect();
1136        assert_eq!(range, ["Eb5", "Gb5", "A5", "C6"]);
1137
1138        assert!(Scale::from_pitches(&[]).is_err());
1139    }
1140    #[test]
1141    fn a_range_starts_at_the_first_scale_pitch_inside_it() {
1142        // music21's own example: C major from E-flat 5 to G-flat 7 starts on
1143        // E5, the first scale pitch that is not below the bottom.
1144        let scale = Scale::new(ScaleType::Major, Pitch::from_name("C").unwrap());
1145        let range = scale
1146            .pitches_between(
1147                &Pitch::from_name("E-5").unwrap(),
1148                &Pitch::from_name("G-7").unwrap(),
1149            )
1150            .unwrap();
1151        let names: Vec<String> = range.iter().map(Pitch::name_with_octave).take(4).collect();
1152        assert_eq!(names, ["E5", "F5", "G5", "A5"]);
1153        assert_eq!(range.last().unwrap().name_with_octave(), "F7");
1154
1155        // A range of exactly one octave has both ends in it.
1156        let octave = scale
1157            .pitches_between(
1158                &Pitch::from_name("C3").unwrap(),
1159                &Pitch::from_name("C4").unwrap(),
1160            )
1161            .unwrap();
1162        let names: Vec<String> = octave.iter().map(Pitch::name_with_octave).collect();
1163        assert_eq!(names, ["C3", "D3", "E3", "F3", "G3", "A3", "B3", "C4"]);
1164
1165        // Asked the other way round, the same range comes back descending,
1166        // which is what music21 does.
1167        let descending: Vec<String> = scale
1168            .pitches_between(
1169                &Pitch::from_name("C5").unwrap(),
1170                &Pitch::from_name("C4").unwrap(),
1171            )
1172            .unwrap()
1173            .iter()
1174            .map(Pitch::name_with_octave)
1175            .collect();
1176        assert_eq!(descending, ["C5", "B4", "A4", "G4", "F4", "E4", "D4", "C4"]);
1177    }
1178
1179    #[test]
1180    fn scale_helpers_match_music21() {
1181        let c_major = Scale::new(ScaleType::Major, Pitch::from_name("C4").unwrap());
1182        let pitch = |name: &str| Pitch::from_name(name).unwrap();
1183        let names = |pitches: &[Pitch]| -> Vec<String> {
1184            pitches.iter().map(Pitch::name_with_octave).collect()
1185        };
1186
1187        assert_eq!(c_major.degree_count(), 7);
1188        assert_eq!(
1189            Scale::new(ScaleType::Chromatic, pitch("C4")).degree_count(),
1190            12
1191        );
1192        assert_eq!(
1193            c_major
1194                .transpose(&Interval::from_name("P5").unwrap())
1195                .unwrap()
1196                .tonic()
1197                .name_with_octave(),
1198            "G4"
1199        );
1200        assert_eq!(
1201            names(&c_major.chord().unwrap().pitches()),
1202            ["C4", "D4", "E4", "F4", "G4", "A4", "B4", "C5"]
1203        );
1204        assert_eq!(
1205            names(
1206                &c_major
1207                    .pitches_from_scale_degrees(&[1, 3, 5, 8, 10])
1208                    .unwrap()
1209            ),
1210            ["C4", "E4", "G4", "C5"]
1211        );
1212        assert_eq!(
1213            c_major.interval_between_degrees(1, 5).unwrap().short_name(),
1214            "P5"
1215        );
1216        assert_eq!(
1217            c_major.interval_between_degrees(3, 7).unwrap().short_name(),
1218            "P5"
1219        );
1220        assert_eq!(
1221            c_major
1222                .interval_between_degrees(5, 2)
1223                .unwrap()
1224                .directed_name(),
1225            "P-4"
1226        );
1227        assert_eq!(
1228            c_major.interval_between_degrees(2, 9).unwrap().short_name(),
1229            "P1"
1230        );
1231
1232        assert!(c_major.is_next(&pitch("D4"), &pitch("C4"), 1).unwrap());
1233        assert!(c_major.is_next(&pitch("D5"), &pitch("C4"), 1).unwrap());
1234        assert!(!c_major.is_next(&pitch("E4"), &pitch("C4"), 1).unwrap());
1235        assert!(c_major.is_next(&pitch("E4"), &pitch("C4"), 2).unwrap());
1236
1237        let (matched, unmatched) = c_major
1238            .match_pitches(&["C4", "E4", "Gb4", "Bb5", "A"].map(pitch))
1239            .unwrap();
1240        assert_eq!(names(&matched), ["C4", "E4", "A4"]);
1241        assert_eq!(names(&unmatched), ["Gb4", "Bb5"]);
1242
1243        assert_eq!(
1244            names(
1245                &c_major
1246                    .find_missing(&["C4", "E4", "G4"].map(pitch))
1247                    .unwrap()
1248            ),
1249            ["D4", "F4", "A4", "B4"]
1250        );
1251        let a_minor = Scale::new(ScaleType::Minor, pitch("A"));
1252        assert_eq!(
1253            names(
1254                &a_minor
1255                    .find_missing(&["A", "B", "C", "E"].map(pitch))
1256                    .unwrap()
1257            ),
1258            ["D5", "F5", "G5"]
1259        );
1260        assert!(
1261            c_major
1262                .find_missing(&["C4", "D4", "E4", "F4", "G4", "A4", "B4"].map(pitch))
1263                .unwrap()
1264                .is_empty()
1265        );
1266    }
1267
1268    #[test]
1269    fn solfeg_matches_music21() {
1270        let c_major = Scale::new(ScaleType::Major, Pitch::from_name("C4").unwrap());
1271        let cases = [
1272            ("C4", "do", "do", "do"),
1273            ("C#4", "di", "di", "do"),
1274            ("D-4", "ra", "ra", "re"),
1275            ("E-4", "me", "me", "mi"),
1276            ("F#4", "fi", "fi", "fa"),
1277            ("G-4", "se", "se", "sol"),
1278            ("G4", "sol", "so", "sol"),
1279            ("A-4", "le", "le", "la"),
1280            ("B-4", "te", "te", "ti"),
1281            ("C-4", "de", "de", "do"),
1282            ("B#4", "tis", "ty", "ti"),
1283            ("F##4", "fis", "fis", "fa"),
1284            ("E#4", "mis", "my", "mi"),
1285            ("D##4", "ris", "ris", "re"),
1286        ];
1287        for (name, music21, humdrum, plain) in cases {
1288            let pitch = Pitch::from_name(name).unwrap();
1289            assert_eq!(
1290                c_major
1291                    .solfeg(&pitch, SolfegVariant::Music21, true)
1292                    .unwrap(),
1293                music21,
1294                "{name}"
1295            );
1296            assert_eq!(
1297                c_major
1298                    .solfeg(&pitch, SolfegVariant::Humdrum, true)
1299                    .unwrap(),
1300                humdrum,
1301                "{name}"
1302            );
1303            assert_eq!(
1304                c_major
1305                    .solfeg(&pitch, SolfegVariant::Music21, false)
1306                    .unwrap(),
1307                plain,
1308                "{name}"
1309            );
1310        }
1311        let chromatic = Scale::new(ScaleType::Chromatic, Pitch::from_name("C4").unwrap());
1312        assert_eq!(
1313            chromatic
1314                .solfeg(
1315                    &Pitch::from_name("D4").unwrap(),
1316                    SolfegVariant::Music21,
1317                    true
1318                )
1319                .unwrap(),
1320            "mi"
1321        );
1322        assert!(
1323            chromatic
1324                .solfeg(
1325                    &Pitch::from_name("B4").unwrap(),
1326                    SolfegVariant::Music21,
1327                    true
1328                )
1329                .is_err()
1330        );
1331        assert!(
1332            c_major
1333                .solfeg(
1334                    &Pitch::from_name("C###4").unwrap(),
1335                    SolfegVariant::Music21,
1336                    true
1337                )
1338                .is_err()
1339        );
1340    }
1341    use super::*;
1342
1343    #[test]
1344    fn degrees_and_neighbouring_pitches_match_music21() {
1345        let scale = Scale::new(ScaleType::Major, Pitch::from_name("G4").unwrap());
1346        let degree = |name: &str| scale.degree_of(&Pitch::from_name(name).unwrap()).unwrap();
1347        assert_eq!(degree("G4"), Some(1));
1348        assert_eq!(degree("A4"), Some(2));
1349        assert_eq!(degree("F#5"), Some(7));
1350        assert_eq!(degree("B"), Some(3));
1351        assert_eq!(degree("B-4"), None);
1352        assert_eq!(degree("E3"), Some(6));
1353        assert_eq!(
1354            scale
1355                .degree_of_pitch_class(&Pitch::from_name("G-4").unwrap())
1356                .unwrap(),
1357            Some(7)
1358        );
1359
1360        let cases = [
1361            ("G4", true, 1, "A4"),
1362            ("G4", false, 1, "F#4"),
1363            ("F#4", true, 1, "G4"),
1364            ("B4", true, 3, "E5"),
1365            ("G4", false, 2, "E4"),
1366            ("E-4", true, 1, "E4"),
1367            ("E-4", false, 1, "D4"),
1368            ("B-4", false, 1, "A4"),
1369            ("G4", true, 8, "A5"),
1370            ("D5", true, 7, "D6"),
1371            ("G", true, 1, "A"),
1372            ("F#5", true, 1, "G5"),
1373            ("C3", false, 4, "F#2"),
1374        ];
1375        for (origin, ascending, steps, expected) in cases {
1376            let origin_pitch = Pitch::from_name(origin).unwrap();
1377            let next = if ascending {
1378                scale.next_pitch_above(&origin_pitch, steps)
1379            } else {
1380                scale.next_pitch_below(&origin_pitch, steps)
1381            };
1382            assert_eq!(
1383                next.unwrap().name_with_octave(),
1384                expected,
1385                "{origin} {ascending} {steps}"
1386            );
1387        }
1388        assert!(
1389            scale
1390                .next_pitch_above(&Pitch::from_name("G4").unwrap(), 0)
1391                .is_err()
1392        );
1393    }
1394
1395    #[test]
1396    fn derivation_matches_music21() {
1397        let pitches = |names: &[&str]| {
1398            names
1399                .iter()
1400                .map(|name| Pitch::from_name(*name).unwrap())
1401                .collect::<Vec<_>>()
1402        };
1403        type Row = (
1404            &'static [&'static str],
1405            ScaleType,
1406            &'static str,
1407            [(&'static str, usize); 4],
1408            &'static [&'static str],
1409        );
1410        let cases: [Row; 12] = [
1411            (
1412                &["C", "E", "G"],
1413                ScaleType::Major,
1414                "G",
1415                [("G", 3), ("F", 3), ("C", 3), ("Bb", 2)],
1416                &["G", "F", "C"],
1417            ),
1418            (
1419                &["C", "E", "G"],
1420                ScaleType::Minor,
1421                "A",
1422                [("A", 3), ("E", 3), ("D", 3), ("B", 2)],
1423                &["A", "E", "D"],
1424            ),
1425            (
1426                &["C", "E", "G"],
1427                ScaleType::Dorian,
1428                "A",
1429                [("A", 3), ("G", 3), ("D", 3), ("Bb", 2)],
1430                &["A", "G", "D"],
1431            ),
1432            (
1433                &["F#", "A", "C#", "E"],
1434                ScaleType::Major,
1435                "A",
1436                [("A", 4), ("E", 4), ("D", 4), ("B", 3)],
1437                &["A", "E", "D"],
1438            ),
1439            (
1440                &["F#", "A", "C#", "E"],
1441                ScaleType::Minor,
1442                "B",
1443                [("B", 4), ("F#", 4), ("Db", 4), ("C#", 4)],
1444                &["B", "F#", "Db", "C#", "Cb"],
1445            ),
1446            (
1447                &["G#", "B", "D", "F"],
1448                ScaleType::HarmonicMinor,
1449                "A",
1450                [("A", 4), ("F#", 4), ("Eb", 4), ("D#", 4)],
1451                &["A", "F#", "Eb", "D#", "C"],
1452            ),
1453            (
1454                &["Bb", "D", "F", "A-"],
1455                ScaleType::Major,
1456                "Eb",
1457                [("Eb", 4), ("D#", 4), ("Bb", 3), ("G#", 3)],
1458                &["Eb", "D#"],
1459            ),
1460            (
1461                &["Bb", "D", "F", "A-"],
1462                ScaleType::Dorian,
1463                "F",
1464                [("F", 4), ("Bb", 3), ("G#", 3), ("G", 3)],
1465                &["F"],
1466            ),
1467            (
1468                &["C", "D", "E", "F#", "G", "A", "B"],
1469                ScaleType::Major,
1470                "G",
1471                [("G", 7), ("D", 6), ("C", 6), ("A", 5)],
1472                &["G"],
1473            ),
1474            (
1475                &["C", "D", "E", "F#", "G", "A", "B"],
1476                ScaleType::Minor,
1477                "E",
1478                [("E", 7), ("B", 6), ("A", 6), ("Cb", 6)],
1479                &["E"],
1480            ),
1481            (
1482                &["C", "C#", "D"],
1483                ScaleType::Major,
1484                "Bb",
1485                [("Bb", 2), ("A", 2), ("G#", 2), ("G", 2)],
1486                &[],
1487            ),
1488            (
1489                &["Eb", "G", "Bb"],
1490                ScaleType::Major,
1491                "Bb",
1492                [("Bb", 3), ("G#", 3), ("Eb", 3), ("D#", 3)],
1493                &["Bb", "G#", "Eb", "D#"],
1494            ),
1495        ];
1496        for (names, scale_type, best, ranked, all) in cases {
1497            let input = pitches(names);
1498            assert_eq!(
1499                scale_type.derive(&input).unwrap().tonic().name(),
1500                best,
1501                "{scale_type:?} {names:?}"
1502            );
1503            let top = scale_type
1504                .derive_ranked(&input, Some(4))
1505                .unwrap()
1506                .into_iter()
1507                .map(|(matched, scale)| (scale.tonic().name(), matched))
1508                .collect::<Vec<_>>();
1509            let expected = ranked
1510                .iter()
1511                .map(|(tonic, matched)| (tonic.to_string(), *matched))
1512                .collect::<Vec<_>>();
1513            assert_eq!(top, expected, "{scale_type:?} {names:?}");
1514            let complete = scale_type
1515                .derive_all(&input)
1516                .unwrap()
1517                .iter()
1518                .map(|scale| scale.tonic().name())
1519                .collect::<Vec<_>>();
1520            assert_eq!(complete, all, "{scale_type:?} {names:?}");
1521        }
1522    }
1523
1524    #[test]
1525    fn degree_with_accidental_matches_music21() {
1526        let scale = Scale::new(ScaleType::Major, Pitch::from_name("C4").unwrap());
1527        let cases = [
1528            ("C4", 1, None),
1529            ("D4", 2, None),
1530            ("E-4", 3, Some("flat")),
1531            ("F#4", 4, Some("sharp")),
1532            ("G", 5, None),
1533            ("A#", 6, Some("sharp")),
1534            ("Bb", 7, Some("flat")),
1535            ("D--4", 2, Some("double-flat")),
1536            ("C#4", 1, Some("sharp")),
1537            ("E#4", 3, Some("sharp")),
1538        ];
1539        for (name, degree, accidental) in cases {
1540            let (found, found_accidental) = scale
1541                .degree_and_accidental_of(&Pitch::from_name(name).unwrap())
1542                .unwrap();
1543            assert_eq!(found, degree, "{name}");
1544            assert_eq!(
1545                found_accidental
1546                    .as_ref()
1547                    .map(|accidental| accidental.name()),
1548                accidental,
1549                "{name}"
1550            );
1551        }
1552    }
1553
1554    fn names(scale_type: ScaleType, tonic: &str) -> Vec<String> {
1555        Scale::new(scale_type, Pitch::from_name(tonic).expect("valid tonic"))
1556            .pitches()
1557            .expect("scale realizes")
1558            .iter()
1559            .map(|pitch| pitch.name())
1560            .collect()
1561    }
1562
1563    #[test]
1564    fn realizes_the_church_modes_on_c() {
1565        assert_eq!(
1566            names(ScaleType::Major, "C4"),
1567            ["C", "D", "E", "F", "G", "A", "B", "C"]
1568        );
1569        assert_eq!(
1570            names(ScaleType::Minor, "C4"),
1571            ["C", "D", "Eb", "F", "G", "Ab", "Bb", "C"]
1572        );
1573        assert_eq!(
1574            names(ScaleType::Dorian, "C4"),
1575            ["C", "D", "Eb", "F", "G", "A", "Bb", "C"]
1576        );
1577        assert_eq!(
1578            names(ScaleType::Phrygian, "C4"),
1579            ["C", "Db", "Eb", "F", "G", "Ab", "Bb", "C"]
1580        );
1581        assert_eq!(
1582            names(ScaleType::Lydian, "C4"),
1583            ["C", "D", "E", "F#", "G", "A", "B", "C"]
1584        );
1585        assert_eq!(
1586            names(ScaleType::Mixolydian, "C4"),
1587            ["C", "D", "E", "F", "G", "A", "Bb", "C"]
1588        );
1589        assert_eq!(
1590            names(ScaleType::Locrian, "C4"),
1591            ["C", "Db", "Eb", "F", "Gb", "Ab", "Bb", "C"]
1592        );
1593    }
1594
1595    #[test]
1596    fn realizes_the_altered_minors() {
1597        assert_eq!(
1598            names(ScaleType::HarmonicMinor, "C4"),
1599            ["C", "D", "Eb", "F", "G", "Ab", "B", "C"]
1600        );
1601        assert_eq!(
1602            names(ScaleType::MelodicMinor, "C4"),
1603            ["C", "D", "Eb", "F", "G", "A", "B", "C"]
1604        );
1605    }
1606
1607    #[test]
1608    fn plagal_modes_share_their_authentic_pitches() {
1609        for (plagal, authentic) in [
1610            (ScaleType::Hypodorian, ScaleType::Dorian),
1611            (ScaleType::Hypophrygian, ScaleType::Phrygian),
1612            (ScaleType::Hypolydian, ScaleType::Lydian),
1613            (ScaleType::Hypomixolydian, ScaleType::Mixolydian),
1614            (ScaleType::Hypolocrian, ScaleType::Locrian),
1615            (ScaleType::Hypoaeolian, ScaleType::Minor),
1616        ] {
1617            let mut plagal_names = names(plagal, "C4");
1618            plagal_names.sort();
1619            plagal_names.dedup();
1620            let mut authentic_names = names(authentic, "C4");
1621            authentic_names.sort();
1622            authentic_names.dedup();
1623            assert_eq!(
1624                plagal_names, authentic_names,
1625                "{plagal:?} should share {authentic:?}'s pitch collection"
1626            );
1627        }
1628    }
1629
1630    #[test]
1631    fn a_plagal_mode_is_realized_a_fourth_below_its_final() {
1632        // music21's own example: the hypodorian on D runs A3 to A4, and the
1633        // note it comes to rest on is its fourth degree.
1634        let scale = Scale::new(
1635            ScaleType::Hypodorian,
1636            Pitch::from_name("d").expect("valid tonic"),
1637        );
1638        let realized: Vec<String> = scale
1639            .pitches()
1640            .expect("scale realizes")
1641            .iter()
1642            .map(Pitch::name_with_octave)
1643            .collect();
1644        assert_eq!(
1645            realized,
1646            ["A3", "B3", "C4", "D4", "E4", "F4", "G4", "A4"],
1647            "a plagal mode starts a fourth below its final"
1648        );
1649        assert_eq!(scale.final_pitch().unwrap().name_with_octave(), "D4");
1650        assert_eq!(scale.dominant().unwrap().name_with_octave(), "F4");
1651
1652        // An authentic mode starts on its own final, and its dominant is the
1653        // fifth degree.
1654        let dorian = Scale::new(
1655            ScaleType::Dorian,
1656            Pitch::from_name("d").expect("valid tonic"),
1657        );
1658        assert_eq!(dorian.final_pitch().unwrap().name_with_octave(), "D4");
1659        assert_eq!(dorian.dominant().unwrap().name_with_octave(), "A4");
1660    }
1661
1662    #[test]
1663    fn a_leading_tone_is_a_semitone_below_the_final() {
1664        // In a minor scale that is not the seventh degree the scale has.
1665        let minor = Scale::new(
1666            ScaleType::Minor,
1667            Pitch::from_name("c").expect("valid tonic"),
1668        );
1669        assert_eq!(minor.pitch_at_degree(7).unwrap().name(), "Bb");
1670        assert_eq!(minor.leading_tone().unwrap().name(), "B");
1671        // In a major scale it already is.
1672        let major = Scale::new(
1673            ScaleType::Major,
1674            Pitch::from_name("C").expect("valid tonic"),
1675        );
1676        assert_eq!(major.leading_tone().unwrap().name_with_octave(), "B4");
1677    }
1678
1679    #[test]
1680    fn whole_tone_spells_upward_until_accidentals_run_out() {
1681        // From C the scale stays on sharps and closes on its tonic.
1682        assert_eq!(
1683            names(ScaleType::WholeTone, "C4"),
1684            ["C", "D", "E", "F#", "G#", "A#", "C"]
1685        );
1686        // From B a literal spelling would need G##, so music21 respells.
1687        assert_eq!(
1688            names(ScaleType::WholeTone, "B4"),
1689            ["B", "C#", "D#", "E#", "G", "A", "B"]
1690        );
1691    }
1692
1693    #[test]
1694    fn octatonic_alternates_tone_and_semitone() {
1695        assert_eq!(
1696            names(ScaleType::Octatonic, "C4"),
1697            ["C", "D", "Eb", "F", "Gb", "Ab", "A", "B", "C"]
1698        );
1699        assert_eq!(
1700            names(ScaleType::Octatonic, "G4"),
1701            ["G", "A", "Bb", "C", "Db", "Eb", "Fb", "Gb", "G"]
1702        );
1703        // The walk from E reaches F- on the tonic's place, which is spelled
1704        // as the tonic (music21 11.0.0b19).
1705        assert_eq!(
1706            names(ScaleType::Octatonic, "E4"),
1707            ["E", "F#", "G", "A", "Bb", "C", "Db", "Eb", "E"]
1708        );
1709    }
1710
1711    #[test]
1712    fn chromatic_uses_the_most_common_spelling() {
1713        assert_eq!(
1714            names(ScaleType::Chromatic, "C4"),
1715            [
1716                "C", "C#", "D", "Eb", "E", "F", "F#", "G", "Ab", "A", "Bb", "B", "C"
1717            ]
1718        );
1719    }
1720
1721    #[test]
1722    fn rag_asawari_is_pentatonic() {
1723        assert_eq!(
1724            names(ScaleType::RagAsawari, "C4"),
1725            ["C", "D", "F", "G", "Ab", "C"]
1726        );
1727    }
1728
1729    #[test]
1730    fn rag_marwa_dips_below_its_sixth_degree() {
1731        // music21's ascending network steps down a M2 from B before closing on
1732        // C, so A appears twice and the line is not monotonic — and then it
1733        // carries on a semitone past the octave, which is the one scale here
1734        // that ends above where it closed.
1735        assert_eq!(
1736            names(ScaleType::RagMarwa, "C4"),
1737            ["C", "Db", "E", "F#", "A", "B", "A", "C", "Db"]
1738        );
1739        assert_eq!(
1740            names(ScaleType::RagMarwa, "E-4"),
1741            ["Eb", "Fb", "G", "A", "C", "D", "C", "Eb", "Fb"]
1742        );
1743    }
1744
1745    #[test]
1746    fn simplifying_scales_never_exceed_their_accidental_budget() {
1747        for scale_type in [ScaleType::WholeTone, ScaleType::Octatonic] {
1748            for tonic in ["C4", "G4", "D4", "A4", "E4", "B4", "F#4", "E-4", "G-4"] {
1749                let pitches = Scale::new(scale_type, Pitch::from_name(tonic).unwrap())
1750                    .pitches()
1751                    .unwrap();
1752                assert!(
1753                    max_alter(&pitches) <= 1,
1754                    "{scale_type:?} on {tonic} exceeded one accidental"
1755                );
1756            }
1757        }
1758    }
1759
1760    #[test]
1761    fn a_note_a_scale_stands_twice_has_two_notes_below_it() {
1762        // Rag Marwa comes down through the flat second twice over: once
1763        // above the tonic, its second degree, and once above the octave, its
1764        // seventh. `D-2` may be read as either, and the note below it is `C2`
1765        // or `B1` accordingly. The places run lowest degree first, and the
1766        // plain step below reads the note as the first of them.
1767        let marwa = Scale::new(ScaleType::RagMarwa, Pitch::from_name("C4").unwrap()).descending();
1768        let from = Pitch::from_name("D-2").unwrap();
1769        assert_eq!(marwa.places_of(&from).unwrap(), 2);
1770        let below: Vec<String> = (0..2)
1771            .map(|place| {
1772                marwa
1773                    .next_pitch_below_from(&from, 1, place)
1774                    .unwrap()
1775                    .name_with_octave()
1776            })
1777            .collect();
1778        assert_eq!(below, ["C2", "B1"]);
1779        assert_eq!(
1780            marwa.next_pitch_below(&from, 1).unwrap().name_with_octave(),
1781            "C2"
1782        );
1783
1784        // A note the scale stands only once is the same whichever place is
1785        // asked for, so a caller that always asks for the first is right.
1786        let major = Scale::new(ScaleType::Major, Pitch::from_name("C4").unwrap());
1787        let d = Pitch::from_name("D4").unwrap();
1788        assert_eq!(major.places_of(&d).unwrap(), 1);
1789        assert_eq!(
1790            major
1791                .next_pitch_below_from(&d, 1, 7)
1792                .unwrap()
1793                .name_with_octave(),
1794            "C4"
1795        );
1796    }
1797
1798    #[test]
1799    fn degree_lookup_matches_the_realized_pitches() {
1800        for scale_type in ScaleType::ALL {
1801            let scale = Scale::new(scale_type, Pitch::from_name("E-4").unwrap());
1802            let pitches = scale.pitches().unwrap();
1803            // Every degree but the closing octave, which is the first degree
1804            // again as far as a degree lookup is concerned. Asked by the
1805            // scale's own degrees, since Rag Asawari's are not its positions.
1806            let degrees = scale
1807                .named_degrees()
1808                .unwrap_or_else(|| (1..=scale.degree_count() as IntegerType).collect());
1809            for (expected, degree) in pitches.iter().zip(degrees) {
1810                let actual = scale.pitch_at_degree(degree).unwrap();
1811                assert_eq!(
1812                    actual.name_with_octave(),
1813                    expected.name_with_octave(),
1814                    "{scale_type:?} degree {degree}"
1815                );
1816                // Read back the other way: the degree the note is found on
1817                // stands on that note. Not necessarily the degree asked for
1818                // — Rag Marwa's A is both its fifth and its seventh.
1819                let found = scale.degree_of(expected).unwrap().unwrap();
1820                assert_eq!(
1821                    scale
1822                        .pitch_at_degree(found as IntegerType)
1823                        .unwrap()
1824                        .name_with_octave(),
1825                    expected.name_with_octave(),
1826                    "{scale_type:?} degree {degree} read back as {found}"
1827                );
1828            }
1829            // A degree the scale does not have is nothing, rather than the
1830            // note that would stand there had the degrees been counted off.
1831            if let Some(named) = scale.named_degrees() {
1832                for degree in 1..=*named.last().unwrap() {
1833                    assert_eq!(
1834                        scale.pitch_on_degree(degree).unwrap().is_some(),
1835                        named.contains(&degree),
1836                        "{scale_type:?} degree {degree}"
1837                    );
1838                }
1839            }
1840        }
1841    }
1842
1843    #[test]
1844    fn a_degree_outside_the_scale_counts_round_it() {
1845        // music21's own answers for `scale.PhrygianScale('g').pitchFromDegree`.
1846        let scale = Scale::new(ScaleType::Phrygian, Pitch::from_name("G4").unwrap());
1847        for (degree, expected) in [
1848            (-1, "Eb5"),
1849            (0, "F5"),
1850            (1, "G4"),
1851            (7, "F5"),
1852            (8, "G4"),
1853            (11, "C5"),
1854            (15, "G4"),
1855        ] {
1856            assert_eq!(
1857                scale.pitch_at_degree(degree).unwrap().name_with_octave(),
1858                expected,
1859                "degree {degree}"
1860            );
1861        }
1862    }
1863
1864    #[test]
1865    fn every_scale_realizes_on_every_common_tonic() {
1866        for scale_type in ScaleType::ALL {
1867            for tonic in [
1868                "C4", "G4", "D4", "A4", "E4", "B4", "F#4", "F4", "B-4", "E-4", "A-4",
1869            ] {
1870                let scale = Scale::new(scale_type, Pitch::from_name(tonic).unwrap());
1871                let pitches = scale.pitches().expect("scale realizes");
1872                let beyond = usize::from(scale_type.beyond_terminus().is_some());
1873                assert_eq!(
1874                    pitches.len(),
1875                    scale_type.degree_count() + 1 + beyond,
1876                    "{scale_type:?} on {tonic}"
1877                );
1878            }
1879        }
1880    }
1881
1882    #[test]
1883    fn music21_names_are_distinct() {
1884        let mut names: Vec<&str> = ScaleType::ALL.iter().map(|s| s.music21_name()).collect();
1885        names.sort_unstable();
1886        let count = names.len();
1887        names.dedup();
1888        assert_eq!(names.len(), count, "music21 names must be unique");
1889    }
1890}