1use crate::defaults::FloatType;
14use crate::error::{Error, Result};
15use crate::pitch::Pitch;
16use crate::voiceleading::VoiceLeadingQuartet;
17
18pub const REST_PS: FloatType = 0.0;
21
22#[must_use]
24pub fn is_rest(pitch: &Pitch) -> bool {
25 pitch.ps() == REST_PS
26}
27
28#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
30pub enum ConsecutiveRule {
31 ParallelFifths,
33 ParallelOctaves,
35 HiddenFifths,
37 HiddenOctaves,
39}
40
41impl ConsecutiveRule {
42 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 fn is_hidden(self) -> bool {
53 matches!(self, Self::HiddenFifths | Self::HiddenOctaves)
54 }
55}
56
57#[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
86fn apart_by(a: &Pitch, b: &Pitch, semitones: FloatType) -> bool {
88 (a.ps() - b.ps()).abs() % 12.0 == semitones
89}
90
91pub 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
139pub 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
165pub 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}