Skip to main content

music21/corpus/
chorales.rs

1//! Bach's chorales by their numbers in each catalogue: music21's
2//! `corpus.chorales.ChoraleList` and `ChoraleListRKBWV`.
3//!
4//! Two lists, as music21 has them. The first, from Wikipedia's list of
5//! chorale harmonisations (CC BY-SA), numbers BWV 250-438 in the Kalmus,
6//! Bärenreiter, Budapest and Riemenschneider catalogues. The second, from
7//! Margaret Greentree's jsbchorales.net, covers every chorale in the corpus
8//! but only by Riemenschneider, BWV and Kalmus number. Both are kept in
9//! `src/corpus/chorales/` as music21 writes them.
10
11use std::sync::LazyLock;
12
13/// The Wikipedia list, one `|title||bwv||kalmus||baerenreiter||budapest||riemenschneider||notes` per line.
14const WIKIPEDIA: &str = include_str!("chorales/wikipedia.txt");
15
16/// The Greentree list, one `riemenschneider---||---bwv---||---title---||---kalmus` per line.
17const GREENTREE: &str = include_str!("chorales/greentree.txt");
18
19/// What the Wikipedia list writes for a chorale with no notes.
20const NO_NOTES: &str = " ";
21
22/// A chorale of BWV 250-438, numbered in every catalogue.
23#[derive(Clone, Debug, PartialEq, Eq)]
24pub struct Chorale {
25    /// The chorale's German title.
26    pub title: String,
27    /// Its number in the Bach-Werke-Verzeichnis.
28    pub bwv: u32,
29    /// Its number in the Kalmus edition.
30    pub kalmus: u32,
31    /// Its number in the Bärenreiter (Kirnberger) edition.
32    pub baerenreiter: u32,
33    /// Its number in the Budapest edition.
34    pub budapest: u32,
35    /// Its number in Riemenschneider's edition.
36    pub riemenschneider: u32,
37    /// What the list notes about it, where it notes anything.
38    pub notes: Option<String>,
39}
40
41/// A chorale of the corpus by its Riemenschneider, BWV and Kalmus numbers.
42#[derive(Clone, Debug, PartialEq, Eq)]
43pub struct CorpusChorale {
44    /// Its number in Riemenschneider's edition.
45    pub riemenschneider: u32,
46    /// Its BWV number with the movement, as the corpus names its file:
47    /// `153.1`, `248.12-2`.
48    pub bwv: String,
49    /// The chorale's German title.
50    pub title: String,
51    /// Its number in the Kalmus edition; 0 where it has none.
52    pub kalmus: u32,
53}
54
55/// The chorales of BWV 250-438, in the list's order.
56///
57/// ```
58/// let first = &music21::corpus::chorales::chorales()[0];
59/// assert_eq!(first.title, "Was Gott tut, das ist wohlgetan");
60/// assert_eq!((first.bwv, first.riemenschneider), (250, 347));
61/// ```
62pub fn chorales() -> &'static [Chorale] {
63    static READ: LazyLock<Vec<Chorale>> =
64        LazyLock::new(|| WIKIPEDIA.lines().filter_map(wikipedia_line).collect());
65    &READ
66}
67
68/// The corpus's chorales, by Riemenschneider number in the list's order.
69///
70/// ```
71/// let second = &music21::corpus::chorales::corpus_chorales()[1];
72/// assert_eq!(second.bwv, "347");
73/// assert_eq!(second.kalmus, 176);
74/// ```
75pub fn corpus_chorales() -> &'static [CorpusChorale] {
76    static READ: LazyLock<Vec<CorpusChorale>> =
77        LazyLock::new(|| GREENTREE.lines().filter_map(greentree_line).collect());
78    &READ
79}
80
81fn wikipedia_line(line: &str) -> Option<Chorale> {
82    let line = line.trim().strip_prefix('|')?;
83    let fields: Vec<&str> = line.split("||").collect();
84    let [
85        title,
86        bwv,
87        kalmus,
88        baerenreiter,
89        budapest,
90        riemenschneider,
91        notes,
92    ] = fields[..]
93    else {
94        return None;
95    };
96    Some(Chorale {
97        title: title.to_string(),
98        bwv: bwv.parse().ok()?,
99        kalmus: kalmus.parse().ok()?,
100        baerenreiter: baerenreiter.parse().ok()?,
101        budapest: budapest.parse().ok()?,
102        riemenschneider: riemenschneider.parse().ok()?,
103        notes: (notes != NO_NOTES).then(|| notes.to_string()),
104    })
105}
106
107fn greentree_line(line: &str) -> Option<CorpusChorale> {
108    let fields: Vec<&str> = line.trim().split("---||---").collect();
109    let [riemenschneider, bwv, title, kalmus] = fields[..] else {
110        return None;
111    };
112    Some(CorpusChorale {
113        riemenschneider: riemenschneider.parse().ok()?,
114        bwv: bwv.to_string(),
115        title: title.to_string(),
116        kalmus: kalmus.parse().ok()?,
117    })
118}
119
120/// A BWV number as a number to sort by: music21's `Iterator._bwvSort`.
121/// A hyphen becomes a decimal point or a zero, and a letter its place
122/// counted from `a` as 10, so `69.6-a` sorts as `69.6010`.
123///
124/// ```
125/// use music21::corpus::chorales::bwv_sort_key;
126///
127/// assert_eq!(bwv_sort_key("69.6-a"), 69.601);
128/// assert_eq!(bwv_sort_key("145-a"), 145.01);
129/// assert!(bwv_sort_key("18.5-w") < bwv_sort_key("20.7"));
130/// ```
131pub fn bwv_sort_key(bwv: &str) -> f64 {
132    let mut out = String::new();
133    for character in bwv.chars() {
134        if character.is_ascii_digit() || character == '.' {
135            out.push(character);
136        } else if character == '-' {
137            out.push_str(if out.contains('.') { "0" } else { ".0" });
138        } else if character.is_alphabetic() {
139            // Shifted so that 'a' is 10.
140            out.push_str(&(character as i64 - 87).to_string());
141        }
142    }
143    out.parse().unwrap_or(0.0)
144}
145
146#[cfg(test)]
147mod tests {
148    use super::*;
149
150    #[test]
151    fn every_line_of_both_lists_is_read() {
152        assert_eq!(chorales().len(), WIKIPEDIA.lines().count());
153        assert_eq!(corpus_chorales().len(), GREENTREE.lines().count());
154    }
155
156    #[test]
157    fn a_chorale_without_notes_has_none() {
158        let found = chorales()
159            .iter()
160            .find(|chorale| chorale.bwv == 431)
161            .unwrap();
162        assert_eq!(found.notes, None);
163        assert_eq!(found.budapest, 358);
164        assert_eq!(
165            chorales()[2].notes.as_deref(),
166            Some("3rd Wedding Chorale in this group")
167        );
168    }
169}