Skip to main content

music21/figuredbass/
checker.rs

1//! Finding where a written-out score breaks the voice-leading rules:
2//! music21's `figuredBass.checker`.
3//!
4//! Where [`super::possibility`] says *whether* a voicing breaks a rule, this
5//! says *which parts* do, numbered from one, the highest. A part that is
6//! resting holds [`REST_PS`] in its place and is passed over by every rule.
7//!
8//! The consecutive rules find their candidates by interval alone and leave
9//! the deciding to a [`VoiceLeadingQuartet`]; [`candidates`] and
10//! [`breaks_rule`] are the two halves, so a caller keeping a table of
11//! quartets already decided, as music21 does, asks only for the new ones.
12
13use crate::defaults::FloatType;
14use crate::error::{Error, Result};
15use crate::pitch::Pitch;
16use crate::voiceleading::VoiceLeadingQuartet;
17
18/// The pitch space a resting part is given in a possibility: music21's
19/// `POSSIBILITY_REST_PS`.
20pub const REST_PS: FloatType = 0.0;
21
22/// Whether a pitch stands for a resting part.
23#[must_use]
24pub fn is_rest(pitch: &Pitch) -> bool {
25    pitch.ps() == REST_PS
26}
27
28/// The rules over two possibilities in a row.
29#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
30pub enum ConsecutiveRule {
31    /// Two parts a fifth apart moving to another fifth.
32    ParallelFifths,
33    /// Two parts an octave apart moving to another octave.
34    ParallelOctaves,
35    /// The outer parts moving in similar motion into a fifth.
36    HiddenFifths,
37    /// The outer parts moving in similar motion into an octave.
38    HiddenOctaves,
39}
40
41impl ConsecutiveRule {
42    /// Semitones past whole octaves that the parts must stand apart for the
43    /// rule to need asking.
44    fn semitones(self) -> FloatType {
45        match self {
46            Self::ParallelFifths | Self::HiddenFifths => 7.0,
47            Self::ParallelOctaves | Self::HiddenOctaves => 0.0,
48        }
49    }
50
51    /// Whether the rule is about the outer parts only.
52    fn is_hidden(self) -> bool {
53        matches!(self, Self::HiddenFifths | Self::HiddenOctaves)
54    }
55}
56
57/// Every pair of parts, as part numbers, where a higher part sings below
58/// a lower one: music21's `checker.voiceCrossing`.
59///
60/// ```
61/// use music21::Pitch;
62/// use music21::figuredbass::checker::voice_crossings;
63///
64/// let pitches: Vec<Pitch> = ["C5", "G5", "E4"]
65///     .iter()
66///     .map(|name| Pitch::from_name(*name).unwrap())
67///     .collect();
68/// assert_eq!(voice_crossings(&pitches), [(1, 2)]);
69/// ```
70#[must_use]
71pub fn voice_crossings(possibility: &[Pitch]) -> Vec<(usize, usize)> {
72    let mut found = Vec::new();
73    for (higher_index, higher) in possibility.iter().enumerate() {
74        if is_rest(higher) {
75            continue;
76        }
77        for (lower_index, lower) in possibility.iter().enumerate().skip(higher_index + 1) {
78            if !is_rest(lower) && higher.ps() < lower.ps() {
79                found.push((higher_index + 1, lower_index + 1));
80            }
81        }
82    }
83    found
84}
85
86/// Whether two pitches stand `semitones` apart past whole octaves.
87fn apart_by(a: &Pitch, b: &Pitch, semitones: FloatType) -> bool {
88    (a.ps() - b.ps()).abs() % 12.0 == semitones
89}
90
91/// The pairs of parts, as part numbers, whose move from `a` to `b` stands
92/// at the rule's interval and so needs [`breaks_rule`] to decide it. For
93/// a hidden rule that is the outer parts or nothing.
94///
95/// # Errors
96///
97/// Two possibilities with different numbers of parts, or none.
98pub fn candidates(a: &[Pitch], b: &[Pitch], rule: ConsecutiveRule) -> Result<Vec<(usize, usize)>> {
99    if a.len() != b.len() {
100        return Err(Error::FiguredBass(format!(
101            "possibilities of {} and {} parts cannot be paired",
102            a.len(),
103            b.len()
104        )));
105    }
106    let semitones = rule.semitones();
107    if rule.is_hidden() {
108        let (Some(last_a), Some(last_b)) = (a.last(), b.last()) else {
109            return Err(Error::FiguredBass(
110                "a possibility with no parts has no outer parts".to_string(),
111            ));
112        };
113        let outer = [&a[0], &b[0], last_a, last_b];
114        if outer.iter().any(|pitch| is_rest(pitch)) || !apart_by(&b[0], last_b, semitones) {
115            return Ok(Vec::new());
116        }
117        return Ok(vec![(1, b.len())]);
118    }
119
120    let mut found = Vec::new();
121    for higher in 0..a.len() {
122        if is_rest(&a[higher]) || is_rest(&b[higher]) {
123            continue;
124        }
125        for lower in higher + 1..a.len() {
126            if is_rest(&a[lower]) || is_rest(&b[lower]) {
127                continue;
128            }
129            if apart_by(&a[higher], &a[lower], semitones)
130                && apart_by(&b[higher], &b[lower], semitones)
131            {
132                found.push((higher + 1, lower + 1));
133            }
134        }
135    }
136    Ok(found)
137}
138
139/// Whether the lower part moving from `lower.0` to `lower.1` against the
140/// higher moving from `higher.0` to `higher.1` breaks the rule, as
141/// music21's `VoiceLeadingQuartet` decides it.
142///
143/// # Errors
144///
145/// Pitches a quartet cannot be made of.
146pub fn breaks_rule(
147    lower: (&Pitch, &Pitch),
148    higher: (&Pitch, &Pitch),
149    rule: ConsecutiveRule,
150) -> Result<bool> {
151    let quartet = VoiceLeadingQuartet::new(
152        lower.0.clone(),
153        lower.1.clone(),
154        higher.0.clone(),
155        higher.1.clone(),
156    )?;
157    Ok(match rule {
158        ConsecutiveRule::ParallelFifths => quartet.parallel_fifth(),
159        ConsecutiveRule::ParallelOctaves => quartet.parallel_octave(),
160        ConsecutiveRule::HiddenFifths => quartet.hidden_fifth(),
161        ConsecutiveRule::HiddenOctaves => quartet.hidden_octave(),
162    })
163}
164
165/// Every pair of parts, as part numbers, that breaks the rule moving from
166/// `a` to `b`: music21's `checker.parallelFifths` and its three siblings.
167///
168/// ```
169/// use music21::Pitch;
170/// use music21::figuredbass::checker::{ConsecutiveRule, violations};
171///
172/// let pitches = |names: &[&str]| -> Vec<Pitch> {
173///     names.iter().map(|name| Pitch::from_name(*name).unwrap()).collect()
174/// };
175/// let a = pitches(&["B4", "G3", "C3"]);
176/// let b = pitches(&["A4", "A3", "D3"]);
177/// assert_eq!(violations(&a, &b, ConsecutiveRule::ParallelFifths)?, [(2, 3)]);
178/// # Ok::<(), music21::Error>(())
179/// ```
180///
181/// # Errors
182///
183/// Two possibilities with different numbers of parts, or none.
184pub fn violations(a: &[Pitch], b: &[Pitch], rule: ConsecutiveRule) -> Result<Vec<(usize, usize)>> {
185    let mut found = Vec::new();
186    for (higher, lower) in candidates(a, b, rule)? {
187        let lower_move = (&a[lower - 1], &b[lower - 1]);
188        let higher_move = (&a[higher - 1], &b[higher - 1]);
189        if breaks_rule(lower_move, higher_move, rule)? {
190            found.push((higher, lower));
191        }
192    }
193    Ok(found)
194}
195
196#[cfg(test)]
197mod tests {
198    use super::*;
199
200    fn pitches(names: &[&str]) -> Vec<Pitch> {
201        names
202            .iter()
203            .map(|name| Pitch::from_name(*name).unwrap())
204            .collect()
205    }
206
207    fn rest() -> Pitch {
208        let mut placeholder = Pitch::from_name("C4").unwrap();
209        placeholder.set_ps(REST_PS);
210        placeholder
211    }
212
213    #[test]
214    fn the_rules_name_music21s_parts() {
215        let a = pitches(&["C4", "G3", "C3"]);
216        let b = pitches(&["D4", "A3", "D3"]);
217        assert_eq!(
218            violations(&a, &b, ConsecutiveRule::ParallelOctaves).unwrap(),
219            [(1, 3)]
220        );
221        assert_eq!(
222            violations(&a, &b, ConsecutiveRule::ParallelFifths).unwrap(),
223            [(2, 3)]
224        );
225
226        let a = pitches(&["E5", "C3"]);
227        let b = pitches(&["A5", "D3"]);
228        assert_eq!(
229            violations(&a, &b, ConsecutiveRule::HiddenFifths).unwrap(),
230            [(1, 2)]
231        );
232        let b = pitches(&["A-5", "D3"]);
233        assert!(
234            violations(&a, &b, ConsecutiveRule::HiddenFifths)
235                .unwrap()
236                .is_empty()
237        );
238    }
239
240    #[test]
241    fn a_resting_part_breaks_no_rule() {
242        let crossed = vec![
243            pitches(&["C5"])[0].clone(),
244            rest(),
245            pitches(&["G5"])[0].clone(),
246        ];
247        assert_eq!(voice_crossings(&crossed), [(1, 3)]);
248
249        let a = vec![rest(), pitches(&["C3"])[0].clone()];
250        let b = pitches(&["A5", "D3"]);
251        assert!(
252            candidates(&a, &b, ConsecutiveRule::HiddenFifths)
253                .unwrap()
254                .is_empty()
255        );
256        assert!(candidates(&a, &pitches(&["A5"]), ConsecutiveRule::ParallelFifths).is_err());
257    }
258}