1pub mod guitar;
3pub(crate) mod root;
4pub mod tables;
5
6use crate::common::numbertools::ORDINALS;
7use crate::defaults::{FloatType, IntegerType, UnsignedIntegerType};
8use crate::duration::Duration;
9use crate::error::Error;
10use crate::error::Result;
11use crate::interval::Interval;
12use crate::key::Key;
13use crate::key::keysignature::KeySignature;
14use crate::notation::{Beams, Lyric, Notehead, StemDirection, Tie};
15use crate::note::{IntoNote, Note};
16use crate::pitch::{Pitch, PitchClass, PitchClassSpecifier};
17use crate::volume::Volume;
18
19pub use guitar::{GuitarFingering, GuitarStringFingering, GuitarTuning, GuitarTuningString};
20
21use num::integer::{gcd, lcm};
22use std::fmt::{Display, Formatter};
23use std::ops::Index;
24use std::str::FromStr;
25use std::sync::LazyLock;
26
27mod names;
28mod notation;
29mod quality;
30mod resolution;
31mod setclass;
32
33pub use names::KnownChordType;
34pub use quality::TriadQuality;
35pub use resolution::ChordResolutionSuggestion;
36pub use setclass::{ChordTableAddress, format_vector_string};
37
38use quality::*;
39
40#[derive(Debug, Clone)]
41#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
42#[must_use]
48pub struct Chord {
49 notes: Vec<Note>,
50 duration: Option<Duration>,
51 #[cfg_attr(feature = "serde", serde(default))]
54 midi_tick_start: crate::display::Drawn<Option<u64>>,
55 #[cfg_attr(feature = "serde", serde(default))]
59 quantization_errors: crate::display::Drawn<(Option<FloatType>, Option<FloatType>)>,
60 #[cfg_attr(feature = "serde", serde(default))]
62 volume: Option<Volume>,
63 #[cfg_attr(feature = "serde", serde(default))]
65 color: Option<String>,
66 #[cfg_attr(feature = "serde", serde(default))]
70 notehead: Notehead,
71 #[cfg_attr(feature = "serde", serde(default))]
72 notehead_fill: Option<bool>,
73 #[cfg_attr(feature = "serde", serde(default))]
74 notehead_parenthesis: bool,
75 #[cfg_attr(feature = "serde", serde(default))]
76 stem_direction: StemDirection,
77 #[cfg_attr(feature = "serde", serde(default))]
79 beams: Beams,
80 #[cfg_attr(feature = "serde", serde(default))]
83 stored_instrument: Option<Box<crate::instrument::Instrument>>,
84 #[cfg_attr(feature = "serde", serde(default))]
88 root_override: Option<Pitch>,
89 #[cfg_attr(feature = "serde", serde(default))]
91 bass_override: Option<Pitch>,
92 #[cfg_attr(feature = "serde", serde(default))]
95 inversion_override: Option<u8>,
96 #[cfg_attr(feature = "serde", serde(default))]
99 expressions: Vec<crate::expressions::Expression>,
100 #[cfg_attr(feature = "serde", serde(default))]
102 articulations: Vec<crate::articulations::Articulation>,
103 #[cfg_attr(feature = "serde", serde(default))]
107 numeral: Option<Box<crate::roman::RomanNumeral>>,
108 #[cfg_attr(feature = "serde", serde(default))]
110 id: Option<String>,
111}
112
113use crate::interval::constants::PERFECT_FIFTH_UP as PERFECT_FIFTH;
114
115impl Index<usize> for Chord {
116 type Output = Note;
117
118 fn index(&self, index: usize) -> &Self::Output {
119 &self.notes[index]
120 }
121}
122
123impl IntoIterator for Chord {
124 type Item = Note;
125 type IntoIter = std::vec::IntoIter<Note>;
126
127 fn into_iter(self) -> Self::IntoIter {
128 self.notes.into_iter()
129 }
130}
131
132impl<'a> IntoIterator for &'a Chord {
133 type Item = &'a Note;
134 type IntoIter = std::slice::Iter<'a, Note>;
135
136 fn into_iter(self) -> Self::IntoIter {
137 self.notes.iter()
138 }
139}
140
141impl<'a> IntoIterator for &'a mut Chord {
142 type Item = &'a mut Note;
143 type IntoIter = std::slice::IterMut<'a, Note>;
144
145 fn into_iter(self) -> Self::IntoIter {
146 self.notes.iter_mut()
147 }
148}
149
150impl FromStr for Chord {
151 type Err = Error;
152
153 fn from_str(value: &str) -> Result<Self> {
154 Self::new(value)
155 }
156}
157
158impl TryFrom<&str> for Chord {
159 type Error = Error;
160
161 fn try_from(value: &str) -> Result<Self> {
162 Self::new(value)
163 }
164}
165
166impl TryFrom<String> for Chord {
167 type Error = Error;
168
169 fn try_from(value: String) -> Result<Self> {
170 Self::new(value)
171 }
172}
173
174impl TryFrom<&[Pitch]> for Chord {
175 type Error = Error;
176
177 fn try_from(value: &[Pitch]) -> Result<Self> {
178 Self::new(value)
179 }
180}
181
182impl TryFrom<&[Note]> for Chord {
183 type Error = Error;
184
185 fn try_from(value: &[Note]) -> Result<Self> {
186 Self::new(value)
187 }
188}
189
190impl TryFrom<&[IntegerType]> for Chord {
191 type Error = Error;
192
193 fn try_from(value: &[IntegerType]) -> Result<Self> {
194 Self::new(value)
195 }
196}
197
198impl TryFrom<&[&str]> for Chord {
199 type Error = Error;
200
201 fn try_from(value: &[&str]) -> Result<Self> {
202 Self::new(value)
203 }
204}
205
206impl TryFrom<&[String]> for Chord {
207 type Error = Error;
208
209 fn try_from(value: &[String]) -> Result<Self> {
210 Self::new(value)
211 }
212}
213
214impl Display for Chord {
215 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
216 write!(f, "{}", self.pitched_common_name())
217 }
218}
219
220impl Chord {
221 pub fn midi_tick_start(&self) -> Option<u64> {
224 self.midi_tick_start.0
225 }
226
227 pub fn set_midi_tick_start(&mut self, tick: Option<u64>) {
229 self.midi_tick_start.0 = tick;
230 }
231
232 pub fn quantization_errors(&self) -> (Option<FloatType>, Option<FloatType>) {
235 self.quantization_errors.0
236 }
237
238 pub fn set_quantization_errors(&mut self, errors: (Option<FloatType>, Option<FloatType>)) {
240 self.quantization_errors.0 = errors;
241 }
242
243 pub fn new<T>(notes: T) -> Result<Self>
248 where
249 T: IntoNotes,
250 {
251 Ok(Self {
252 notes: notes.try_into_notes()?.into_iter().collect(),
253 ..Self::empty()
254 })
255 }
256
257 pub fn empty() -> Self {
259 Self {
260 notes: Vec::new(),
261 duration: None,
262 midi_tick_start: crate::display::Drawn(None),
263 quantization_errors: crate::display::Drawn((None, None)),
264 volume: None,
265 color: None,
266 notehead: Notehead::default(),
267 notehead_fill: None,
268 notehead_parenthesis: false,
269 stem_direction: StemDirection::default(),
270 beams: Beams::default(),
271 stored_instrument: None,
272 root_override: None,
273 bass_override: None,
274 inversion_override: None,
275 expressions: Vec::new(),
276 articulations: Vec::new(),
277 numeral: None,
278 id: None,
279 }
280 }
281
282 pub fn id(&self) -> Option<&str> {
285 self.id.as_deref()
286 }
287
288 pub fn set_id(&mut self, id: Option<String>) {
290 self.id = id;
291 }
292
293 pub fn numeral(&self) -> Option<&crate::roman::RomanNumeral> {
296 self.numeral.as_deref()
297 }
298
299 pub fn set_numeral(&mut self, numeral: Option<crate::roman::RomanNumeral>) {
302 self.numeral = numeral.map(Box::new);
303 }
304
305 pub fn with_numeral(mut self, numeral: crate::roman::RomanNumeral) -> Self {
307 self.set_numeral(Some(numeral));
308 self
309 }
310
311 pub fn guitar_fingering(&self) -> Option<GuitarFingering> {
319 guitar::suggested_guitar_fingering(self)
320 }
321
322 pub fn guitar_fingering_with_tuning(&self, tuning: &GuitarTuning) -> Option<GuitarFingering> {
328 guitar::suggested_guitar_fingering_with_tuning(self, tuning)
329 }
330
331 pub fn pitch_classes(&self) -> Vec<u8> {
333 self.ordered_pitch_classes()
334 }
335
336 pub fn polyrhythm_components(&self) -> Vec<UnsignedIntegerType> {
343 let pitch_classes = self.ordered_pitch_classes();
344 if pitch_classes.is_empty() {
345 return vec![1];
346 }
347
348 let root_pc = self
349 .find_root_pitch()
350 .map(root::pitch_class)
351 .filter(|root_pc| pitch_classes.contains(root_pc))
352 .unwrap_or(pitch_classes[0]);
353 let mut offsets = pitch_classes
354 .iter()
355 .map(|pc| (*pc + 12 - root_pc) % 12)
356 .collect::<Vec<_>>();
357 offsets.sort_unstable();
358
359 let ratios = offsets
360 .into_iter()
361 .map(Self::just_ratio_for_semitone)
362 .collect::<Vec<_>>();
363 let common_denominator = ratios
364 .iter()
365 .fold(1, |acc, (_, denominator)| lcm(acc, *denominator));
366 let integers = ratios
367 .iter()
368 .map(|(numerator, denominator)| numerator * (common_denominator / denominator))
369 .collect::<Vec<_>>();
370 let divisor = integers.iter().copied().reduce(gcd).unwrap_or(1).max(1);
371
372 integers.into_iter().map(|value| value / divisor).collect()
373 }
374
375 pub fn polyrhythm_ratio_string(&self) -> String {
377 self.polyrhythm_components()
378 .into_iter()
379 .map(|component| component.to_string())
380 .collect::<Vec<_>>()
381 .join(":")
382 }
383
384 pub fn add<T>(&mut self, notes: T) -> Result<()>
388 where
389 T: IntoNotes,
390 {
391 self.notes.extend(notes.try_into_notes()?);
392 Ok(())
393 }
394
395 pub fn remove(&mut self, pitch: &Pitch) -> Result<()> {
398 let found = self.notes.iter().position(|note| ¬e.pitch == pitch);
399 match found {
400 Some(index) => {
401 let _ = self.notes.remove(index);
402 Ok(())
403 }
404 None => Err(Error::Chord("Chord.remove(x), x not in chord".to_string())),
405 }
406 }
407
408 pub fn remove_named(&mut self, name_with_octave: &str) -> Result<()> {
411 let found = self
412 .notes
413 .iter()
414 .position(|note| note.pitch.name_with_octave() == name_with_octave);
415 match found {
416 Some(index) => {
417 let _ = self.notes.remove(index);
418 Ok(())
419 }
420 None => Err(Error::Chord("Chord.remove(x), x not in chord".to_string())),
421 }
422 }
423
424 pub fn pitches(&self) -> Vec<Pitch> {
426 self.notes.iter().map(|note| note.pitch.clone()).collect()
427 }
428
429 pub fn iter_pitches(&self) -> impl Iterator<Item = &Pitch> + '_ {
435 self.notes.iter().map(|note| ¬e.pitch)
436 }
437
438 pub fn notes(&self) -> &[Note] {
440 &self.notes
441 }
442
443 pub fn notes_mut(&mut self) -> &mut [Note] {
447 &mut self.notes
448 }
449
450 pub fn len(&self) -> usize {
452 self.notes.len()
453 }
454
455 pub fn is_empty(&self) -> bool {
457 self.notes.is_empty()
458 }
459
460 pub fn note_for_pitch(&self, pitch: &Pitch) -> Option<&Note> {
463 self.notes.iter().find(|note| ¬e.pitch == pitch)
464 }
465
466 pub fn note_for_pitch_mut(&mut self, pitch: &Pitch) -> Option<&mut Note> {
468 self.notes.iter_mut().find(|note| ¬e.pitch == pitch)
469 }
470
471 pub fn duration(&self) -> Option<&Duration> {
473 self.duration.as_ref()
474 }
475
476 pub fn set_duration(&mut self, duration: Duration) {
478 self.duration = Some(duration);
479 }
480
481 pub fn with_duration(mut self, duration: Duration) -> Self {
483 self.set_duration(duration);
484 self
485 }
486
487 pub fn inversion(&self) -> Option<u8> {
494 if self.notes.is_empty() {
495 return None;
496 }
497 if let Some(fixed) = self.inversion_override {
498 return Some(fixed);
499 }
500 self.found_inversion()
501 }
502
503 pub fn found_inversion(&self) -> Option<u8> {
505 self.inversion_with_root(self.root()?)
506 }
507
508 pub fn overridden_inversion(&self) -> Option<u8> {
511 self.inversion_override
512 }
513
514 pub fn set_inversion_override(&mut self, inversion: Option<u8>) {
530 self.inversion_override = inversion;
531 }
532
533 pub(crate) fn inversion_with_root(&self, root: &Pitch) -> Option<u8> {
536 let bass_to_root = diatonic_steps_above(self.bass()?, root);
537 Some([0, 3, 6, 2, 5, 1, 4][usize::from(bass_to_root - 1)])
538 }
539
540 pub fn inversion_name(&self) -> Result<Option<IntegerType>> {
546 let Some(root) = self.root() else {
548 return Ok(None);
549 };
550 let Some(inversion) = self
551 .inversion_override
552 .or_else(|| self.inversion_with_root(root))
553 else {
554 return Ok(None);
555 };
556 self.inversion_name_from(root, IntegerType::from(inversion))
557 }
558
559 pub fn inversion_name_of(&self, inversion: IntegerType) -> Result<Option<IntegerType>> {
565 let Some(root) = self.root() else {
566 return Ok(None);
567 };
568 if inversion == -1 {
569 return Ok(None);
570 }
571 self.inversion_name_from(root, inversion)
572 }
573
574 fn inversion_name_from(
575 &self,
576 root: &Pitch,
577 inversion: IntegerType,
578 ) -> Result<Option<IntegerType>> {
579 let at = |names: &[IntegerType]| {
580 usize::try_from(inversion)
581 .ok()
582 .and_then(|index| names.get(index))
583 .copied()
584 };
585 if self.chord_step_from(7, root).is_some() {
587 return at(&[7, 65, 43, 42]).map(Some).ok_or_else(|| {
588 Error::Chord(format!("Not a normal inversion for a seventh: {inversion}"))
589 });
590 }
591 if self.is_triad_from(root) {
592 return at(&[53, 6, 64]).map(Some).ok_or_else(|| {
593 Error::Chord(format!("Not a normal inversion for a triad: {inversion}"))
594 });
595 }
596 Err(Error::Chord(
597 "Not a triad or Seventh, cannot determine inversion.".to_string(),
598 ))
599 }
600
601 pub fn simplify_enharmonics(&self, key_context: Option<KeySignature>) -> Result<Self> {
607 let mut chord = self.clone();
608 chord.simplify_enharmonics_in_place(key_context)?;
609 Ok(chord)
610 }
611
612 pub fn simplify_enharmonics_in_place(
614 &mut self,
615 key_context: Option<KeySignature>,
616 ) -> Result<()> {
617 match crate::pitch::simplify_multiple_enharmonics(&self.pitches(), None, key_context) {
618 Ok(pitches) => {
619 for (i, pitch) in pitches.iter().enumerate() {
620 if let Some(note) = self.notes.get_mut(i) {
621 note.pitch = pitch.clone();
622 }
623 }
624 Ok(())
625 }
626 Err(err) => Err(Error::Chord(format!(
627 "simplifying multiple enharmonics failed because of {err}"
628 ))),
629 }
630 }
631
632 pub fn root(&self) -> Option<&Pitch> {
634 self.root_override
635 .as_ref()
636 .or_else(|| self.find_root_pitch())
637 }
638
639 pub fn found_root(&self) -> Option<&Pitch> {
641 self.find_root_pitch()
642 }
643
644 pub fn set_root(&mut self, root: Option<Pitch>) {
648 self.root_override = root;
649 }
650
651 pub fn bass(&self) -> Option<&Pitch> {
654 self.bass_override.as_ref().or_else(|| self.bass_pitch())
655 }
656
657 pub fn found_bass(&self) -> Option<&Pitch> {
659 self.bass_pitch()
660 }
661
662 pub fn overridden_bass(&self) -> Option<&Pitch> {
665 self.bass_override.as_ref()
666 }
667
668 pub fn overridden_root(&self) -> Option<&Pitch> {
671 self.root_override.as_ref()
672 }
673
674 pub fn set_bass(&mut self, bass: Option<Pitch>) {
678 let Some(bass) = bass else {
679 self.bass_override = None;
680 return;
681 };
682 let known = self
683 .notes
684 .iter()
685 .any(|note| note.pitch.name_with_octave() == bass.name_with_octave());
686 if !known {
687 self.notes.insert(0, Note::from_pitch(bass.clone()));
688 }
689 self.bass_override = Some(bass);
690 }
691
692 pub fn set_inversion(&mut self, inversion: u8) -> Result<()> {
697 self.bass_override = None;
698 self.inversion_override = None;
699 let mut runs = self.notes.len() + 2;
700 while self.inversion() != Some(inversion) {
701 if runs == 0 {
702 return Err(Error::Chord(
703 "Could not invert chord: inversion may not exist".to_string(),
704 ));
705 }
706 runs -= 1;
707 let highest_ps = self
708 .notes
709 .iter()
710 .map(|note| note.pitch.ps())
711 .fold(FloatType::NEG_INFINITY, FloatType::max);
712 let Some(bass_name) = self.bass().map(Pitch::name_with_octave) else {
713 return Err(Error::Chord(
714 "Could not invert chord: inversion may not exist".to_string(),
715 ));
716 };
717 let Some(index) = self
718 .notes
719 .iter()
720 .position(|note| note.pitch.name_with_octave() == bass_name)
721 else {
722 return Err(Error::Chord(
723 "Could not invert chord: inversion may not exist".to_string(),
724 ));
725 };
726 while self.notes[index].pitch.ps() < highest_ps {
727 let octave = self.notes[index].pitch.implicit_octave();
728 self.notes[index].pitch.octave_setter(Some(octave + 1));
729 }
730 }
731 *self = self.sort_ascending();
732 Ok(())
733 }
734
735 pub fn closed_position(
740 &self,
741 force_octave: Option<IntegerType>,
742 leave_redundant_pitches: bool,
743 ) -> Self {
744 let mut chord = self.clone();
745 let Some(bass_index) = chord.bass_index() else {
746 return chord;
747 };
748 let implicit_octave = crate::defaults::PITCH_OCTAVE as IntegerType;
749 if let Some(force_octave) = force_octave {
750 let bass_octave = chord.notes[bass_index]
751 .pitch
752 .octave()
753 .unwrap_or(implicit_octave);
754 let shift = force_octave - bass_octave;
755 for note in &mut chord.notes {
756 let octave = note.pitch.octave().unwrap_or(implicit_octave);
757 note.pitch.octave_setter(Some(octave + shift));
758 }
759 }
760 let bass_ps = chord.notes[bass_index].pitch.ps();
761 let bass_number = root::diatonic_note_number(&chord.notes[bass_index].pitch);
762 for note in &mut chord.notes {
763 let mut octave = note.pitch.octave().unwrap_or(implicit_octave);
764 note.pitch.octave_setter(Some(octave));
765 while note.pitch.ps() >= bass_ps + 12.0 {
766 octave -= 1;
767 note.pitch.octave_setter(Some(octave));
768 }
769 if root::diatonic_note_number(¬e.pitch) < bass_number {
770 note.pitch.octave_setter(Some(octave + 1));
771 }
772 }
773 if !leave_redundant_pitches {
774 chord.retain_first_by(spelling_and_octave);
775 }
776 chord.sort_ascending_in_place();
777 chord
778 }
779
780 pub fn remove_redundant_pitches_reporting(&self) -> (Self, Vec<Pitch>) {
783 self.reduced_reporting(spelling_and_octave)
784 }
785
786 pub fn remove_redundant_pitch_names_reporting(&self) -> (Self, Vec<Pitch>) {
789 self.reduced_reporting(Pitch::name)
790 }
791
792 pub fn remove_redundant_pitch_classes_reporting(&self) -> (Self, Vec<Pitch>) {
795 self.reduced_reporting(root::pitch_class)
796 }
797
798 fn reduced_reporting<K: PartialEq>(&self, key: impl Fn(&Pitch) -> K) -> (Self, Vec<Pitch>) {
799 let mut kept = self.clone();
800 let mut seen: Vec<K> = Vec::with_capacity(self.notes.len());
801 let mut removed = Vec::new();
802 kept.notes.retain(|note| {
803 let candidate = key(¬e.pitch);
804 if seen.contains(&candidate) {
805 removed.push(note.pitch.clone());
806 false
807 } else {
808 seen.push(candidate);
809 true
810 }
811 });
812 (kept, removed)
813 }
814
815 pub fn remove_redundant_pitches(&self) -> Self {
820 let mut chord = self.clone();
821 chord.retain_first_by(spelling_and_octave);
822 chord
823 }
824
825 pub fn remove_redundant_pitch_names(&self) -> Self {
828 let mut chord = self.clone();
829 chord.retain_first_by(Pitch::name);
830 chord
831 }
832
833 pub fn remove_redundant_pitch_classes(&self) -> Self {
836 let mut chord = self.clone();
837 chord.retain_first_by(root::pitch_class);
838 chord
839 }
840
841 pub fn sort_ascending(&self) -> Self {
844 let mut chord = self.clone();
845 chord.sort_ascending_in_place();
846 chord
847 }
848
849 pub(crate) fn unique_pitch_name_count(&self) -> usize {
859 self.notes
860 .iter()
861 .enumerate()
862 .filter(|(index, note)| {
863 !self.notes[..*index]
864 .iter()
865 .any(|earlier| same_pitch_name(&earlier.pitch, ¬e.pitch))
866 })
867 .count()
868 }
869
870 fn bass_index(&self) -> Option<usize> {
874 let bass = self.bass_pitch()?;
875 self.notes
876 .iter()
877 .position(|note| std::ptr::eq(¬e.pitch, bass))
878 }
879
880 fn retain_first_by<K: PartialEq>(&mut self, key: impl Fn(&Pitch) -> K) {
881 let mut seen: Vec<K> = Vec::with_capacity(self.notes.len());
882 self.notes.retain(|note| {
883 let candidate = key(¬e.pitch);
884 if seen.contains(&candidate) {
885 false
886 } else {
887 seen.push(candidate);
888 true
889 }
890 });
891 }
892
893 fn sort_ascending_in_place(&mut self) {
894 let order = self.ascending_order();
895 self.notes = order
896 .iter()
897 .map(|&index| self.notes[index].clone())
898 .collect();
899 }
900
901 pub(crate) fn ascending_order(&self) -> Vec<usize> {
904 let mut order: Vec<usize> = (0..self.notes.len()).collect();
905 order.sort_by(|&left, &right| {
906 let (left, right) = (&self.notes[left].pitch, &self.notes[right].pitch);
907 root::diatonic_note_number(left)
908 .cmp(&root::diatonic_note_number(right))
909 .then_with(|| {
910 left.ps()
911 .partial_cmp(&right.ps())
912 .unwrap_or(std::cmp::Ordering::Equal)
913 })
914 });
915 order
916 }
917
918 pub fn transpose(&self, interval: &Interval) -> Result<Self> {
920 let mut chord = self.clone();
921 for note in &mut chord.notes {
922 note.pitch = interval.transpose_pitch(¬e.pitch)?;
923 }
924 if let Some(root) = &chord.root_override {
928 chord.root_override = Some(interval.transpose_pitch(root)?);
929 }
930 if let Some(bass) = &chord.bass_override {
931 chord.bass_override = Some(interval.transpose_pitch(bass)?);
932 }
933 if let Some(numeral) = &chord.numeral {
935 chord.numeral = Some(Box::new(numeral.transpose(interval)?));
936 }
937 Ok(chord)
938 }
939
940 pub fn scale_degrees(
945 &self,
946 scale: &crate::scale::Scale,
947 ) -> Result<Vec<(Option<usize>, Option<crate::pitch::Accidental>)>> {
948 self.pitch_refs()
949 .map(|pitch| match scale.degree_and_accidental_of(pitch) {
950 Ok((degree, accidental)) => Ok((Some(degree), accidental)),
951 Err(Error::Scale(_)) => Ok((None, None)),
952 Err(error) => Err(error),
953 })
954 .collect()
955 }
956
957 fn bass_pitch(&self) -> Option<&Pitch> {
958 root::bass_pitch(self.pitch_refs())
959 }
960
961 fn find_root_pitch(&self) -> Option<&Pitch> {
962 root::find_root_pitch(self.pitch_refs())
963 }
964
965 fn pitch_refs(&self) -> impl Iterator<Item = &Pitch> {
966 self.notes.iter().map(|note| ¬e.pitch)
967 }
968
969 fn just_ratio_for_semitone(offset: u8) -> (UnsignedIntegerType, UnsignedIntegerType) {
970 const RATIOS: [(UnsignedIntegerType, UnsignedIntegerType); 12] = [
971 (1, 1),
972 (16, 15),
973 (9, 8),
974 (6, 5),
975 (5, 4),
976 (4, 3),
977 (7, 5),
978 (3, 2),
979 (25, 16),
980 (5, 3),
981 (7, 4),
982 (15, 8),
983 ];
984 RATIOS[offset as usize % 12]
985 }
986}
987
988fn same_pitch_name(left: &Pitch, right: &Pitch) -> bool {
991 left.step() == right.step() && left.accidental().modifier() == right.accidental().modifier()
992}
993
994pub trait IntoNotes {
1001 const FROM_INTEGER_PITCHES: bool = false;
1003
1004 type Notes: IntoIterator<Item = Note>;
1006
1007 fn try_into_notes(self) -> Result<Self::Notes>;
1009}
1010
1011impl<T> IntoNotes for Option<T>
1012where
1013 T: IntoNotes,
1014{
1015 const FROM_INTEGER_PITCHES: bool = T::FROM_INTEGER_PITCHES;
1016
1017 type Notes = Vec<Note>;
1018
1019 fn try_into_notes(self) -> Result<Self::Notes> {
1020 match self {
1021 Some(notes) => Ok(notes.try_into_notes()?.into_iter().collect()),
1022 None => Ok(Vec::new()),
1023 }
1024 }
1025}
1026
1027impl<T> IntoNotes for Vec<T>
1028where
1029 T: IntoNote,
1030{
1031 const FROM_INTEGER_PITCHES: bool = T::FROM_INTEGER_PITCH;
1032
1033 type Notes = Vec<Note>;
1034
1035 fn try_into_notes(self) -> Result<Self::Notes> {
1036 let mut notes = self
1037 .into_iter()
1038 .map(IntoNote::try_into_note)
1039 .collect::<Result<Vec<_>>>()?;
1040 if Self::FROM_INTEGER_PITCHES {
1041 simplify_integer_notes(&mut notes)?;
1042 }
1043 Ok(notes)
1044 }
1045}
1046
1047fn spelling_and_octave(pitch: &Pitch) -> (String, crate::defaults::Octave) {
1052 (pitch.name(), pitch.octave())
1053}
1054
1055fn simplify_integer_notes(notes: &mut [Note]) -> Result<()> {
1056 if notes.is_empty() {
1057 return Ok(());
1058 }
1059
1060 let pitches = notes
1061 .iter()
1062 .map(|note| note.pitch.clone())
1063 .collect::<Vec<_>>();
1064 for (note, pitch) in notes
1065 .iter_mut()
1066 .zip(crate::pitch::simplify_multiple_enharmonics(
1067 &pitches, None, None,
1068 )?)
1069 {
1070 note.pitch = pitch;
1071 }
1072
1073 Ok(())
1074}
1075
1076impl IntoNotes for &[Pitch] {
1077 type Notes = Vec<Note>;
1078
1079 fn try_into_notes(self) -> Result<Self::Notes> {
1080 Ok(self.iter().cloned().map(Note::from_pitch).collect())
1081 }
1082}
1083
1084impl IntoNotes for &[Note] {
1085 type Notes = Vec<Note>;
1086
1087 fn try_into_notes(self) -> Result<Self::Notes> {
1088 Ok(self.to_vec())
1089 }
1090}
1091
1092impl IntoNotes for &[Chord] {
1093 type Notes = Vec<Note>;
1094
1095 fn try_into_notes(self) -> Result<Self::Notes> {
1096 Ok(self.iter().flat_map(|chord| chord.notes.clone()).collect())
1097 }
1098}
1099
1100impl IntoNotes for &[String] {
1101 type Notes = Vec<Note>;
1102
1103 fn try_into_notes(self) -> Result<Self::Notes> {
1104 self.iter()
1105 .map(|name| Note::from_name(name.as_str()))
1106 .collect::<Result<Vec<_>>>()
1107 }
1108}
1109
1110impl IntoNotes for String {
1111 type Notes = Vec<Note>;
1112
1113 fn try_into_notes(self) -> Result<Self::Notes> {
1114 self.as_str().try_into_notes()
1115 }
1116}
1117
1118impl IntoNotes for &[&str] {
1119 type Notes = Vec<Note>;
1120
1121 fn try_into_notes(self) -> Result<Self::Notes> {
1122 let mut vec = vec![];
1123 for str in self {
1124 vec.append(&mut str.try_into_notes()?);
1125 }
1126 Ok(vec)
1127 }
1128}
1129
1130impl IntoNotes for &str {
1131 type Notes = Vec<Note>;
1132
1133 fn try_into_notes(self) -> Result<Self::Notes> {
1134 if self.trim().is_empty() {
1135 Ok(Vec::new())
1136 } else if self.contains(char::is_whitespace) {
1137 self.split_whitespace()
1138 .collect::<Vec<&str>>()
1139 .try_into_notes()
1140 } else {
1141 Ok(vec![Note::from_name(self)?])
1142 }
1143 }
1144}
1145
1146impl IntoNotes for &[IntegerType] {
1147 const FROM_INTEGER_PITCHES: bool = true;
1148
1149 type Notes = Vec<Note>;
1150
1151 fn try_into_notes(self) -> Result<Self::Notes> {
1152 let mut notes = self
1153 .iter()
1154 .map(|number| Note::from_number(*number as FloatType))
1155 .collect::<Result<Vec<_>>>()?;
1156 simplify_integer_notes(&mut notes)?;
1157 Ok(notes)
1158 }
1159}
1160
1161impl Chord {
1162 pub fn inversion_text(&self) -> String {
1165 Self::inversion_text_of(self.inversion().map_or(-1, IntegerType::from))
1166 }
1167
1168 pub fn inversion_text_of(inversion: IntegerType) -> String {
1172 if inversion == 0 {
1173 return "Root Position".to_string();
1174 }
1175 match usize::try_from(inversion)
1176 .ok()
1177 .and_then(|index| ORDINALS.get(index))
1178 {
1179 Some(ordinal) => format!("{ordinal} Inversion"),
1180 None => "Unknown Position".to_string(),
1181 }
1182 }
1183
1184 pub fn semi_closed_position(
1188 &self,
1189 force_octave: Option<IntegerType>,
1190 leave_redundant_pitches: bool,
1191 ) -> Self {
1192 let mut chord = self.closed_position(force_octave, leave_redundant_pitches);
1193 let implicit_octave = crate::defaults::PITCH_OCTAVE as IntegerType;
1194 let mut remaining: Vec<usize> = (0..chord.notes.len()).collect();
1195 while !remaining.is_empty() {
1196 let mut used_steps = Vec::new();
1197 let mut still_clashing = Vec::new();
1198 for index in remaining {
1199 let pitch = &mut chord.notes[index].pitch;
1200 let step = root::diatonic_note_number(pitch).rem_euclid(7);
1201 if used_steps.contains(&step) {
1202 let octave = pitch.octave().unwrap_or(implicit_octave) + 1;
1203 pitch.octave_setter(Some(octave));
1204 still_clashing.push(index);
1205 } else {
1206 used_steps.push(step);
1207 }
1208 }
1209 remaining = still_clashing;
1210 }
1211 chord.sort_ascending_in_place();
1212 chord
1213 }
1214
1215 pub fn sort_chromatic_ascending(&self) -> Self {
1218 let mut chord = self.clone();
1219 chord.notes.sort_by(|left, right| {
1220 left.pitch
1221 .ps()
1222 .partial_cmp(&right.pitch.ps())
1223 .unwrap_or(std::cmp::Ordering::Equal)
1224 });
1225 chord
1226 }
1227
1228 pub fn sort_diatonic_ascending(&self) -> Self {
1232 self.sort_ascending()
1233 }
1234
1235 pub fn diatonic_ascending_order(&self) -> Vec<usize> {
1246 self.ascending_order()
1247 }
1248
1249 pub fn is_sorted_diatonic_ascending(&self) -> bool {
1266 self.notes.windows(2).all(|pair| {
1267 let (left, right) = (&pair[0].pitch, &pair[1].pitch);
1268 let step = root::diatonic_note_number(left).cmp(&root::diatonic_note_number(right));
1269 step.then(left.ps().total_cmp(&right.ps())).is_le()
1270 })
1271 }
1272
1273 pub fn sort_frequency_ascending(&self) -> Self {
1275 let mut chord = self.clone();
1276 chord.notes.sort_by(|left, right| {
1277 left.pitch
1278 .frequency_hz()
1279 .partial_cmp(&right.pitch.frequency_hz())
1280 .unwrap_or(std::cmp::Ordering::Equal)
1281 });
1282 chord
1283 }
1284
1285 pub fn pitch_names(&self) -> Vec<String> {
1287 self.notes.iter().map(|note| note.pitch.name()).collect()
1288 }
1289
1290 pub fn note_pitch_classes(&self) -> Vec<u8> {
1294 self.notes
1295 .iter()
1296 .map(|note| root::pitch_class(¬e.pitch))
1297 .collect()
1298 }
1299}
1300
1301#[cfg(test)]
1302mod tests {
1303
1304 #[test]
1305 fn a_chord_indexes_and_iterates_over_its_notes() {
1306 let chord = Chord::new("C4 E4 G4").unwrap();
1307
1308 assert_eq!(chord.len(), 3);
1309 assert!(!chord.is_empty());
1310 assert_eq!(chord[1].pitch.name_with_octave(), "E4");
1311
1312 let borrowed: Vec<String> = (&chord)
1313 .into_iter()
1314 .map(|note| note.pitch.name_with_octave())
1315 .collect();
1316 assert_eq!(borrowed, vec!["C4", "E4", "G4"]);
1317 assert_eq!(chord.into_iter().count(), 3);
1318 }
1319
1320 #[test]
1321 fn every_chord_step_is_its_first_pitch_in_order() {
1322 let chord = Chord::new("C4 E4 G4 B4 C5 D5").unwrap();
1325 let root = chord.root().unwrap().clone();
1326 assert_eq!(
1327 chord.all_chord_steps(&root),
1328 [(1, 0), (3, 1), (5, 2), (7, 3), (2, 5)]
1329 );
1330 }
1331
1332 #[test]
1333 fn forte_and_interval_vector_constructors_match_music21() {
1334 let names = |chord: &Chord| chord.pitch_names();
1335 assert_eq!(
1336 names(&Chord::from_forte_class("3-11").unwrap()),
1337 ["C", "Eb", "G"]
1338 );
1339 assert_eq!(
1340 names(&Chord::from_forte_class("3-11B").unwrap()),
1341 ["C", "E", "G"]
1342 );
1343 assert_eq!(
1344 names(&Chord::from_forte_class("3-11a").unwrap()),
1345 ["C", "Eb", "G"]
1346 );
1347 assert_eq!(
1348 names(&Chord::from_forte_address(4, 27, Some(-1)).unwrap()),
1349 ["C", "Eb", "Gb", "Ab"]
1350 );
1351 assert_eq!(
1352 Chord::from_forte_class("3-11").unwrap().prime_form_string(),
1353 "<037>"
1354 );
1355 assert!(Chord::from_forte_class("311").is_err());
1356 assert!(Chord::from_forte_class("3-99").is_err());
1357 assert_eq!(
1358 Chord::from_forte_class("4-z15")
1359 .unwrap()
1360 .forte_class()
1361 .as_deref(),
1362 Some("4-15A")
1363 );
1364 assert_eq!(
1365 Chord::from_forte_class("4-Z15").unwrap().pitch_names(),
1366 Chord::from_forte_class("4-15").unwrap().pitch_names()
1367 );
1368
1369 assert_eq!(
1370 names(&Chord::from_interval_vector(&[0, 0, 1, 1, 1, 0], false).unwrap()),
1371 ["C", "Eb", "G"]
1372 );
1373 assert_eq!(
1374 names(&Chord::from_interval_vector(&[1, 1, 1, 1, 1, 1], false).unwrap()),
1375 ["C", "C#", "E", "F#"]
1376 );
1377 assert_eq!(
1378 names(&Chord::from_interval_vector(&[1, 1, 1, 1, 1, 1], true).unwrap()),
1379 ["C", "Db", "Eb", "G"]
1380 );
1381 assert!(Chord::from_interval_vector(&[9, 9, 9, 9, 9, 9], false).is_none());
1382 }
1383
1384 #[test]
1385 fn geometric_normal_form_matches_music21() {
1386 let cases: [(&str, &[u8]); 9] = [
1387 ("C4 E4 G4", &[0, 3, 8]),
1388 ("E4 G4 C5", &[0, 3, 8]),
1389 ("C4 D-4 E4 G-4", &[0, 1, 4, 6]),
1390 ("C4 E-4 G-4 A4", &[0, 3, 6, 9]),
1391 ("C4", &[0]),
1392 ("C4 C5", &[0]),
1393 ("B3 C4 E4", &[0, 1, 5]),
1394 ("F#4 A4 C5 E-5", &[0, 3, 6, 9]),
1395 ("C4 D4 E4 F4 G4 A4 B4", &[0, 1, 3, 5, 6, 8, 10]),
1396 ];
1397 for (notes, expected) in cases {
1398 assert_eq!(
1399 Chord::new(notes).unwrap().geometric_normal_form(),
1400 expected,
1401 "{notes}"
1402 );
1403 }
1404 assert!(Chord::empty().geometric_normal_form().is_empty());
1405 }
1406
1407 #[test]
1408 #[allow(clippy::type_complexity)]
1409 fn set_class_strings_and_flags_match_music21() {
1410 let cases: [(&str, &str, &str, u8, &str, usize, bool, bool, &str, bool); 14] = [
1411 (
1412 "C4 E4 G4",
1413 "<001110>",
1414 "<047>",
1415 11,
1416 "3-11B",
1417 3,
1418 true,
1419 false,
1420 "Root Position",
1421 false,
1422 ),
1423 (
1424 "C4 E-4 G-4 B--4",
1425 "<004002>",
1426 "<0369>",
1427 28,
1428 "4-28",
1429 4,
1430 false,
1431 false,
1432 "Root Position",
1433 true,
1434 ),
1435 (
1436 "C4 E4 G4 B-4",
1437 "<012111>",
1438 "<47A0>",
1439 27,
1440 "4-27B",
1441 4,
1442 true,
1443 false,
1444 "Root Position",
1445 false,
1446 ),
1447 (
1448 "C3 G3 E4 C5",
1449 "<001110>",
1450 "<047>",
1451 11,
1452 "3-11B",
1453 4,
1454 true,
1455 false,
1456 "Root Position",
1457 false,
1458 ),
1459 (
1460 "E-4 G4 C5",
1461 "<001110>",
1462 "<037>",
1463 11,
1464 "3-11A",
1465 3,
1466 false,
1467 false,
1468 "First Inversion",
1469 false,
1470 ),
1471 (
1472 "C4 D-4 E4 G-4",
1473 "<111111>",
1474 "<0146>",
1475 15,
1476 "4-15A",
1477 4,
1478 false,
1479 true,
1480 "Root Position",
1481 false,
1482 ),
1483 (
1484 "C4 D-4 E-4 G4",
1485 "<111111>",
1486 "<0137>",
1487 29,
1488 "4-29A",
1489 4,
1490 false,
1491 true,
1492 "Root Position",
1493 false,
1494 ),
1495 (
1496 "C4 C#4 D4 E4 F#4 G4 A4 B4",
1497 "<465472>",
1498 "<B0124679>",
1499 23,
1500 "8-23",
1501 8,
1502 false,
1503 false,
1504 "Root Position",
1505 false,
1506 ),
1507 (
1508 "G3 C4 E4",
1509 "<001110>",
1510 "<047>",
1511 11,
1512 "3-11B",
1513 3,
1514 true,
1515 false,
1516 "Second Inversion",
1517 false,
1518 ),
1519 (
1520 "B#3 C4 E4 G-4 F#4",
1521 "<010101>",
1522 "<046>",
1523 8,
1524 "3-8B",
1525 5,
1526 true,
1527 false,
1528 "Third Inversion",
1529 false,
1530 ),
1531 (
1532 "C4 E-4 G-4 A4",
1533 "<004002>",
1534 "<0369>",
1535 28,
1536 "4-28",
1537 4,
1538 false,
1539 false,
1540 "First Inversion",
1541 true,
1542 ),
1543 (
1544 "C4",
1545 "<000000>",
1546 "<0>",
1547 1,
1548 "1-1",
1549 1,
1550 false,
1551 false,
1552 "Root Position",
1553 false,
1554 ),
1555 (
1556 "C4 F4 G4",
1557 "<010020>",
1558 "<570>",
1559 9,
1560 "3-9",
1561 3,
1562 false,
1563 false,
1564 "Second Inversion",
1565 false,
1566 ),
1567 (
1568 "D4 F4 A-4 C-5",
1569 "<004002>",
1570 "<258B>",
1571 28,
1572 "4-28",
1573 4,
1574 false,
1575 false,
1576 "Root Position",
1577 true,
1578 ),
1579 ];
1580 for (
1581 notes,
1582 vector,
1583 normal_order,
1584 forte_number,
1585 forte_tn,
1586 cardinality,
1587 prime_inversion,
1588 z_relation,
1589 inversion_text,
1590 false_diminished,
1591 ) in cases
1592 {
1593 let chord = Chord::new(notes).unwrap();
1594 assert_eq!(chord.interval_vector_string(), vector, "{notes}");
1595 assert_eq!(chord.normal_order_string(), normal_order, "{notes}");
1596 assert_eq!(chord.forte_class_number(), Some(forte_number), "{notes}");
1597 assert_eq!(chord.forte_class_tn().as_deref(), Some(forte_tn), "{notes}");
1598 assert_eq!(chord.multiset_cardinality(), cardinality, "{notes}");
1599 assert_eq!(chord.is_prime_form_inversion(), prime_inversion, "{notes}");
1600 assert_eq!(chord.has_z_relation(), z_relation, "{notes}");
1601 assert_eq!(chord.inversion_text(), inversion_text, "{notes}");
1602 assert_eq!(
1603 chord.is_false_diminished_seventh(),
1604 false_diminished,
1605 "{notes}"
1606 );
1607 }
1608
1609 let empty = Chord::empty();
1610 assert_eq!(empty.interval_vector_string(), "<000000>");
1611 assert_eq!(empty.normal_order_string(), "<>");
1612 assert_eq!(empty.forte_class_number(), None);
1613 assert_eq!(empty.multiset_cardinality(), 0);
1614 assert!(!empty.has_z_relation());
1615 assert_eq!(empty.inversion_text(), "Unknown Position");
1616 }
1617
1618 #[test]
1619 fn z_relations_pair_up_like_music21() {
1620 let z15 = Chord::new("C4 D-4 E4 G-4").unwrap();
1621 let z29 = Chord::new("C4 D-4 E-4 G4").unwrap();
1622 let triad = Chord::new("C E G").unwrap();
1623 assert!(z15.are_z_relations(&z29));
1624 assert!(z29.are_z_relations(&z15));
1625 assert!(!z15.are_z_relations(&triad));
1626 assert!(!triad.are_z_relations(&z15));
1627 }
1628
1629 #[test]
1630 fn interval_from_chord_step_matches_music21() {
1631 let cases: [(&str, Option<&str>, Option<&str>); 9] = [
1632 ("C4 E4 G4", Some("M3"), Some("P5")),
1633 ("C4 E-4 G-4 B--4", Some("m3"), Some("d5")),
1634 ("C3 G3 E4 C5", Some("M10"), Some("P5")),
1635 ("E-4 G4 C5", Some("M6"), Some("P4")),
1636 ("C4 D-4 E4 G-4", Some("M3"), Some("d5")),
1637 ("C4 E-4 G-4 A4", Some("M6"), Some("A4")),
1638 ("A2 C#4 E4 G4", Some("M10"), Some("P12")),
1639 ("C4", None, None),
1640 ("C4 F4 G4", None, Some("P4")),
1641 ];
1642 for (notes, third, fifth) in cases {
1643 let chord = Chord::new(notes).unwrap();
1644 let name = |interval: Option<Interval>| interval.map(|interval| interval.short_name());
1645 assert_eq!(
1646 name(chord.interval_from_chord_step(3)).as_deref(),
1647 third,
1648 "{notes}"
1649 );
1650 assert_eq!(
1651 name(chord.interval_from_chord_step(5)).as_deref(),
1652 fifth,
1653 "{notes}"
1654 );
1655 }
1656 assert!(Chord::empty().interval_from_chord_step(3).is_none());
1657 }
1658
1659 fn octave_names(chord: &Chord) -> Vec<String> {
1660 chord
1661 .pitches()
1662 .iter()
1663 .map(Pitch::name_with_octave)
1664 .collect()
1665 }
1666
1667 #[test]
1668 fn semi_closed_position_matches_music21() {
1669 let cases: [(&str, &[&str], &[&str]); 7] = [
1670 ("C4 E4 G4", &["C4", "E4", "G4"], &["C3", "E3", "G3"]),
1671 ("C3 G3 E4 C5", &["C3", "E3", "G3"], &["C3", "E3", "G3"]),
1672 ("E-4 G4 C5", &["Eb4", "G4", "C5"], &["Eb3", "G3", "C4"]),
1673 (
1674 "C4 C#4 D4 E4 F#4 G4 A4 B4",
1675 &["C4", "D4", "E4", "F#4", "G4", "A4", "B4", "C#5"],
1676 &["C3", "D3", "E3", "F#3", "G3", "A3", "B3", "C#4"],
1677 ),
1678 ("C4 E4 G4 C5 E5", &["C4", "E4", "G4"], &["C3", "E3", "G3"]),
1679 (
1680 "B#3 C4 E4 G-4 F#4",
1681 &["B#3", "C4", "E4", "F#4", "Gb4"],
1682 &["B#3", "C4", "E4", "F#4", "Gb4"],
1683 ),
1684 (
1685 "E4 G#4 B4 D5 F5",
1686 &["E4", "F4", "G#4", "B4", "D5"],
1687 &["E3", "F3", "G#3", "B3", "D4"],
1688 ),
1689 ];
1690 for (notes, expected, expected_forced) in cases {
1691 let chord = Chord::new(notes).unwrap();
1692 assert_eq!(
1693 octave_names(&chord.semi_closed_position(None, false)),
1694 expected,
1695 "{notes}"
1696 );
1697 assert_eq!(
1698 octave_names(&chord.semi_closed_position(Some(3), false)),
1699 expected_forced,
1700 "{notes} forced to octave 3"
1701 );
1702 }
1703 }
1704
1705 #[test]
1706 fn sort_variants_match_music21() {
1707 let chord = Chord::new("B#3 C4 E4 G-4 F#4").unwrap();
1708 assert_eq!(
1709 octave_names(&chord.sort_chromatic_ascending()),
1710 ["B#3", "C4", "E4", "Gb4", "F#4"]
1711 );
1712 assert_eq!(
1713 octave_names(&chord.sort_diatonic_ascending()),
1714 ["B#3", "C4", "E4", "F#4", "Gb4"]
1715 );
1716 assert_eq!(
1717 octave_names(&chord.sort_frequency_ascending()),
1718 ["B#3", "C4", "E4", "Gb4", "F#4"]
1719 );
1720 let spread = Chord::new("C5 G3 E4 C3").unwrap();
1721 assert_eq!(
1722 octave_names(&spread.sort_chromatic_ascending()),
1723 ["C3", "G3", "E4", "C5"]
1724 );
1725 assert_eq!(
1726 octave_names(&spread.sort_frequency_ascending()),
1727 ["C3", "G3", "E4", "C5"]
1728 );
1729 assert_eq!(chord.pitch_names(), ["B#", "C", "E", "Gb", "F#"]);
1730 }
1731
1732 #[test]
1734 fn a_chord_says_whether_it_is_already_sorted() {
1735 for (notes, sorted) in [
1736 ("C4 E4 G4", true),
1737 ("E4 C4 G4", false),
1738 ("C4 D#4 E-4", true),
1741 ("C4 E-4 D#4", false),
1742 ("B#3 C4", true),
1743 ("C4 B#3", false),
1744 ("C4 C4", true),
1745 ("C4", true),
1746 ] {
1747 let chord = Chord::new(notes).unwrap();
1748 assert_eq!(
1749 chord.is_sorted_diatonic_ascending(),
1750 sorted,
1751 "{notes} sorted?"
1752 );
1753 assert!(
1755 chord
1756 .sort_diatonic_ascending()
1757 .is_sorted_diatonic_ascending()
1758 );
1759 }
1760 }
1761
1762 #[test]
1763 fn full_name_matches_music21() {
1764 let chord = Chord::new("C4 E-4 G-4 B--4").unwrap();
1767 assert_eq!(
1768 chord.full_name(),
1769 "Chord {C in octave 4 | E-flat in octave 4 | G-flat in octave 4 | B-double-flat in octave 4} Quarter"
1770 );
1771 let quarter = chord.clone().with_duration(Duration::quarter());
1772 assert_eq!(
1773 quarter.full_name(),
1774 "Chord {C in octave 4 | E-flat in octave 4 | G-flat in octave 4 | B-double-flat in octave 4} Quarter"
1775 );
1776 let dotted = Chord::new("C4 E4 G4")
1777 .unwrap()
1778 .with_duration(Duration::new(1.5).unwrap());
1779 assert_eq!(
1780 dotted.full_name(),
1781 "Chord {C in octave 4 | E in octave 4 | G in octave 4} Dotted Quarter"
1782 );
1783 }
1784 use crate::{Duration, GuitarTuning, Interval, Key, Pitch, chord::Chord, chord::TriadQuality};
1785
1786 #[test]
1787 fn a_chord_carries_notation_for_all_its_notes() {
1788 use crate::notation::{Beams, Notehead, StemDirection};
1789
1790 let mut chord = Chord::new("C4 E4 G4").unwrap();
1791 assert_eq!(chord.notehead(), Notehead::Normal);
1792 chord.set_notehead(Notehead::Diamond);
1793 assert_eq!(chord.notehead(), Notehead::Diamond);
1794 assert_eq!(chord.notehead_fill(), None);
1795 chord.set_notehead_fill(Some(false));
1796 assert_eq!(chord.notehead_fill(), Some(false));
1797 assert!(!chord.notehead_parenthesis());
1798 chord.set_notehead_parenthesis(true);
1799 assert!(chord.notehead_parenthesis());
1800 chord.set_stem_direction(StemDirection::Down);
1801 assert_eq!(chord.stem_direction(), StemDirection::Down);
1802 assert!(chord.beams().is_empty());
1803 let mut beams = Beams::default();
1804 beams
1805 .fill(crate::duration::DurationType::Eighth, None)
1806 .unwrap();
1807 chord.set_beams(beams.clone());
1808 assert_eq!(chord.beams(), &beams);
1809 }
1810
1811 #[test]
1812 fn notes_are_added_and_removed_as_music21_adds_and_removes_them() {
1813 let mut chord = Chord::new("C4 E4 G4").unwrap();
1814 chord.add("B-4").unwrap();
1815 assert_eq!(chord.pitch_names(), ["C", "E", "G", "Bb"]);
1816 chord.remove(&Pitch::from_name("E4").unwrap()).unwrap();
1817 assert!(chord.remove(&Pitch::from_name("E4").unwrap()).is_err());
1818 chord.remove_named("G4").unwrap();
1819 assert!(chord.remove_named("G4").is_err());
1820 assert_eq!(chord.pitch_names(), ["C", "Bb"]);
1821 assert_eq!(chord.note_pitch_classes(), [0, 10]);
1822 assert_eq!(
1823 Chord::new("E4 C4 G4 C5").unwrap().note_pitch_classes(),
1824 [4, 0, 7, 0]
1825 );
1826 }
1827
1828 #[test]
1829 fn an_overridden_bass_or_root_is_kept_apart_from_the_inferred_one() {
1830 let mut chord = Chord::new("C4 E4 G4").unwrap();
1831 let e = Pitch::from_name("E4").unwrap();
1832 assert_eq!(chord.overridden_bass(), None);
1833 assert_eq!(chord.found_bass().map(Pitch::name), Some("C".to_string()));
1834 chord.set_bass(Some(e.clone()));
1835 assert_eq!(chord.overridden_bass(), Some(&e));
1836 assert_eq!(chord.bass().map(Pitch::name), Some("E".to_string()));
1837 assert_eq!(chord.found_bass().map(Pitch::name), Some("C".to_string()));
1838 chord.set_bass(None);
1839 assert_eq!(chord.overridden_bass(), None);
1840 chord.set_bass(Some(Pitch::from_name("A3").unwrap()));
1842 assert_eq!(chord.pitch_names(), ["A", "C", "E", "G"]);
1843
1844 let mut chord = Chord::new("C4 E4 G4").unwrap();
1845 assert_eq!(chord.overridden_root(), None);
1846 chord.set_root(Some(e.clone()));
1847 assert_eq!(chord.overridden_root(), Some(&e));
1848 assert_eq!(chord.root().map(Pitch::name), Some("E".to_string()));
1849 assert_eq!(chord.found_root().map(Pitch::name), Some("C".to_string()));
1850 }
1851
1852 #[test]
1853 fn set_inversion_raises_the_bass_until_the_chord_stands_in_it() {
1854 let mut chord = Chord::new("C4 E4 G4").unwrap();
1855 chord.set_inversion(1).unwrap();
1856 assert_eq!(chord.inversion(), Some(1));
1857 assert_eq!(
1858 chord
1859 .pitches()
1860 .iter()
1861 .map(Pitch::name_with_octave)
1862 .collect::<Vec<_>>(),
1863 ["E4", "G4", "C5"]
1864 );
1865 chord.set_inversion(0).unwrap();
1866 assert_eq!(chord.bass().map(Pitch::name), Some("C".to_string()));
1867 assert!(chord.set_inversion(5).is_err());
1868 }
1869
1870 #[test]
1871 fn a_fixed_inversion_wins_until_it_is_cleared() {
1872 let mut chord = Chord::new("C4 E4 G4").unwrap();
1873 chord.set_inversion_override(Some(2));
1874 assert_eq!(chord.inversion(), Some(2));
1875 assert_eq!(chord.overridden_inversion(), Some(2));
1876 assert_eq!(chord.found_inversion(), Some(0));
1877 assert_eq!(chord.inversion_name().unwrap(), Some(64));
1878 assert_eq!(chord.inversion_text(), "Second Inversion");
1879
1880 assert_eq!(chord.clone().inversion(), Some(2));
1882 let up = Interval::from_name("M2").unwrap();
1883 assert_eq!(chord.transpose(&up).unwrap().inversion(), Some(2));
1884
1885 chord.set_inversion_override(None);
1886 assert_eq!(chord.inversion(), Some(0));
1887 assert_eq!(Chord::empty().inversion(), None);
1888 }
1889
1890 #[test]
1891 fn a_fixed_inversion_past_any_ordinal_is_an_unknown_position() {
1892 let mut chord = Chord::new("C4 E4 G4").unwrap();
1893 chord.set_inversion_override(Some(200));
1894 assert_eq!(chord.inversion_text(), "Unknown Position");
1895 assert!(chord.inversion_name().is_err());
1896 }
1897
1898 #[test]
1899 fn moving_a_chord_to_an_inversion_forgets_a_fixed_one() {
1900 let mut chord = Chord::new("C4 E4 G4").unwrap();
1901 chord.set_inversion_override(Some(2));
1902 chord.set_inversion(1).unwrap();
1903 assert_eq!(chord.overridden_inversion(), None);
1904 assert_eq!(chord.bass().map(Pitch::name), Some("E".to_string()));
1905 }
1906
1907 #[test]
1908 fn chord_steps_can_be_measured_from_a_root_the_caller_names() {
1909 let chord = Chord::new("E4 G4 C5").unwrap();
1910 let c = Pitch::from_name("C4").unwrap();
1911 let g = Pitch::from_name("G4").unwrap();
1912 assert_eq!(chord.inversion_from_root(&c), Some(1));
1913 assert_eq!(chord.inversion_from_root(&g), Some(6));
1915 assert_eq!(
1916 chord.chord_step_with_root(3, &c).map(Pitch::name),
1917 Some("E".to_string())
1918 );
1919 assert_eq!(chord.chord_step_with_root(3, &g), None);
1920 assert_eq!(chord.semitones_from_chord_step_with_root(5, &c), Some(7));
1921 assert_eq!(chord.semitones_from_chord_step_with_root(3, &g), None);
1922 }
1923
1924 #[test]
1925 fn the_reductions_report_what_they_dropped() {
1926 let names = |pitches: Vec<Pitch>| -> Vec<String> {
1927 pitches.iter().map(Pitch::name_with_octave).collect()
1928 };
1929 let (kept, dropped) = Chord::new("C4 E4 G4 C4")
1930 .unwrap()
1931 .remove_redundant_pitches_reporting();
1932 assert_eq!(kept.pitch_names(), ["C", "E", "G"]);
1933 assert_eq!(names(dropped), ["C4"]);
1934 let (kept, dropped) = Chord::new("C4 E4 G4 C5")
1935 .unwrap()
1936 .remove_redundant_pitch_names_reporting();
1937 assert_eq!(kept.pitch_names(), ["C", "E", "G"]);
1938 assert_eq!(names(dropped), ["C5"]);
1939 let (kept, dropped) = Chord::new("C4 E4 G4 B#4")
1940 .unwrap()
1941 .remove_redundant_pitch_classes_reporting();
1942 assert_eq!(kept.pitch_names(), ["C", "E", "G"]);
1943 assert_eq!(names(dropped), ["B#4"]);
1944 }
1945
1946 #[test]
1947 fn pitches_that_only_print_alike_are_not_redundant() {
1948 let mut low_b: Pitch = "B".parse().unwrap();
1949 low_b.octave_setter(Some(-1));
1950 let mut b_flat: Pitch = "Bb".parse().unwrap();
1951 b_flat.octave_setter(Some(1));
1952 assert_eq!(low_b.name_with_octave(), "B-1");
1954 assert_eq!(b_flat.name_with_octave(), "Bb1");
1955 let chord = Chord::new(vec![low_b, b_flat]).unwrap();
1956 let (kept, dropped) = chord.remove_redundant_pitches_reporting();
1957 assert_eq!(kept.notes.len(), 2);
1958 assert!(dropped.is_empty());
1959 assert_eq!(chord.remove_redundant_pitches().notes.len(), 2);
1960
1961 let chord = Chord::new("C C4").unwrap();
1962 assert_eq!(chord.remove_redundant_pitches().notes.len(), 2);
1963 assert_eq!(
1964 Chord::new("C4 C4")
1965 .unwrap()
1966 .remove_redundant_pitches()
1967 .notes
1968 .len(),
1969 1
1970 );
1971 }
1972
1973 #[test]
1974 fn the_chord_table_address_is_a_record_and_an_empty_chord_has_one() {
1975 let address = Chord::new("C E G").unwrap().chord_tables_address_entry();
1976 assert_eq!(address.cardinality, 3);
1977 assert_eq!(address.forte_class, 11);
1978 assert_eq!(address.inversion, -1);
1979 assert_eq!(address.pitch_class_original, 0);
1980 let empty = Chord::new("").unwrap().chord_tables_address_entry();
1981 assert_eq!(
1982 (
1983 empty.cardinality,
1984 empty.forte_class,
1985 empty.inversion,
1986 empty.pitch_class_original
1987 ),
1988 (0, 0, 0, 0)
1989 );
1990 assert_eq!(super::format_vector_string(&[0, 0, 1, 1, 1, 0]), "<001110>");
1991 }
1992
1993 #[test]
1994 fn a_chord_is_built_from_any_of_the_inputs_try_from_accepts() {
1995 use crate::note::Note;
1996
1997 let names = |chord: Chord| chord.pitch_names();
1998 assert_eq!(names(Chord::try_from("C E G").unwrap()), ["C", "E", "G"]);
1999 assert_eq!(
2000 names(Chord::try_from("C E G".to_string()).unwrap()),
2001 ["C", "E", "G"]
2002 );
2003 let pitches = [
2004 Pitch::from_name("C4").unwrap(),
2005 Pitch::from_name("E4").unwrap(),
2006 ];
2007 assert_eq!(names(Chord::try_from(&pitches[..]).unwrap()), ["C", "E"]);
2008 let notes = [Note::from_pitch(pitches[0].clone())];
2009 assert_eq!(names(Chord::try_from(¬es[..]).unwrap()), ["C"]);
2010 assert_eq!(names(Chord::try_from(&[60, 64][..]).unwrap()), ["C", "E"]);
2011 assert_eq!(names(Chord::try_from(&["C", "G"][..]).unwrap()), ["C", "G"]);
2012 let owned = ["D".to_string(), "A".to_string()];
2013 assert_eq!(names(Chord::try_from(&owned[..]).unwrap()), ["D", "A"]);
2014 }
2015
2016 #[test]
2017 fn set_duration_applies_to_non_empty_chords() {
2018 for input in ["", "C", "C E G", "C E G B-"] {
2020 let mut chord = Chord::new(input).unwrap();
2021 chord.set_duration(Duration::whole());
2022 assert_eq!(
2023 chord.duration().map(Duration::quarter_length),
2024 Some(4.0),
2025 "set_duration on {input:?}"
2026 );
2027 }
2028 }
2029
2030 struct PredicateCase {
2031 notes: &'static str,
2032 quality: TriadQuality,
2033 flags: [bool; 14],
2034 third: Option<&'static str>,
2035 fifth: Option<&'static str>,
2036 seventh: Option<&'static str>,
2037 enharmonic: bool,
2038 repeated_third: bool,
2039 third_semitones: Option<u8>,
2040 }
2041
2042 #[test]
2043 fn triad_and_seventh_predicates_match_music21() {
2044 use TriadQuality::*;
2045 let t = true;
2046 let f = false;
2047 let cases = [
2048 PredicateCase {
2049 notes: "C E G",
2050 quality: Major,
2051 flags: [t, t, f, f, f, f, f, f, f, t, f, f, t, f],
2052 third: Some("E"),
2053 fifth: Some("G"),
2054 seventh: None,
2055 enharmonic: f,
2056 repeated_third: f,
2057 third_semitones: Some(4),
2058 },
2059 PredicateCase {
2060 notes: "C E- G",
2061 quality: Minor,
2062 flags: [t, f, t, f, f, f, f, f, f, t, f, f, t, f],
2063 third: Some("Eb"),
2064 fifth: Some("G"),
2065 seventh: None,
2066 enharmonic: f,
2067 repeated_third: f,
2068 third_semitones: Some(3),
2069 },
2070 PredicateCase {
2071 notes: "C E- G-",
2072 quality: Diminished,
2073 flags: [t, f, f, t, f, f, f, f, f, f, f, f, t, f],
2074 third: Some("Eb"),
2075 fifth: Some("Gb"),
2076 seventh: None,
2077 enharmonic: f,
2078 repeated_third: f,
2079 third_semitones: Some(3),
2080 },
2081 PredicateCase {
2082 notes: "C E G#",
2083 quality: Augmented,
2084 flags: [t, f, f, f, t, f, f, f, f, f, f, f, t, f],
2085 third: Some("E"),
2086 fifth: Some("G#"),
2087 seventh: None,
2088 enharmonic: f,
2089 repeated_third: f,
2090 third_semitones: Some(4),
2091 },
2092 PredicateCase {
2093 notes: "C4 E4 G4 B-4",
2094 quality: Major,
2095 flags: [f, f, f, f, f, t, t, f, f, f, f, f, t, t],
2096 third: Some("E4"),
2097 fifth: Some("G4"),
2098 seventh: Some("Bb4"),
2099 enharmonic: f,
2100 repeated_third: f,
2101 third_semitones: Some(4),
2102 },
2103 PredicateCase {
2104 notes: "C E- G- B--",
2105 quality: Diminished,
2106 flags: [f, f, f, f, f, t, f, f, t, f, f, f, t, t],
2107 third: Some("Eb"),
2108 fifth: Some("Gb"),
2109 seventh: Some("Bbb"),
2110 enharmonic: f,
2111 repeated_third: f,
2112 third_semitones: Some(3),
2113 },
2114 PredicateCase {
2115 notes: "C E- G- B-",
2116 quality: Diminished,
2117 flags: [f, f, f, f, f, t, f, t, f, f, f, f, t, t],
2118 third: Some("Eb"),
2119 fifth: Some("Gb"),
2120 seventh: Some("Bb"),
2121 enharmonic: f,
2122 repeated_third: f,
2123 third_semitones: Some(3),
2124 },
2125 PredicateCase {
2126 notes: "C E G B",
2127 quality: Major,
2128 flags: [f, f, f, f, f, t, f, f, f, f, f, f, t, t],
2129 third: Some("E"),
2130 fifth: Some("G"),
2131 seventh: Some("B"),
2132 enharmonic: f,
2133 repeated_third: f,
2134 third_semitones: Some(4),
2135 },
2136 PredicateCase {
2137 notes: "E G C",
2138 quality: Major,
2139 flags: [t, t, f, f, f, f, f, f, f, t, f, f, t, f],
2140 third: Some("E"),
2141 fifth: Some("G"),
2142 seventh: None,
2143 enharmonic: f,
2144 repeated_third: f,
2145 third_semitones: Some(4),
2146 },
2147 PredicateCase {
2148 notes: "G C E",
2149 quality: Major,
2150 flags: [t, t, f, f, f, f, f, f, f, t, f, f, t, f],
2151 third: Some("E"),
2152 fifth: Some("G"),
2153 seventh: None,
2154 enharmonic: f,
2155 repeated_third: f,
2156 third_semitones: Some(4),
2157 },
2158 PredicateCase {
2159 notes: "C E",
2160 quality: Major,
2161 flags: [f, f, f, f, f, f, f, f, f, t, t, f, f, f],
2162 third: Some("E"),
2163 fifth: None,
2164 seventh: None,
2165 enharmonic: f,
2166 repeated_third: f,
2167 third_semitones: Some(4),
2168 },
2169 PredicateCase {
2170 notes: "C E-",
2171 quality: Minor,
2172 flags: [f, f, f, f, f, f, f, f, f, t, f, t, f, f],
2173 third: Some("Eb"),
2174 fifth: None,
2175 seventh: None,
2176 enharmonic: f,
2177 repeated_third: f,
2178 third_semitones: Some(3),
2179 },
2180 PredicateCase {
2181 notes: "C G",
2182 quality: Other,
2183 flags: [f, f, f, f, f, f, f, f, f, t, f, f, f, f],
2184 third: None,
2185 fifth: Some("G"),
2186 seventh: None,
2187 enharmonic: f,
2188 repeated_third: f,
2189 third_semitones: None,
2190 },
2191 PredicateCase {
2192 notes: "C F",
2193 quality: Other,
2194 flags: [f, f, f, f, f, f, f, f, f, f, f, f, f, f],
2195 third: None,
2196 fifth: Some("C"),
2197 seventh: None,
2198 enharmonic: f,
2199 repeated_third: f,
2200 third_semitones: None,
2201 },
2202 PredicateCase {
2203 notes: "C4 F4",
2204 quality: Other,
2205 flags: [f, f, f, f, f, f, f, f, f, f, f, f, f, f],
2206 third: None,
2207 fifth: Some("C4"),
2208 seventh: None,
2209 enharmonic: f,
2210 repeated_third: f,
2211 third_semitones: None,
2212 },
2213 PredicateCase {
2214 notes: "C E G C5",
2215 quality: Major,
2216 flags: [t, t, f, f, f, f, f, f, f, t, f, f, t, f],
2217 third: Some("E"),
2218 fifth: Some("G"),
2219 seventh: None,
2220 enharmonic: f,
2221 repeated_third: f,
2222 third_semitones: Some(4),
2223 },
2224 PredicateCase {
2225 notes: "C E E- G",
2226 quality: Other,
2227 flags: [f, f, f, f, f, f, f, f, f, f, f, f, t, f],
2228 third: Some("E"),
2229 fifth: Some("G"),
2230 seventh: None,
2231 enharmonic: f,
2232 repeated_third: t,
2233 third_semitones: Some(4),
2234 },
2235 PredicateCase {
2236 notes: "B# E G",
2237 quality: Other,
2238 flags: [t, f, f, f, f, f, f, f, f, f, f, f, t, f],
2239 third: Some("G"),
2240 fifth: Some("B#"),
2241 seventh: None,
2242 enharmonic: f,
2243 repeated_third: f,
2244 third_semitones: Some(3),
2245 },
2246 PredicateCase {
2247 notes: "C F# G",
2248 quality: Other,
2249 flags: [f, f, f, f, f, f, f, f, f, f, f, f, f, f],
2250 third: None,
2251 fifth: Some("C"),
2252 seventh: None,
2253 enharmonic: f,
2254 repeated_third: f,
2255 third_semitones: None,
2256 },
2257 PredicateCase {
2258 notes: "C E G B- D",
2259 quality: Major,
2260 flags: [f, f, f, f, f, f, f, f, f, f, f, f, t, t],
2261 third: Some("E"),
2262 fifth: Some("G"),
2263 seventh: Some("Bb"),
2264 enharmonic: f,
2265 repeated_third: f,
2266 third_semitones: Some(4),
2267 },
2268 PredicateCase {
2269 notes: "C",
2270 quality: Other,
2271 flags: [f, f, f, f, f, f, f, f, f, t, f, f, f, f],
2272 third: None,
2273 fifth: None,
2274 seventh: None,
2275 enharmonic: f,
2276 repeated_third: f,
2277 third_semitones: None,
2278 },
2279 PredicateCase {
2280 notes: "E-4 G4 B-4",
2281 quality: Major,
2282 flags: [t, t, f, f, f, f, f, f, f, t, f, f, t, f],
2283 third: Some("G4"),
2284 fifth: Some("Bb4"),
2285 seventh: None,
2286 enharmonic: f,
2287 repeated_third: f,
2288 third_semitones: Some(4),
2289 },
2290 PredicateCase {
2291 notes: "C#4 E4 G4",
2292 quality: Diminished,
2293 flags: [t, f, f, t, f, f, f, f, f, f, f, f, t, f],
2294 third: Some("E4"),
2295 fifth: Some("G4"),
2296 seventh: None,
2297 enharmonic: f,
2298 repeated_third: f,
2299 third_semitones: Some(3),
2300 },
2301 PredicateCase {
2302 notes: "C4 E4 G4 E5",
2303 quality: Major,
2304 flags: [t, t, f, f, f, f, f, f, f, t, f, f, t, f],
2305 third: Some("E4"),
2306 fifth: Some("G4"),
2307 seventh: None,
2308 enharmonic: f,
2309 repeated_third: f,
2310 third_semitones: Some(4),
2311 },
2312 PredicateCase {
2313 notes: "C#4 D-4 E4",
2314 quality: Minor,
2315 flags: [f, f, f, f, f, f, f, f, f, f, f, t, f, f],
2316 third: Some("E4"),
2317 fifth: None,
2318 seventh: None,
2319 enharmonic: t,
2320 repeated_third: f,
2321 third_semitones: Some(3),
2322 },
2323 ];
2324 for case in cases {
2325 let chord = Chord::new(case.notes).unwrap();
2326 let notes = case.notes;
2327 let name = |pitch: Option<&Pitch>| pitch.map(Pitch::name_with_octave);
2328 assert_eq!(chord.quality(), case.quality, "{notes} quality");
2329 let actual = [
2330 chord.is_triad(),
2331 chord.is_major_triad(),
2332 chord.is_minor_triad(),
2333 chord.is_diminished_triad(),
2334 chord.is_augmented_triad(),
2335 chord.is_seventh(),
2336 chord.is_dominant_seventh(),
2337 chord.is_half_diminished_seventh(),
2338 chord.is_diminished_seventh(),
2339 chord.is_consonant(),
2340 chord.is_incomplete_major_triad(),
2341 chord.is_incomplete_minor_triad(),
2342 chord.contains_triad(),
2343 chord.contains_seventh(),
2344 ];
2345 assert_eq!(actual, case.flags, "{notes} predicates");
2346 assert_eq!(name(chord.third()).as_deref(), case.third, "{notes} third");
2347 assert_eq!(name(chord.fifth()).as_deref(), case.fifth, "{notes} fifth");
2348 assert_eq!(
2349 name(chord.seventh()).as_deref(),
2350 case.seventh,
2351 "{notes} seventh"
2352 );
2353 assert_eq!(
2354 chord.has_any_enharmonic_spelled_pitches(),
2355 case.enharmonic,
2356 "{notes} enharmonic"
2357 );
2358 assert_eq!(
2359 chord.has_repeated_chord_step(3),
2360 case.repeated_third,
2361 "{notes} repeated third"
2362 );
2363 assert_eq!(
2364 chord.semitones_from_chord_step(3),
2365 case.third_semitones,
2366 "{notes} third semitones"
2367 );
2368 }
2369
2370 let empty = Chord::empty();
2371 assert_eq!(empty.quality(), TriadQuality::Other);
2372 assert!(!empty.is_triad());
2373 assert!(!empty.is_consonant());
2374 assert!(empty.third().is_none());
2375 assert!(!empty.contains_triad());
2376 assert_eq!(TriadQuality::Diminished.to_string(), "diminished");
2377 }
2378
2379 #[test]
2380 fn consonance_of_dyads_follows_closed_position() {
2381 assert!(Chord::new("C4 C5 E5").unwrap().is_consonant());
2382 assert!(!Chord::new("C4 F4 C5").unwrap().is_consonant());
2383 assert!(Chord::new("F4 C5").unwrap().is_consonant());
2384 assert!(!Chord::new("C4 G3").unwrap().is_consonant());
2385 }
2386
2387 #[test]
2388 fn closed_position_matches_music21() {
2389 let names = |chord: Chord| {
2390 chord
2391 .pitches()
2392 .iter()
2393 .map(Pitch::name_with_octave)
2394 .collect::<Vec<_>>()
2395 };
2396 let cases = [
2397 ("C#4 G5 E6", None, vec!["C#4", "E4", "G4"]),
2398 ("C#4 G5 E6", Some(2), vec!["C#2", "E2", "G2"]),
2399 ("C#4 G5 E6", Some(6), vec!["C#6", "E6", "G6"]),
2400 ("C#4 F4 C5 F5", None, vec!["C#4", "F4", "C5"]),
2401 ("A B", None, vec!["A4", "B4"]),
2402 ("C4 B#7", None, vec!["C4", "B#4"]),
2403 ("E4 C5 G5", None, vec!["E4", "G4", "C5"]),
2404 (
2405 "C3 C#3 E-3 E3 E#3 G3",
2406 None,
2407 vec!["C3", "C#3", "Eb3", "E3", "E#3", "G3"],
2408 ),
2409 ("G4 C4 E4", Some(5), vec!["C5", "E5", "G5"]),
2410 ("C4 E4 G4 C5 E5", None, vec!["C4", "E4", "G4"]),
2411 ("C#4 D-4 E4", None, vec!["C#4", "Db4", "E4"]),
2412 ("E#4 F-4", None, vec!["E#4", "Fb4"]),
2415 ("C6 B#5", None, vec!["B#5", "C6"]),
2416 (
2417 "A-6 E-2 D#2 E#3 A#5",
2418 None,
2419 vec!["D#2", "Eb2", "E#2", "Ab2", "A#2"],
2420 ),
2421 ];
2422 for (notes, force_octave, expected) in cases {
2423 let chord = Chord::new(notes).unwrap();
2424 assert_eq!(
2425 names(chord.closed_position(force_octave, false)),
2426 expected,
2427 "{notes}"
2428 );
2429 }
2430 assert!(
2431 Chord::empty()
2432 .closed_position(None, false)
2433 .notes()
2434 .is_empty()
2435 );
2436 assert_eq!(
2437 names(
2438 Chord::new("C4 E4 C4 E5")
2439 .unwrap()
2440 .remove_redundant_pitches()
2441 ),
2442 vec!["C4", "E4", "E5"]
2443 );
2444 assert_eq!(
2445 names(
2446 Chord::new("C4 E4 C5 E5")
2447 .unwrap()
2448 .remove_redundant_pitch_names()
2449 ),
2450 vec!["C4", "E4"]
2451 );
2452 assert_eq!(
2453 names(
2454 Chord::new("C#4 D-4 E4")
2455 .unwrap()
2456 .remove_redundant_pitch_classes()
2457 ),
2458 vec!["C#4", "E4"]
2459 );
2460 assert_eq!(
2461 names(Chord::new("G-4 F##4 E4").unwrap().sort_ascending()),
2462 vec!["E4", "F##4", "Gb4"]
2463 );
2464 }
2465
2466 #[test]
2467 fn inversions_match_music21() {
2468 let cases = [
2469 ("C E G", 0, "C", "C"),
2470 ("E G C", 0, "C", "C"),
2471 ("G C E", 0, "C", "C"),
2472 ("C4 E4 G4 Bb4", 0, "C4", "C4"),
2473 ("E4 G4 Bb4 C5", 1, "C5", "E4"),
2474 ("B-3 C4 E4 G4", 3, "C4", "Bb3"),
2475 ("G3 C4 E4 Bb4", 2, "C4", "G3"),
2476 ("A-4 C5 F#5", 1, "F#5", "Ab4"),
2477 ("C5 F#5 A-5", 2, "F#5", "C5"),
2478 ("F#4 A-4 C5", 0, "F#4", "F#4"),
2479 ("C F G", 2, "F", "C"),
2480 ("C4 G4 E5", 0, "C4", "C4"),
2481 ("C", 0, "C", "C"),
2482 ("G C", 0, "C", "C"),
2483 ("E C", 0, "C", "C"),
2484 ("F A C E", 2, "F", "C"),
2485 ("E4 C5 G5", 1, "C5", "E4"),
2486 ("C E G A", 1, "A", "C"),
2487 ("C F# G", 2, "F#", "C"),
2488 ("D4 F#4 A4 C5 E5", 0, "D4", "D4"),
2489 ("A-3 C4 Eb4 F#4", 1, "F#4", "Ab3"),
2490 ("C4 A-4 E-5 F#5", 2, "F#5", "C4"),
2491 ("E3 G3 B-3 D-4", 0, "E3", "E3"),
2492 ];
2493 for (notes, inversion, root, bass) in cases {
2494 let chord = Chord::new(notes).unwrap();
2495 assert_eq!(chord.inversion(), Some(inversion), "{notes} inversion");
2496 assert_eq!(
2497 chord.root().map(Pitch::name_with_octave).as_deref(),
2498 Some(root),
2499 "{notes} root"
2500 );
2501 assert_eq!(
2502 chord.bass().map(Pitch::name_with_octave).as_deref(),
2503 Some(bass),
2504 "{notes} bass"
2505 );
2506 }
2507 assert_eq!(Chord::empty().inversion(), None);
2508 assert_eq!(
2509 Chord::new("B#3 C4 E4")
2510 .unwrap()
2511 .bass()
2512 .unwrap()
2513 .name_with_octave(),
2514 "B#3"
2515 );
2516 }
2517
2518 #[test]
2519 fn augmented_sixths_and_set_class_helpers_match_music21() {
2520 struct Case {
2521 notes: &'static str,
2522 flags: [bool; 11],
2523 prime_form: &'static str,
2524 forte_tni: &'static str,
2525 cardinality: usize,
2526 ordered: &'static str,
2527 }
2528 let t = true;
2529 let f = false;
2530 let cases = [
2531 Case {
2532 notes: "A-4 C5 F#5",
2533 flags: [t, t, f, f, f, t, t, f, f, f, f],
2534 prime_form: "<026>",
2535 forte_tni: "3-8",
2536 cardinality: 3,
2537 ordered: "<068>",
2538 },
2539 Case {
2540 notes: "A-4 C5 D5 F#5",
2541 flags: [t, f, t, f, f, t, f, f, t, f, f],
2542 prime_form: "<0268>",
2543 forte_tni: "4-25",
2544 cardinality: 4,
2545 ordered: "<0268>",
2546 },
2547 Case {
2548 notes: "A-4 C5 E-5 F#5",
2549 flags: [t, f, f, t, f, t, f, f, f, f, f],
2550 prime_form: "<0258>",
2551 forte_tni: "4-27",
2552 cardinality: 4,
2553 ordered: "<0368>",
2554 },
2555 Case {
2556 notes: "A-4 C5 D#5 F#5",
2557 flags: [t, f, f, f, t, t, f, f, f, f, f],
2558 prime_form: "<0258>",
2559 forte_tni: "4-27",
2560 cardinality: 4,
2561 ordered: "<0368>",
2562 },
2563 Case {
2564 notes: "C4 E4 G4",
2565 flags: [f, f, f, f, f, f, f, f, f, t, t],
2566 prime_form: "<037>",
2567 forte_tni: "3-11",
2568 cardinality: 3,
2569 ordered: "<047>",
2570 },
2571 Case {
2572 notes: "F#4 A-4 C5",
2573 flags: [f, f, f, f, f, t, t, f, f, f, f],
2574 prime_form: "<026>",
2575 forte_tni: "3-8",
2576 cardinality: 3,
2577 ordered: "<068>",
2578 },
2579 Case {
2580 notes: "C5 F#5 A-5",
2581 flags: [f, f, f, f, f, t, t, f, f, f, f],
2582 prime_form: "<026>",
2583 forte_tni: "3-8",
2584 cardinality: 3,
2585 ordered: "<068>",
2586 },
2587 Case {
2588 notes: "A-4 F#5 C6",
2589 flags: [t, t, f, f, f, t, t, f, f, f, f],
2590 prime_form: "<026>",
2591 forte_tni: "3-8",
2592 cardinality: 3,
2593 ordered: "<068>",
2594 },
2595 Case {
2596 notes: "A-4 C5 E-5 F#5 A-5",
2597 flags: [t, f, f, t, f, t, f, f, f, f, f],
2598 prime_form: "<0258>",
2599 forte_tni: "4-27",
2600 cardinality: 4,
2601 ordered: "<0368>",
2602 },
2603 Case {
2604 notes: "C E G B- D",
2605 flags: [f, f, f, f, f, f, f, t, f, f, f],
2606 prime_form: "<02469>",
2607 forte_tni: "5-34",
2608 cardinality: 5,
2609 ordered: "<0247A>",
2610 },
2611 Case {
2612 notes: "C E G B D F",
2613 flags: [f, f, f, f, f, f, f, f, f, f, f],
2614 prime_form: "<013568>",
2615 forte_tni: "6-25",
2616 cardinality: 6,
2617 ordered: "<02457B>",
2618 },
2619 Case {
2620 notes: "C E G#",
2621 flags: [f, f, f, f, f, f, f, f, t, f, f],
2622 prime_form: "<048>",
2623 forte_tni: "3-12",
2624 cardinality: 3,
2625 ordered: "<048>",
2626 },
2627 Case {
2628 notes: "C E- G- B--",
2629 flags: [f, f, f, f, f, f, f, f, t, f, f],
2630 prime_form: "<0369>",
2631 forte_tni: "4-28",
2632 cardinality: 4,
2633 ordered: "<0369>",
2634 },
2635 Case {
2636 notes: "C D E F# G# A#",
2637 flags: [f, f, f, f, f, f, f, f, t, f, f],
2638 prime_form: "<02468A>",
2639 forte_tni: "6-35",
2640 cardinality: 6,
2641 ordered: "<02468A>",
2642 },
2643 Case {
2644 notes: "C C# D D# E F F# G G# A A# B",
2645 flags: [f, f, f, f, f, f, f, f, t, f, f],
2646 prime_form: "<0123456789AB>",
2647 forte_tni: "12-1",
2648 cardinality: 12,
2649 ordered: "<0123456789AB>",
2650 },
2651 Case {
2652 notes: "C",
2653 flags: [f, f, f, f, f, f, f, f, f, f, f],
2654 prime_form: "<0>",
2655 forte_tni: "1-1",
2656 cardinality: 1,
2657 ordered: "<0>",
2658 },
2659 Case {
2660 notes: "B- D F A-",
2661 flags: [f, f, f, f, f, f, f, f, f, t, f],
2662 prime_form: "<0258>",
2663 forte_tni: "4-27",
2664 cardinality: 4,
2665 ordered: "<258A>",
2666 },
2667 Case {
2668 notes: "C F#",
2669 flags: [f, f, f, f, f, f, f, f, t, f, f],
2670 prime_form: "<06>",
2671 forte_tni: "2-6",
2672 cardinality: 2,
2673 ordered: "<06>",
2674 },
2675 ];
2676 for case in cases {
2677 let chord = Chord::new(case.notes).unwrap();
2678 let notes = case.notes;
2679 let actual = [
2680 chord.is_augmented_sixth(false),
2681 chord.is_italian_augmented_sixth(false, false),
2682 chord.is_french_augmented_sixth(false),
2683 chord.is_german_augmented_sixth(false),
2684 chord.is_swiss_augmented_sixth(false),
2685 chord.is_augmented_sixth(true),
2686 chord.is_italian_augmented_sixth(true, false),
2687 chord.is_ninth(),
2688 chord.is_transpositionally_symmetrical(false),
2689 chord.can_be_dominant_v(),
2690 chord.can_be_tonic(),
2691 ];
2692 assert_eq!(actual, case.flags, "{notes}");
2693 assert_eq!(
2694 chord.prime_form_string(),
2695 case.prime_form,
2696 "{notes} prime form"
2697 );
2698 assert_eq!(
2699 chord.forte_class_tni().as_deref(),
2700 Some(case.forte_tni),
2701 "{notes} forte tni"
2702 );
2703 assert_eq!(chord.pitch_class_cardinality(), case.cardinality, "{notes}");
2704 assert_eq!(
2705 chord.ordered_pitch_classes_string(),
2706 case.ordered,
2707 "{notes}"
2708 );
2709 }
2710
2711 assert!(
2712 Chord::new("C")
2713 .unwrap()
2714 .is_transpositionally_symmetrical(true)
2715 );
2716 assert!(
2717 !Chord::new("C D-")
2718 .unwrap()
2719 .is_transpositionally_symmetrical(false)
2720 );
2721 assert!(
2722 Chord::new("A-4 C5 D5 F#5")
2723 .unwrap()
2724 .is_transpositionally_symmetrical(false)
2725 );
2726 assert!(
2727 !Chord::new("A-4 C5 D5 F#5")
2728 .unwrap()
2729 .is_transpositionally_symmetrical(true)
2730 );
2731 assert!(
2732 Chord::new("C C# D D# E F F# G G# A A# B")
2733 .unwrap()
2734 .has_any_repeated_diatonic_note()
2735 );
2736 assert!(
2737 !Chord::new("C E G")
2738 .unwrap()
2739 .has_any_repeated_diatonic_note()
2740 );
2741
2742 let empty = Chord::empty();
2743 assert!(empty.is_transpositionally_symmetrical(false));
2744 assert!(empty.prime_form().is_empty());
2745 assert_eq!(empty.prime_form_string(), "<>");
2746 assert_eq!(empty.forte_class_tni(), None);
2747 assert_eq!(empty.pitch_class_cardinality(), 0);
2748 assert_eq!(empty.ordered_pitch_classes_string(), "<>");
2749 }
2750
2751 #[test]
2752 fn transpose_moves_every_note() {
2753 let names = |chord: Chord| {
2754 chord
2755 .pitches()
2756 .iter()
2757 .map(Pitch::name_with_octave)
2758 .collect::<Vec<_>>()
2759 };
2760 let chord = Chord::new("C4 E4 G4").unwrap();
2761 let up = |name: &str| {
2762 chord
2763 .transpose(&Interval::from_name(name).unwrap())
2764 .unwrap()
2765 };
2766 assert_eq!(names(up("M2")), vec!["D4", "F#4", "A4"]);
2767 assert_eq!(names(up("-m3")), vec!["A3", "C#4", "E4"]);
2768 assert_eq!(
2769 names(
2770 chord
2771 .transpose(&Interval::from_semitones(3).unwrap())
2772 .unwrap()
2773 ),
2774 vec!["Eb4", "G4", "Bb4"]
2775 );
2776 let bare = Chord::new("C E G").unwrap();
2777 assert_eq!(
2778 names(bare.transpose(&Interval::from_name("P5").unwrap()).unwrap()),
2779 vec!["G", "B", "D"]
2780 );
2781 }
2782
2783 #[test]
2784 fn scale_degrees_match_music21() {
2785 let cases = [
2786 (
2787 "C",
2788 "C E G",
2789 vec![(Some(1), None), (Some(3), None), (Some(5), None)],
2790 ),
2791 (
2792 "C",
2793 "C E- G",
2794 vec![(Some(1), None), (Some(3), Some("flat")), (Some(5), None)],
2795 ),
2796 (
2797 "F",
2798 "F A C E",
2799 vec![
2800 (Some(1), None),
2801 (Some(3), None),
2802 (Some(5), None),
2803 (Some(7), None),
2804 ],
2805 ),
2806 (
2807 "a",
2808 "G# B D",
2809 vec![(Some(7), Some("sharp")), (Some(2), None), (Some(4), None)],
2810 ),
2811 (
2812 "B-",
2813 "E- G B-",
2814 vec![(Some(4), None), (Some(6), None), (Some(1), None)],
2815 ),
2816 (
2817 "D",
2818 "C# E G B-",
2819 vec![
2820 (Some(7), None),
2821 (Some(2), None),
2822 (Some(4), None),
2823 (Some(6), Some("flat")),
2824 ],
2825 ),
2826 (
2827 "C",
2828 "C E G B- D-",
2829 vec![
2830 (Some(1), None),
2831 (Some(3), None),
2832 (Some(5), None),
2833 (Some(7), Some("flat")),
2834 (Some(2), Some("flat")),
2835 ],
2836 ),
2837 ];
2838 for (key, notes, expected) in cases {
2839 let scale = Key::from_tonic(key).unwrap().scale();
2840 let degrees = Chord::new(notes)
2841 .unwrap()
2842 .scale_degrees(&scale)
2843 .unwrap()
2844 .into_iter()
2845 .map(|(degree, accidental)| (degree, accidental.map(|a| a.name().to_string())))
2846 .collect::<Vec<_>>();
2847 let expected = expected
2848 .into_iter()
2849 .map(|(degree, accidental): (Option<usize>, Option<&str>)| {
2850 (degree, accidental.map(str::to_string))
2851 })
2852 .collect::<Vec<_>>();
2853 assert_eq!(degrees, expected, "{key} {notes}");
2854 }
2855 }
2856
2857 #[test]
2858 fn pitched_common_names_match_the_music21_reference() {
2859 let cases = [
2860 ("C E G", "C-major triad"),
2861 ("C E- G", "C-minor triad"),
2862 ("C E G B-", "C-dominant seventh chord"),
2863 ("C E G B", "C-major seventh chord"),
2864 ("C E- G B-", "C-minor seventh chord"),
2865 ("C E- G- B-", "C-half-diminished seventh chord"),
2866 ("C E- G- B--", "C-diminished seventh chord"),
2867 ("C E G B- D", "C-dominant-ninth"),
2868 ("C E G B D", "C-major-ninth chord"),
2869 ("C E- G B- D", "C-minor-ninth chord"),
2870 ("G2 B2 D3 F3", "G-dominant seventh chord"),
2871 ("B2 D3 F3 A3", "B-half-diminished seventh chord"),
2872 ];
2873 for (notes, expected) in cases {
2874 let chord = Chord::new(notes).unwrap();
2875 assert_eq!(chord.pitched_common_name(), expected, "{notes}");
2876 }
2877
2878 let integers: &[crate::IntegerType] = &[1, 2, 3, 4, 5, 10];
2879 let chord = Chord::new(integers).unwrap();
2880 assert_eq!(chord.pitched_common_name(), "forte class 6-36B above C#");
2881 }
2882
2883 #[test]
2884 fn c_e_g_pitchedcommonname() {
2885 let chord = Chord::new("C E G");
2886
2887 assert!(chord.is_ok());
2888
2889 assert_eq!(chord.unwrap().pitched_common_name(), "C-major triad");
2890 }
2891
2892 #[test]
2893 fn new_accepts_empty_inputs() {
2894 assert_eq!(Chord::new("").unwrap().pitched_common_name(), "empty chord");
2895 assert_eq!(
2896 Chord::new(Vec::<Pitch>::new())
2897 .unwrap()
2898 .pitched_common_name(),
2899 "empty chord"
2900 );
2901 assert_eq!(
2902 Chord::new(Option::<&str>::None)
2903 .unwrap()
2904 .pitched_common_name(),
2905 "empty chord"
2906 );
2907 }
2908
2909 #[test]
2910 fn pitched_common_names_returns_aliases() {
2911 let chord = Chord::new("C E G#").unwrap();
2912 assert_eq!(
2913 chord.pitched_common_names(),
2914 vec![
2915 "C-augmented triad".to_string(),
2916 "C-equal 3-part octave division".to_string()
2917 ]
2918 );
2919 }
2920
2921 #[test]
2922 fn chord_symbols_return_symbol_names() {
2923 let major_seventh = Chord::new("C E G B").unwrap();
2924 let petrushka = Chord::new("C4 D4 Eb4 F#4 Ab4 A4").unwrap();
2925 let slash_chord = Chord::new("F4 C5 D5 E-5").unwrap();
2926
2927 assert_eq!(major_seventh.chord_symbol().as_deref(), Some("Cmaj7"));
2928 assert_eq!(
2929 petrushka.chord_symbol().as_deref(),
2930 Some("Ddom7dim5add5addb9/C")
2931 );
2932 assert_eq!(slash_chord.chord_symbol().as_deref(), None);
2933 }
2934
2935 #[test]
2936 fn chord_symbols_with_root_accept_pitch_names() {
2937 let chord = Chord::new("G3 C4 E4").unwrap();
2938
2939 assert_eq!(
2940 chord.chord_symbol_with_root("C").unwrap().as_deref(),
2941 Some("C/G")
2942 );
2943 assert_eq!(
2944 chord.chord_symbol_with_root(0).unwrap().as_deref(),
2945 Some("C/G")
2946 );
2947 }
2948
2949 #[test]
2950 fn guitar_fingering_covers_common_chord_tones() {
2951 let chord = Chord::new("C E G").unwrap();
2952 let fingering = chord.guitar_fingering().unwrap();
2953
2954 assert_eq!(fingering.strings.len(), 6);
2955 assert_eq!(fingering.covered_pitch_classes, vec![0, 4, 7]);
2958 assert!(fingering.omitted_pitch_classes.is_empty());
2959 assert!(
2960 fingering.covered_pitch_spaces.len() >= 3,
2961 "expected a full voicing, got {:?}",
2962 fingering.covered_pitch_spaces
2963 );
2964 assert!(
2965 fingering
2966 .strings
2967 .iter()
2968 .filter(|string| string.fret.is_some_and(|fret| fret > 0))
2969 .all(|string| string
2970 .finger
2971 .is_some_and(|finger| (1..=4).contains(&finger)))
2972 );
2973 }
2974
2975 #[test]
2976 fn guitar_fingering_still_returns_large_pitch_sets() {
2977 let chord = Chord::new("C D E F G A B").unwrap();
2978 let fingering = chord.guitar_fingering().unwrap();
2979
2980 assert_eq!(fingering.strings.len(), 6);
2981 assert!(!fingering.covered_pitch_classes.is_empty());
2982 assert!(!fingering.omitted_pitch_classes.is_empty());
2983 }
2984
2985 #[test]
2986 fn guitar_fingering_uses_supplied_tuning_and_octaves() {
2987 let chord = Chord::new("D3 A3 D4").unwrap();
2988 let tuning = GuitarTuning::new(["D2", "A2", "D3", "G3", "A3", "D4"]).unwrap();
2989 let fingering = chord.guitar_fingering_with_tuning(&tuning).unwrap();
2990
2991 assert_eq!(fingering.strings.len(), 6);
2992 assert_eq!(fingering.strings[0].string_name, "D2");
2993 assert_eq!(fingering.covered_pitch_classes, vec![2, 9]);
2994 assert!(fingering.omitted_pitch_classes.is_empty());
2995 }
2996
2997 fn shape(notes: &str) -> String {
2999 Chord::new(notes)
3000 .unwrap()
3001 .guitar_fingering()
3002 .unwrap()
3003 .strings
3004 .iter()
3005 .map(|string| match string.fret {
3006 None => "x".to_string(),
3007 Some(fret) => fret.to_string(),
3008 })
3009 .collect::<Vec<_>>()
3010 .join(" ")
3011 }
3012
3013 #[test]
3014 fn guitar_fingering_finds_the_standard_open_chords() {
3015 assert_eq!(shape("C E G"), "x 3 2 0 1 0");
3018 assert_eq!(shape("A C# E"), "x 0 2 2 2 0");
3019 assert_eq!(shape("E G# B"), "0 2 2 1 0 0");
3020 assert_eq!(shape("D F# A"), "x x 0 2 3 2");
3021 assert_eq!(shape("A C E"), "x 0 2 2 1 0");
3022 assert_eq!(shape("E G B"), "0 2 2 0 0 0");
3023 assert_eq!(shape("D F A"), "x x 0 2 3 1");
3024 assert_eq!(shape("G B D F"), "3 2 0 0 0 1");
3025 assert_eq!(shape("C E G B"), "x 3 2 0 0 0");
3026 assert_eq!(shape("A C E G"), "x 0 2 0 1 0");
3027 }
3028
3029 #[test]
3030 fn guitar_fingering_keeps_every_chord_tone() {
3031 for notes in ["G B D F", "C E G B-", "A C E G", "C E G B", "B D F"] {
3034 let fingering = Chord::new(notes).unwrap().guitar_fingering().unwrap();
3035 assert!(
3036 fingering.omitted_pitch_classes.is_empty(),
3037 "{notes} dropped {:?}",
3038 fingering.omitted_pitch_classes
3039 );
3040 }
3041 }
3042
3043 #[test]
3044 fn guitar_fingering_puts_the_root_in_the_bass_for_open_chords() {
3045 for (notes, root) in [("C E G", 0), ("G B D", 7), ("E G# B", 4), ("A C E", 9)] {
3046 let fingering = Chord::new(notes).unwrap().guitar_fingering().unwrap();
3047 let bass = fingering
3048 .strings
3049 .iter()
3050 .find_map(|string| string.fret.and(string.pitch_class))
3051 .expect("a sounding string");
3052 assert_eq!(bass, root, "{notes} should sound its root lowest");
3053 }
3054 }
3055
3056 #[test]
3057 fn guitar_tuning_rejects_empty_tunings() {
3058 assert!(GuitarTuning::new(Vec::<&str>::new()).is_err());
3059 }
3060
3061 #[test]
3062 fn dyad_names_follow_music21_interval_rules() {
3063 let pcs = [0, 1];
3064 let integer_chord = Chord::new(pcs.as_slice()).unwrap();
3065 assert_eq!(integer_chord.common_name(), "Minor Second");
3066 assert_eq!(integer_chord.pitched_common_name(), "Minor Second above C");
3067
3068 let spelled_chord = Chord::new("C C#").unwrap();
3069 assert_eq!(spelled_chord.common_name(), "Augmented Unison");
3070 assert_eq!(
3071 spelled_chord.pitched_common_name(),
3072 "Augmented Unison above C"
3073 );
3074
3075 let octave = Chord::new("D3 D4").unwrap();
3076 assert_eq!(octave.common_name(), "Perfect Octave");
3077 assert_eq!(octave.pitched_common_name(), "Perfect Octave above D");
3078
3079 let compound = Chord::new("E-3 C5 C6").unwrap();
3080 assert_eq!(compound.common_name(), "Major Sixth with octave doublings");
3081 assert_eq!(
3082 compound.pitched_common_name(),
3083 "Major Sixth with octave doublings above Eb"
3084 );
3085 }
3086
3087 #[test]
3088 fn chord_metadata_methods_have_forte_and_inversion() {
3089 let chord = Chord::new("C E G").unwrap();
3090 assert_eq!(chord.root_pitch_name().as_deref(), Some("C"));
3091 assert_eq!(chord.bass_pitch_name().as_deref(), Some("C"));
3092 assert_eq!(chord.inversion(), Some(0));
3093 assert_eq!(chord.inversion_name().unwrap(), Some(53));
3094 assert_eq!(chord.inversion_text(), "Root Position");
3095 assert_eq!(chord.forte_class().as_deref(), Some("3-11B"));
3096 assert_eq!(chord.interval_class_vector(), Some(vec![0, 0, 1, 1, 1, 0]));
3097 assert!(chord.invariance_vector().is_some());
3098 assert_eq!(chord.z_relation(), None);
3099 assert!(
3100 chord
3101 .common_names()
3102 .iter()
3103 .any(|name| name == "major triad")
3104 );
3105 }
3106
3107 #[test]
3108 fn chord_simplifies_enharmonics_explicitly() {
3109 let chord = Chord::new("D# F## A#").unwrap();
3110 let simplified = chord.simplify_enharmonics(None).unwrap();
3111 assert_eq!(chord.pitches()[0].name(), "D#");
3112 assert_eq!(simplified.pitches().len(), chord.pitches().len());
3113
3114 let mut in_place = chord.clone();
3115 in_place.simplify_enharmonics_in_place(None).unwrap();
3116 assert_eq!(
3117 simplified
3118 .pitches()
3119 .into_iter()
3120 .map(|pitch| pitch.name_with_octave())
3121 .collect::<Vec<_>>(),
3122 in_place
3123 .pitches()
3124 .into_iter()
3125 .map(|pitch| pitch.name_with_octave())
3126 .collect::<Vec<_>>()
3127 );
3128 }
3129
3130 #[test]
3131 fn chord_maps_to_reduced_polyrhythm_components() {
3132 let major = Chord::new("C E G").unwrap();
3133 assert_eq!(major.polyrhythm_components(), vec![4, 5, 6]);
3134 assert_eq!(major.polyrhythm_ratio_string(), "4:5:6");
3135
3136 let empty = Chord::empty();
3137 assert_eq!(empty.polyrhythm_ratio_string(), "1");
3138 }
3139
3140 #[test]
3141 fn new_rejects_invalid_pitch_inputs() {
3142 assert!(Chord::new("C nope G").is_err());
3143 }
3144
3145 #[test]
3146 fn chord_supports_rust_conversion_traits() {
3147 let parsed: Chord = "C E G".parse().unwrap();
3148 assert_eq!(parsed.to_string(), "C-major triad");
3149 assert_eq!(parsed.notes().len(), 3);
3150
3151 let from_str = Chord::try_from("C E G").unwrap();
3152 assert_eq!(from_str.pitched_common_name(), "C-major triad");
3153
3154 let midi = [60, 64, 67];
3155 let from_slice = Chord::try_from(midi.as_slice()).unwrap();
3156 assert_eq!(from_slice.pitched_common_name(), "C-major triad");
3157 }
3158
3159 #[test]
3160 fn known_chord_types_include_music21_table_names() {
3161 let known = Chord::known_chord_types();
3162 assert_eq!(known.len(), 351);
3163 assert!(
3164 known
3165 .iter()
3166 .any(|entry| entry.common_names.iter().any(|name| name == "major triad"))
3167 );
3168 assert!(known.iter().any(|entry| {
3169 entry
3170 .common_names
3171 .iter()
3172 .any(|name| name == "dominant seventh chord")
3173 }));
3174 }
3175
3176 #[test]
3177 fn chord_first_inversion_detected() {
3178 let chord = Chord::new("E3 G3 C4").unwrap();
3179 assert_eq!(chord.inversion(), Some(1));
3180 assert_eq!(chord.inversion_name().unwrap(), Some(6));
3181 assert_eq!(chord.inversion_text(), "First Inversion");
3182 assert_eq!(
3183 Chord::new("C E G B-").unwrap().inversion_name().unwrap(),
3184 Some(7)
3185 );
3186 assert!(Chord::new("C D E").unwrap().inversion_name().is_err());
3189 }
3190
3191 #[test]
3192 fn dominant_seventh_resolves_to_tonic() {
3193 let chord = Chord::new("G3 B3 D4 F4").unwrap();
3194 let resolution = chord.resolution_chord("C", Some("major")).unwrap().unwrap();
3195
3196 assert_eq!(resolution.pitched_common_name(), "C-major triad");
3197 }
3198
3199 #[test]
3200 fn resolution_chords_stay_near_source_register() {
3201 let chord = Chord::new("G2 B2 D3 F3").unwrap();
3202 let resolution = chord.resolution_chord("C", Some("major")).unwrap().unwrap();
3203 let names = resolution
3204 .pitches()
3205 .into_iter()
3206 .map(|pitch| pitch.name_with_octave())
3207 .collect::<Vec<_>>();
3208
3209 assert_eq!(names, vec!["C3", "E3", "G3"]);
3210 }
3211
3212 #[test]
3213 fn resolution_suggestions_infer_contexts() {
3214 let chord = Chord::new("G3 B3 D4 F4").unwrap();
3215 let suggestions = chord.resolution_suggestions().unwrap();
3216
3217 assert!(suggestions.iter().any(|suggestion| {
3218 suggestion.key_context == "dominant resolution to C major"
3219 && suggestion.chord.pitched_common_name() == "C-major triad"
3220 }));
3221 assert!(suggestions.iter().any(|suggestion| {
3222 suggestion.key_context == "dominant resolution to C minor"
3223 && suggestion.chord.pitched_common_name() == "C-minor triad"
3224 }));
3225 }
3226
3227 #[test]
3228 fn resolution_suggestions_stay_near_source_register() {
3229 let chord = Chord::new("G2 B2 D3 F3").unwrap();
3230 let suggestions = chord.resolution_suggestions().unwrap();
3231 let c_major = suggestions
3232 .iter()
3233 .find(|suggestion| suggestion.key_context == "dominant resolution to C major")
3234 .unwrap();
3235 let names = c_major
3236 .chord
3237 .pitches()
3238 .into_iter()
3239 .map(|pitch| pitch.name_with_octave())
3240 .collect::<Vec<_>>();
3241
3242 assert_eq!(names, vec!["C3", "E3", "G3"]);
3243 }
3244
3245 #[test]
3246 fn resolution_suggestions_can_use_explicit_key_context() {
3247 let secondary_dominant = Chord::new("D3 F#3 A3 C4").unwrap();
3248 let c_major = Key::from_tonic_mode("C", Some("major")).unwrap();
3249 let suggestions = secondary_dominant
3250 .resolution_suggestions_in_key(&c_major)
3251 .unwrap();
3252
3253 assert_eq!(suggestions.len(), 1);
3254 assert_eq!(suggestions[0].key_context, "dominant resolution in C major");
3255 assert_eq!(suggestions[0].chord.pitched_common_name(), "G-major triad");
3256 }
3257
3258 #[test]
3259 fn dominant_seventh_resolves_to_minor_tonic() {
3260 let chord = Chord::new("G3 B3 D4 F4").unwrap();
3261 let resolution = chord.resolution_chord("C", Some("minor")).unwrap().unwrap();
3262
3263 assert_eq!(resolution.pitched_common_name(), "C-minor triad");
3264 }
3265
3266 #[test]
3267 fn secondary_dominant_resolves_to_diatonic_target() {
3268 let chord = Chord::new("D3 F#3 A3 C4").unwrap();
3269 let resolution = chord.resolution_chord("C", Some("major")).unwrap().unwrap();
3270
3271 assert_eq!(resolution.pitched_common_name(), "G-major triad");
3272 }
3273
3274 #[test]
3275 fn dominant_extensions_resolve_to_tonic() {
3276 let dominant_ninth = Chord::new("G2 B2 D3 F3 A3").unwrap();
3277 let dominant_eleventh = Chord::new("G2 B2 D3 F3 A3 C4").unwrap();
3278 let dominant_thirteenth = Chord::new("G2 B2 D3 F3 A3 C4 E4").unwrap();
3279
3280 for chord in [dominant_ninth, dominant_eleventh, dominant_thirteenth] {
3281 let resolution = chord.resolution_chord("C", Some("major")).unwrap().unwrap();
3282 assert_eq!(resolution.pitched_common_name(), "C-major triad");
3283 }
3284 }
3285
3286 #[test]
3287 fn leading_tone_sevenths_resolve_by_semitone() {
3288 let fully_diminished = Chord::new("B3 D4 F4 A-4").unwrap();
3289 let half_diminished = Chord::new("B3 D4 F4 A4").unwrap();
3290
3291 assert_eq!(
3292 fully_diminished
3293 .resolution_chord("C", Some("major"))
3294 .unwrap()
3295 .unwrap()
3296 .pitched_common_name(),
3297 "C-major triad"
3298 );
3299 assert_eq!(
3300 half_diminished
3301 .resolution_chord("C", Some("major"))
3302 .unwrap()
3303 .unwrap()
3304 .pitched_common_name(),
3305 "C-major triad"
3306 );
3307 }
3308
3309 #[test]
3310 fn leading_tone_diminished_triad_resolves_by_semitone() {
3311 let chord = Chord::new("B3 D4 F4").unwrap();
3312 let resolution = chord.resolution_chord("C", Some("major")).unwrap().unwrap();
3313
3314 assert_eq!(resolution.pitched_common_name(), "C-major triad");
3315 }
3316
3317 #[test]
3318 fn contextual_augmented_sixth_resolves_to_dominant() {
3319 let german_augmented_sixth = Chord::new("A-3 C4 E-4 F#4").unwrap();
3320 let resolution = german_augmented_sixth
3321 .resolution_chord("C", Some("major"))
3322 .unwrap()
3323 .unwrap();
3324
3325 assert_eq!(resolution.pitched_common_name(), "G-major triad");
3326 }
3327
3328 #[test]
3329 fn unsupported_resolution_returns_none() {
3330 let tonic = Chord::new("C E G").unwrap();
3331 assert!(
3332 tonic
3333 .resolution_chord("C", Some("major"))
3334 .unwrap()
3335 .is_none()
3336 );
3337 }
3338}