Skip to main content

music21/figuredbass/
mod.rs

1//! Figured bass: the numbers written under a bass note, and what they mean.
2//!
3//! A column of figures says how far above the bass each note of the chord
4//! stands, and an accidental beside a number says how that note is spelled.
5//! Most of a column is left out in practice — a bare `7` means a seventh
6//! chord in root position, fifth and third and all — so a column is read in
7//! two forms: as written, and expanded to every note it stands for.
8//!
9//! This is the port of music21's `figuredBass.notation`, and it is what
10//! [`crate::roman::RomanNumeral`] reads its own digits with.
11
12use std::fmt;
13
14pub mod checker;
15pub mod possibility;
16pub mod realizer;
17pub mod resolution;
18pub mod rules;
19pub mod scale;
20pub mod segment;
21
22use crate::{
23    defaults::IntegerType,
24    error::{Error, Result},
25    pitch::{Accidental, Pitch},
26};
27
28/// The number a figure carries when it is nothing but an extender line:
29/// music21's `EXTENDER_SENTINEL`.
30pub const EXTENDER: IntegerType = -1;
31
32/// The shorthand a column is written in, and every note it stands for.
33///
34/// music21's `shorthandNotation`. A column not listed here is read as it was
35/// written.
36const SHORTHAND: &[(&[Option<IntegerType>], &[IntegerType])] = &[
37    // A column written as nothing at all, or as a bare accidental, is the
38    // triad over its bass.
39    (&[None], &[5, 3]),
40    (&[Some(5)], &[5, 3]),
41    (&[Some(6)], &[6, 3]),
42    (&[Some(7)], &[7, 5, 3]),
43    (&[Some(9)], &[9, 7, 5, 3]),
44    (&[Some(11)], &[11, 9, 7, 5, 3]),
45    (&[Some(13)], &[13, 11, 9, 7, 5, 3]),
46    (&[Some(6), Some(5)], &[6, 5, 3]),
47    (&[Some(4), Some(3)], &[6, 4, 3]),
48    (&[Some(4), Some(2)], &[6, 4, 2]),
49    (&[Some(2)], &[6, 4, 2]),
50];
51
52/// The marks figured bass writes that music21's `Accidental` does not know by
53/// itself, and what each stands for: music21's `specialModifiers`.
54const SPECIAL: &[(&str, &str)] = &[
55    ("+", "#"),
56    ("/", "-"),
57    ("\\", "#"),
58    ("b", "-"),
59    ("bb", "--"),
60    ("bbb", "---"),
61    ("bbbb", "-----"),
62    ("++", "##"),
63    ("+++", "###"),
64    ("++++", "####"),
65    ("\u{266f}", "#"),
66    ("\u{266e}", "n"),
67    ("\u{266d}", "-"),
68];
69
70/// The accidental written beside a figure: music21's `Modifier`.
71///
72/// Figured bass has its own marks — a `+` raises and a `/` lowers — so the
73/// string it was written with is kept alongside the accidental it means.
74#[derive(Clone, Debug, Default, PartialEq)]
75#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
76#[must_use]
77pub struct Modifier {
78    written: Option<String>,
79    accidental: Option<Accidental>,
80}
81
82impl Modifier {
83    /// Reads one, which may be nothing at all: neither `None` nor the empty
84    /// string says anything about how the note is spelled.
85    pub fn new(written: Option<&str>) -> Result<Self> {
86        let Some(mark) = written.filter(|mark| !mark.is_empty()) else {
87            return Ok(Self {
88                written: written.map(str::to_string),
89                accidental: None,
90            });
91        };
92        let accidental = match Accidental::new(mark) {
93            Ok(accidental) => accidental,
94            Err(_) => {
95                let Some((_, spelled)) = SPECIAL.iter().find(|(special, _)| *special == mark)
96                else {
97                    return Err(Error::Notation(format!(
98                        "Figure modifier unsupported in music21: {mark}"
99                    )));
100                };
101                Accidental::new(*spelled)?
102            }
103        };
104        Ok(Self {
105            written: Some(mark.to_string()),
106            accidental: Some(accidental),
107        })
108    }
109
110    /// The mark as it was written.
111    pub fn written(&self) -> Option<&str> {
112        self.written.as_deref()
113    }
114
115    /// The accidental it stands for, and nothing where nothing was written.
116    pub fn accidental(&self) -> Option<&Accidental> {
117        self.accidental.as_ref()
118    }
119
120    /// The same note spelled as this modifier asks.
121    ///
122    /// A written natural replaces whatever was there; anything else is added
123    /// to it, so a sharp against a flattened note raises it to a natural.
124    pub fn modify(&self, pitch: &Pitch) -> Result<Pitch> {
125        let Some(accidental) = &self.accidental else {
126            return Ok(pitch.clone());
127        };
128        let mut modified = pitch.clone();
129        let alter = if accidental.alter() == 0.0 || pitch.written_accidental().is_none() {
130            accidental.alter()
131        } else {
132            pitch.accidental().alter() + accidental.alter()
133        };
134        modified.set_accidental(Accidental::new(alter)?);
135        Ok(modified)
136    }
137
138    /// The name of a pitch spelled as this modifier asks: music21's
139    /// `modifyPitchName`, so a sharp makes `D` into `D#`.
140    pub fn modify_pitch_name(&self, name: &str) -> Result<String> {
141        Ok(self.modify(&Pitch::from_name(name)?)?.name())
142    }
143}
144
145/// A pitch from its name: music21's `convertToPitch`, which raises a
146/// `ValueError` rather than a pitch error for a name it cannot read.
147pub fn convert_to_pitch(name: &str) -> Result<Pitch> {
148    Pitch::from_name(name)
149        .map_err(|_| Error::Value(format!("Cannot convert string {name} to a music21 Pitch.")))
150}
151
152impl fmt::Display for Modifier {
153    /// music21's `_reprInternal`: the mark and the accidental it means.
154    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
155        let written = match &self.written {
156            Some(written) => written.as_str(),
157            None => "None",
158        };
159        match &self.accidental {
160            Some(accidental) => write!(f, "{written} {}", accidental.name()),
161            None => write!(f, "{written} None"),
162        }
163    }
164}
165
166/// One figure of a column: a number above the bass and the accidental written
167/// beside it.
168#[derive(Clone, Debug, PartialEq)]
169#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
170#[must_use]
171pub struct Figure {
172    number: Option<IntegerType>,
173    modifier: Modifier,
174    extender: bool,
175}
176
177impl Figure {
178    /// One figure. A number of `None` is a figure written as a bare
179    /// accidental, which stands for the third.
180    pub fn new(number: Option<IntegerType>, modifier: Modifier, extender: bool) -> Self {
181        Self {
182            number,
183            modifier,
184            extender,
185        }
186    }
187
188    /// How far above the bass the note stands, counted inclusively.
189    pub fn number(&self) -> Option<IntegerType> {
190        self.number
191    }
192
193    /// Puts the figure at another number.
194    pub fn set_number(&mut self, number: Option<IntegerType>) {
195        self.number = number;
196    }
197
198    /// The accidental written beside the number.
199    pub fn modifier(&self) -> &Modifier {
200        &self.modifier
201    }
202
203    /// Whether a line carries the figure on from the note before.
204    pub fn has_extender(&self) -> bool {
205        self.extender
206    }
207
208    /// Whether the figure is nothing but that line: music21 reads a number of
209    /// one as no number at all, so an extender on it carries the whole
210    /// column forward.
211    pub fn is_pure_extender(&self) -> bool {
212        self.number == Some(1) && self.extender
213    }
214}
215
216impl fmt::Display for Figure {
217    /// music21's `_reprInternal`.
218    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
219        if self.is_pure_extender() {
220            return write!(f, "pure-extender <Modifier {}>", self.modifier);
221        }
222        let number = match self.number {
223            Some(EXTENDER) => "_".to_string(),
224            Some(number) => number.to_string(),
225            None => "None".to_string(),
226        };
227        let extender = if self.extender { "(extender)" } else { "" };
228        write!(f, "{number}{extender} <Modifier {}>", self.modifier)
229    }
230}
231
232/// One column of figured bass, as written and as it stands expanded.
233///
234/// music21's `figuredBass.notation.Notation`. The figures are given as one
235/// string, comma-separated: `'7,5,#3'`, `'6,4'`, `'4+,2'`.
236#[derive(Clone, Debug, Default, PartialEq)]
237#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
238#[must_use]
239pub struct Notation {
240    column: String,
241    figure_strings: Vec<String>,
242    original_numbers: Vec<Option<IntegerType>>,
243    original_modifiers: Vec<Option<String>>,
244    numbers: Vec<Option<IntegerType>>,
245    modifier_strings: Vec<Option<String>>,
246    extenders: Vec<bool>,
247    figures: Vec<Figure>,
248    figures_as_written: Vec<Figure>,
249}
250
251impl Notation {
252    /// Reads a column.
253    pub fn parse(column: &str) -> Result<Self> {
254        let mut notation = Self {
255            column: column.to_string(),
256            ..Self::default()
257        };
258        notation.read_column()?;
259        notation.expand();
260        notation.build_figures()?;
261        Ok(notation)
262    }
263
264    /// music21's `_parseNotationColumn`: every comma-separated figure split
265    /// into its number and the mark beside it.
266    fn read_column(&mut self) -> Result<()> {
267        for written in self.column.split(',') {
268            let written = written.trim();
269            self.figure_strings.push(written.to_string());
270            let digits: String = written
271                .chars()
272                .filter(|letter| letter.is_ascii_digit() || *letter == '_')
273                .collect();
274            let marks: String = written
275                .chars()
276                .filter(|letter| !letter.is_ascii_digit() && *letter != '_')
277                .collect();
278
279            let mut number = None;
280            let mut extender = false;
281            if !digits.is_empty() {
282                if digits == "_" {
283                    number = Some(EXTENDER);
284                    extender = true;
285                } else if digits.contains('_') {
286                    extender = true;
287                    number = digits.trim_matches('_').parse().ok();
288                } else {
289                    number = digits.parse().ok();
290                }
291            }
292            self.original_numbers.push(number);
293            self.original_modifiers
294                .push((!marks.is_empty()).then_some(marks));
295            self.extenders.push(extender);
296        }
297        self.numbers = self.original_numbers.clone();
298        self.modifier_strings = self.original_modifiers.clone();
299        Ok(())
300    }
301
302    /// music21's `_translateToLonghand`: a column written in shorthand stands
303    /// for every note the shorthand leaves out, and each mark stays with the
304    /// number it was written against.
305    fn expand(&mut self) {
306        let longhand = SHORTHAND
307            .iter()
308            .find(|(shorthand, _)| *shorthand == self.numbers.as_slice())
309            .map(|(_, longhand)| longhand.to_vec());
310        let Some(longhand) = longhand else {
311            // A figure written as a bare accidental is the third.
312            self.numbers = self
313                .numbers
314                .iter()
315                .map(|number| Some(number.unwrap_or(3)))
316                .collect();
317            return;
318        };
319        let against: Vec<IntegerType> = self
320            .numbers
321            .iter()
322            .map(|number| number.unwrap_or(3))
323            .collect();
324        self.modifier_strings = longhand
325            .iter()
326            .map(|number| {
327                against
328                    .iter()
329                    .position(|written| written == number)
330                    .and_then(|index| self.modifier_strings[index].clone())
331            })
332            .collect();
333        self.numbers = longhand.into_iter().map(Some).collect();
334    }
335
336    /// music21's `_getFigures`: the numbers and their marks, paired up.
337    fn build_figures(&mut self) -> Result<()> {
338        for (index, number) in self.numbers.iter().enumerate() {
339            let modifier = Modifier::new(self.modifier_strings[index].as_deref())?;
340            let extender = self.extenders.get(index).copied().unwrap_or(false);
341            self.figures.push(Figure::new(*number, modifier, extender));
342        }
343        for (index, number) in self.original_numbers.iter().enumerate() {
344            let modifier = Modifier::new(self.original_modifiers[index].as_deref())?;
345            self.figures_as_written
346                .push(Figure::new(*number, modifier, false));
347        }
348        Ok(())
349    }
350
351    /// The column as it was written.
352    pub fn column(&self) -> &str {
353        &self.column
354    }
355
356    /// Each figure of the written column, as a string.
357    pub fn figure_strings(&self) -> &[String] {
358        &self.figure_strings
359    }
360
361    /// The numbers as written, before the shorthand was expanded.
362    pub fn original_numbers(&self) -> &[Option<IntegerType>] {
363        &self.original_numbers
364    }
365
366    /// The marks as written.
367    pub fn original_modifiers(&self) -> &[Option<String>] {
368        &self.original_modifiers
369    }
370
371    /// The numbers of the expanded column.
372    pub fn numbers(&self) -> &[Option<IntegerType>] {
373        &self.numbers
374    }
375
376    /// The marks of the expanded column.
377    pub fn modifier_strings(&self) -> &[Option<String>] {
378        &self.modifier_strings
379    }
380
381    /// Whether any figure carries a line on from the note before.
382    pub fn has_extenders(&self) -> bool {
383        self.extenders.iter().any(|extender| *extender)
384    }
385
386    /// Which figures carry such a line.
387    pub fn extenders(&self) -> &[bool] {
388        &self.extenders
389    }
390
391    /// The figures of the expanded column.
392    pub fn figures(&self) -> &[Figure] {
393        &self.figures
394    }
395
396    /// The figures of the column as it was written.
397    pub fn figures_as_written(&self) -> &[Figure] {
398        &self.figures_as_written
399    }
400
401    /// The accidentals of the expanded column, one per figure.
402    pub fn modifiers(&self) -> Vec<&Modifier> {
403        self.figures.iter().map(Figure::modifier).collect()
404    }
405}
406
407impl fmt::Display for Notation {
408    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
409        f.write_str(&self.column)
410    }
411}
412
413#[cfg(test)]
414mod tests {
415    use super::*;
416
417    #[test]
418    fn a_column_keeps_what_it_was_written_with_beside_what_it_means() {
419        let notation = Notation::parse("6,#").unwrap();
420        assert_eq!(notation.column(), "6,#");
421        assert_eq!(notation.figures_as_written().len(), 2);
422        assert_eq!(notation.original_modifiers(), [None, Some("#".to_string())]);
423        assert_eq!(notation.extenders(), [false, false]);
424        assert_eq!(notation.modifiers().len(), notation.figures().len());
425        assert_eq!(notation.modifiers()[1].written(), Some("#"));
426        assert_eq!(notation.modifiers()[0].written(), None);
427        assert!(notation.to_string().contains("6,#"));
428
429        let mut figure = Figure::new(Some(6), Modifier::new(None).unwrap(), true);
430        assert!(figure.has_extender());
431        assert!(!figure.is_pure_extender());
432        figure.set_number(Some(1));
433        assert!(figure.is_pure_extender());
434        figure.set_number(None);
435        assert_eq!(figure.number(), None);
436    }
437
438    /// music21's own examples for `modifyPitchName` and `convertToPitch`.
439    #[test]
440    fn a_modifier_respells_a_pitch_name() {
441        assert_eq!(
442            Modifier::new(Some("#"))
443                .unwrap()
444                .modify_pitch_name("D")
445                .unwrap(),
446            "D#"
447        );
448        assert_eq!(
449            Modifier::new(Some("-"))
450                .unwrap()
451                .modify_pitch_name("F")
452                .unwrap(),
453            "Fb"
454        );
455        assert_eq!(
456            Modifier::new(Some("n"))
457                .unwrap()
458                .modify_pitch_name("C#")
459                .unwrap(),
460            "C"
461        );
462        assert_eq!(
463            Modifier::new(None)
464                .unwrap()
465                .modify_pitch_name("Bb")
466                .unwrap(),
467            "Bb"
468        );
469        assert!(
470            Modifier::new(Some("#"))
471                .unwrap()
472                .modify_pitch_name("H")
473                .is_err()
474        );
475
476        assert_eq!(convert_to_pitch("C5").unwrap().to_string(), "C5");
477        assert!(matches!(convert_to_pitch("nonsense"), Err(Error::Value(_))));
478    }
479
480    #[test]
481    fn a_column_expands_out_of_its_shorthand() {
482        let notation = Notation::parse("4+,2").unwrap();
483        assert_eq!(notation.figure_strings(), ["4+", "2"]);
484        assert_eq!(notation.original_numbers(), [Some(4), Some(2)]);
485        assert_eq!(notation.numbers(), [Some(6), Some(4), Some(2)]);
486        assert_eq!(
487            notation.modifier_strings(),
488            [None, Some("+".to_string()), None]
489        );
490        assert_eq!(
491            notation.figures()[1].to_string(),
492            "4 <Modifier + sharp>",
493            "the mark stays with the number it was written against"
494        );
495    }
496
497    #[test]
498    fn a_bare_mark_is_the_third() {
499        let notation = Notation::parse("-6, -").unwrap();
500        assert_eq!(notation.original_numbers(), [Some(6), None]);
501        assert_eq!(notation.numbers(), [Some(6), Some(3)]);
502        assert_eq!(notation.figures()[1].to_string(), "3 <Modifier - flat>");
503    }
504
505    #[test]
506    fn figured_bass_reads_its_own_marks() {
507        // A `+` raises and a `/` lowers, which no accidental name would.
508        assert_eq!(
509            Modifier::new(Some("+"))
510                .unwrap()
511                .accidental()
512                .map(|accidental| accidental.name()),
513            Some("sharp")
514        );
515        assert_eq!(
516            Modifier::new(Some("/"))
517                .unwrap()
518                .accidental()
519                .map(|accidental| accidental.name()),
520            Some("flat")
521        );
522        assert!(Modifier::new(Some("")).unwrap().accidental().is_none());
523        assert!(Modifier::new(None).unwrap().accidental().is_none());
524        assert!(Modifier::new(Some("zzz")).is_err());
525    }
526
527    #[test]
528    fn an_extender_carries_the_figure_on() {
529        let notation = Notation::parse("7_").unwrap();
530        assert!(notation.has_extenders());
531        let pure = Figure::new(Some(1), Modifier::new(Some("#")).unwrap(), true);
532        assert!(pure.is_pure_extender());
533        assert_eq!(pure.to_string(), "pure-extender <Modifier # sharp>");
534    }
535}