Skip to main content

music21/meter/
tools.rs

1//! music21's `meter.tools`: reading meters written as text, and the ways
2//! music21 conventionally divides a meter.
3//!
4//! A meter is written `3/8`, `slow 6/8`, `3/8+2/8` or `3+2/8`, the last
5//! sharing one denominator among the numerators before it. The division
6//! options are what [`super::MeterTerminal::partition_options`] chooses
7//! among, in music21's order of preference.
8
9use num::BigInt;
10use num::integer::Integer;
11
12use crate::common::numbertools::{float_ratio, limit_denominator};
13use crate::common::stringtools::get_num_from_str;
14use crate::defaults::{FloatType, UnsignedIntegerType};
15
16/// The denominators music21 will write a meter in, in order: music21's
17/// `validDenominators`.
18pub const VALID_DENOMINATORS: [UnsignedIntegerType; 8] = [1, 2, 4, 8, 16, 32, 64, 128];
19
20/// How a meter's beat is felt, from the word written before it: music21's
21/// `MeterDivision`.
22#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
23pub enum MeterDivision {
24    /// `fast 6/8`: the beat is the dotted quarter.
25    Fast,
26    /// `slow 6/8`: the beat is the eighth.
27    Slow,
28    /// No word: the meter's own reading.
29    #[default]
30    None,
31}
32
33impl MeterDivision {
34    /// The member's name in music21's enum: `FAST`, `SLOW` or `NONE`.
35    #[must_use]
36    pub fn music21_name(self) -> &'static str {
37        match self {
38            Self::Fast => "FAST",
39            Self::Slow => "SLOW",
40            Self::None => "NONE",
41        }
42    }
43}
44
45/// A meter read from text: music21's `MeterTerminalTuple`.
46#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
47pub struct SlashMeter {
48    /// The number of units.
49    pub numerator: UnsignedIntegerType,
50    /// The unit, as a note value: `8` for eighths.
51    pub denominator: UnsignedIntegerType,
52    /// The word written before it, if any.
53    pub division: MeterDivision,
54}
55
56/// Why a meter written as text could not be read, each the exception
57/// music21 raises, with its message.
58#[derive(Clone, Debug, Eq, PartialEq)]
59pub enum SlashError {
60    /// No `n/d` in it, or a numerator with no denominator after it:
61    /// music21's `MeterException`.
62    Meter(String),
63    /// A part with a slash that is not `n/d`: music21's
64    /// `TimeSignatureException`.
65    TimeSignature(String),
66    /// A part with no slash that is not a number: music21's plain
67    /// `Music21Exception`.
68    Unreadable(String),
69}
70
71impl std::fmt::Display for SlashError {
72    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73        match self {
74            Self::Meter(message) | Self::TimeSignature(message) | Self::Unreadable(message) => {
75                formatter.write_str(message)
76            }
77        }
78    }
79}
80
81impl std::error::Error for SlashError {}
82
83/// `n/d` at the start of `text`, both runs of ASCII digits, as music21's
84/// `(\d+)/(\d+)` matches it.
85fn leading_ratio(text: &str) -> Option<(UnsignedIntegerType, UnsignedIntegerType)> {
86    let (numerator, rest) = text.split_at(text.find(|c: char| !c.is_ascii_digit())?);
87    let rest = rest.strip_prefix('/')?;
88    let end = rest
89        .find(|c: char| !c.is_ascii_digit())
90        .unwrap_or(rest.len());
91    let denominator = &rest[..end];
92    if numerator.is_empty() || denominator.is_empty() {
93        return None;
94    }
95    Some((numerator.parse().ok()?, denominator.parse().ok()?))
96}
97
98/// One meter read from text, with the word before it that says how its
99/// beat is felt: music21's `slashToTuple`.
100///
101/// ```
102/// use music21::meter::tools::{MeterDivision, slash_to_tuple};
103///
104/// let read = slash_to_tuple("slow 6/8").unwrap();
105/// assert_eq!((read.numerator, read.denominator), (6, 8));
106/// assert_eq!(read.division, MeterDivision::Slow);
107/// ```
108///
109/// # Errors
110///
111/// [`SlashError::Meter`] where there is no `n/d` to read.
112pub fn slash_to_tuple(value: &str) -> Result<SlashMeter, SlashError> {
113    let (numbers, words) = get_num_from_str(value, "0123456789/.");
114    let words = words.to_lowercase();
115    let division = if words.contains("slow") {
116        MeterDivision::Slow
117    } else if words.contains("fast") {
118        MeterDivision::Fast
119    } else {
120        MeterDivision::None
121    };
122    let Some((numerator, denominator)) = leading_ratio(numbers.trim()) else {
123        return Err(SlashError::Meter(format!(
124            "slashToTuple() cannot find two part fraction for {value}"
125        )));
126    };
127    Ok(SlashMeter {
128        numerator,
129        denominator,
130        division,
131    })
132}
133
134/// A compound meter as the ratio of each of its parts, leaving out a part
135/// that is not one: music21's `slashCompoundToFraction`.
136///
137/// ```
138/// use music21::meter::tools::slash_compound_to_fraction;
139///
140/// assert_eq!(slash_compound_to_fraction("3/8+2/4"), [(3, 8), (2, 4)]);
141/// ```
142#[must_use]
143pub fn slash_compound_to_fraction(value: &str) -> Vec<(UnsignedIntegerType, UnsignedIntegerType)> {
144    value
145        .trim()
146        .split('+')
147        .filter_map(|part| slash_to_tuple(part).ok())
148        .map(|read| (read.numerator, read.denominator))
149        .collect()
150}
151
152/// A meter written with or without a denominator on each part as the ratio
153/// of each part, and whether any numerator borrowed the next denominator,
154/// as in `3+2/8`: music21's `slashMixedToFraction`.
155///
156/// ```
157/// use music21::meter::tools::slash_mixed_to_fraction;
158///
159/// let (parts, summed) = slash_mixed_to_fraction("3+2/8+3/4").unwrap();
160/// assert_eq!(parts, [(3, 8), (2, 8), (3, 4)]);
161/// assert!(summed);
162/// ```
163///
164/// # Errors
165///
166/// [`SlashError::TimeSignature`] for a part with a slash that is no ratio,
167/// [`SlashError::Unreadable`] for a bare numerator that is no number, and
168/// [`SlashError::Meter`] for a numerator with no denominator after it.
169pub fn slash_mixed_to_fraction(
170    value: &str,
171) -> Result<(Vec<(UnsignedIntegerType, UnsignedIntegerType)>, bool), SlashError> {
172    let mut read: Vec<(UnsignedIntegerType, Option<UnsignedIntegerType>)> = Vec::new();
173    let mut summed = false;
174    for part in value.trim().split('+') {
175        if part.contains('/') {
176            let ratio = slash_to_tuple(part).map_err(|_| {
177                SlashError::TimeSignature(format!("Cannot create time signature from \"{value}\""))
178            })?;
179            read.push((ratio.numerator, Some(ratio.denominator)));
180            continue;
181        }
182        let numerator = part.trim().parse().map_err(|_| {
183            SlashError::Unreadable(format!(
184                "Cannot parse this file -- this error often comes up if the musicxml \
185                 pickled file is out of date after a change in musicxml/__init__.py . \
186                 Clear your temp directory of .p and .p.gz files and try again. \
187                 Time Signature: {value} "
188            ))
189        })?;
190        read.push((numerator, None));
191        summed = true;
192    }
193
194    let mut parts = Vec::with_capacity(read.len());
195    for (index, (numerator, denominator)) in read.iter().enumerate() {
196        // A bare numerator takes the first denominator after it.
197        let denominator = denominator
198            .or_else(|| read[index + 1..].iter().find_map(|(_, later)| *later))
199            .ok_or_else(|| {
200                SlashError::Meter(format!("cannot match denominator to numerator in: {value}"))
201            })?;
202        parts.push((*numerator, denominator));
203    }
204    Ok((parts, summed))
205}
206
207/// Ratios as a meter writes them, numerators run together where neighbours
208/// share a denominator: music21's `fractionToSlashMixed`.
209///
210/// ```
211/// use music21::meter::tools::fraction_to_slash_mixed;
212///
213/// let mixed = fraction_to_slash_mixed(&[(3, 8), (2, 8), (3, 4)]);
214/// assert_eq!(mixed, [("3+2".to_string(), 8), ("3".to_string(), 4)]);
215/// ```
216#[must_use]
217pub fn fraction_to_slash_mixed(
218    fractions: &[(UnsignedIntegerType, UnsignedIntegerType)],
219) -> Vec<(String, UnsignedIntegerType)> {
220    let mut runs: Vec<(Vec<String>, UnsignedIntegerType)> = Vec::new();
221    for (numerator, denominator) in fractions {
222        match runs.last_mut() {
223            Some((numerators, shared)) if shared == denominator => {
224                numerators.push(numerator.to_string());
225            }
226            _ => runs.push((vec![numerator.to_string()], *denominator)),
227        }
228    }
229    runs.into_iter()
230        .map(|(numerators, denominator)| (numerators.join("+"), denominator))
231        .collect()
232}
233
234/// The sum of ratios, not reduced, so that `3/8 + 3/8` is `6/8`: music21's
235/// `fractionSum`. Unlike denominators meet at their least common multiple,
236/// and nothing at all sums to `0/1`.
237///
238/// ```
239/// use music21::meter::tools::fraction_sum;
240/// use num::BigInt;
241///
242/// let big = |pairs: &[(i32, i32)]| -> Vec<(BigInt, BigInt)> {
243///     pairs.iter().map(|(n, d)| (BigInt::from(*n), BigInt::from(*d))).collect()
244/// };
245/// assert_eq!(fraction_sum(&big(&[(3, 8), (3, 8)])), (6.into(), 8.into()));
246/// assert_eq!(fraction_sum(&big(&[(1, 6), (2, 3)])), (5.into(), 6.into()));
247/// ```
248#[must_use]
249pub fn fraction_sum(fractions: &[(BigInt, BigInt)]) -> (BigInt, BigInt) {
250    let Some((_, first)) = fractions.first() else {
251        return (BigInt::from(0), BigInt::from(1));
252    };
253    if fractions
254        .iter()
255        .all(|(_, denominator)| denominator == first)
256    {
257        let numerator = fractions.iter().map(|(numerator, _)| numerator).sum();
258        return (numerator, first.clone());
259    }
260    let common = fractions
261        .iter()
262        .fold(BigInt::from(1), |common, (_, denominator)| {
263            common.lcm(denominator)
264        });
265    let numerator = fractions
266        .iter()
267        .map(|(numerator, denominator)| numerator * (&common / denominator))
268        .sum();
269    (numerator, common)
270}
271
272/// The fraction with a denominator of at most sixteen nearest a proportion:
273/// music21's `proportionToFraction`. `None` for a value that is not finite.
274///
275/// ```
276/// use music21::meter::tools::proportion_to_fraction;
277/// use num::BigInt;
278///
279/// let third = proportion_to_fraction(0.333).unwrap();
280/// assert_eq!(third, (BigInt::from(1), BigInt::from(3)));
281/// ```
282#[must_use]
283pub fn proportion_to_fraction(value: FloatType) -> Option<(BigInt, BigInt)> {
284    let (numerator, denominator) = float_ratio(value)?;
285    limit_denominator(&numerator, &denominator, &BigInt::from(16)).ok()
286}
287
288/// The same ratio in shorter notes, while the denominator allows: music21's
289/// `divisionOptionsFractionsUpward`.
290#[must_use]
291pub fn fractions_upward(
292    numerator: UnsignedIntegerType,
293    denominator: UnsignedIntegerType,
294) -> Vec<String> {
295    let largest = VALID_DENOMINATORS[VALID_DENOMINATORS.len() - 1];
296    let mut out = Vec::new();
297    if denominator >= largest {
298        return out;
299    }
300    let (mut numerator, mut denominator) = (numerator * 2, denominator * 2);
301    while denominator <= largest {
302        out.push(format!("{numerator}/{denominator}"));
303        numerator *= 2;
304        denominator *= 2;
305    }
306    out
307}
308
309/// The same ratio in longer notes, while it stays whole: music21's
310/// `divisionOptionsFractionsDownward`.
311#[must_use]
312pub fn fractions_downward(
313    numerator: UnsignedIntegerType,
314    denominator: UnsignedIntegerType,
315) -> Vec<String> {
316    let smallest = VALID_DENOMINATORS[0];
317    let mut out = Vec::new();
318    if denominator <= smallest || !numerator.is_multiple_of(2) {
319        return out;
320    }
321    let (mut numerator, mut denominator) = (numerator / 2, denominator / 2);
322    loop {
323        out.push(format!("{numerator}/{denominator}"));
324        if !numerator.is_multiple_of(2) || denominator <= smallest {
325            break;
326        }
327        numerator /= 2;
328        denominator /= 2;
329    }
330    out
331}
332
333/// One unit at a time, then twice as many half as long: music21's
334/// `divisionOptionsAdditiveMultiplesUpward`, which stops at sixteen parts or
335/// at the numerator where that is larger.
336#[must_use]
337pub fn additive_multiples_upward(
338    numerator: UnsignedIntegerType,
339    denominator: UnsignedIntegerType,
340) -> Vec<Vec<String>> {
341    let mut out = Vec::new();
342    if numerator <= 1 {
343        return out;
344    }
345    let largest = VALID_DENOMINATORS[VALID_DENOMINATORS.len() - 1];
346    let limit = if numerator > 16 { numerator } else { 16 };
347    let (mut denominator, mut count) = (denominator, numerator);
348    while denominator <= largest && count <= limit {
349        out.push(vec![format!("1/{denominator}"); count as usize]);
350        denominator *= 2;
351        count *= 2;
352    }
353    out
354}
355
356/// The bar halved, and halved again while it stays even: music21's
357/// `divisionOptionsAdditiveMultiplesEvenDivision`. A `4/4` bar reads
358/// `1/2+1/2`, written in the note value a half of it actually is.
359#[must_use]
360pub fn additive_multiples_halved(
361    numerator: UnsignedIntegerType,
362    denominator: UnsignedIntegerType,
363) -> Vec<Vec<String>> {
364    let mut out = Vec::new();
365    if !numerator.is_multiple_of(2) || denominator < 2 {
366        return out;
367    }
368    let (mut count, mut denominator) = (numerator / 2, denominator / 2);
369    while denominator >= 1 && count > 1 {
370        out.push(vec![format!("1/{denominator}"); count as usize]);
371        if !count.is_multiple_of(2) || denominator == 1 {
372            break;
373        }
374        denominator /= 2;
375        count /= 2;
376    }
377    out
378}
379
380/// Even groupings in the bar's own note value: music21's
381/// `divisionOptionsAdditiveMultiples`, which reads `6/4` as `3/4+3/4`.
382#[must_use]
383pub fn additive_multiples(
384    numerator: UnsignedIntegerType,
385    denominator: UnsignedIntegerType,
386) -> Vec<Vec<String>> {
387    let mut out = Vec::new();
388    if numerator <= 3 || !numerator.is_multiple_of(2) {
389        return out;
390    }
391    let mut divisor = 2;
392    while numerator.is_multiple_of(divisor) {
393        let count = numerator / divisor;
394        if count <= 1 {
395            break;
396        }
397        out.push(vec![format!("{count}/{denominator}"); divisor as usize]);
398        divisor *= 2;
399    }
400    out
401}
402
403/// A single unit split into smaller ones: music21's
404/// `divisionOptionsAdditiveMultiplesDownward`, which only ever applies where
405/// the numerator is one.
406#[must_use]
407pub fn additive_multiples_downward(
408    numerator: UnsignedIntegerType,
409    denominator: UnsignedIntegerType,
410) -> Vec<Vec<String>> {
411    let largest = VALID_DENOMINATORS[VALID_DENOMINATORS.len() - 1];
412    let mut out = Vec::new();
413    if denominator >= largest || numerator != 1 {
414        return out;
415    }
416    let (mut count, mut denominator) = (2usize, denominator * 2);
417    while denominator <= largest {
418        out.push(vec![format!("{numerator}/{denominator}"); count]);
419        denominator *= 2;
420        count *= 2;
421    }
422    out
423}
424
425/// The ways music21 divides a meter, in the order it prefers them, each
426/// once: music21's `divisionOptionsAlgo`.
427///
428/// The order is the behaviour, not decoration:
429/// [`super::MeterTerminal::partitioned_by_count`] takes the first option of the right
430/// length, so these pieces are composed in the same sequence music21
431/// composes them in.
432#[must_use]
433pub fn division_options_algo(
434    numerator: UnsignedIntegerType,
435    denominator: UnsignedIntegerType,
436) -> Vec<Vec<String>> {
437    let mut options: Vec<Vec<String>> = Vec::new();
438
439    // Compound meters divide into threes first: 6/8 is two dotted beats.
440    if numerator > 3 && numerator.is_multiple_of(3) {
441        options.push(vec![format!("3/{denominator}"); (numerator / 3) as usize]);
442    }
443    // The odd meters music21 keeps a grouping for.
444    let groupings: &[&[UnsignedIntegerType]] = match numerator {
445        5 => &[&[2, 3], &[3, 2]],
446        7 => &[&[2, 2, 3], &[3, 2, 2], &[2, 3, 2]],
447        10 => &[&[2, 2, 3, 3]],
448        _ => &[],
449    };
450    for grouping in groupings {
451        options.push(
452            grouping
453                .iter()
454                .map(|count| format!("{count}/{denominator}"))
455                .collect(),
456        );
457    }
458    options.extend(additive_multiples_upward(numerator, denominator));
459    options.extend(additive_multiples_halved(numerator, denominator));
460    options.push(vec![format!("{numerator}/{denominator}")]);
461    options.extend(additive_multiples(numerator, denominator));
462    options.extend(additive_multiples_downward(numerator, denominator));
463    for written in fractions_downward(numerator, denominator) {
464        options.push(vec![written]);
465    }
466    for written in fractions_upward(numerator, denominator) {
467        options.push(vec![written]);
468    }
469    // music21 hands each option out once.
470    let mut seen: Vec<Vec<String>> = Vec::new();
471    options.retain(|option| {
472        if seen.contains(option) {
473            return false;
474        }
475        seen.push(option.clone());
476        true
477    });
478    options
479}
480
481/// The divisions music21 keeps by hand because no rule produces them: only
482/// the two extra readings of a five.
483#[must_use]
484pub fn division_options_preset(
485    numerator: UnsignedIntegerType,
486    denominator: UnsignedIntegerType,
487) -> Vec<Vec<String>> {
488    if numerator != 5 {
489        return Vec::new();
490    }
491    vec![
492        vec![
493            format!("2/{denominator}"),
494            format!("2/{denominator}"),
495            format!("1/{denominator}"),
496        ],
497        vec![
498            format!("2/{denominator}"),
499            format!("1/{denominator}"),
500            format!("2/{denominator}"),
501        ],
502    ]
503}
504
505#[cfg(test)]
506mod tests {
507    use super::*;
508
509    fn strings(options: &[Vec<String>]) -> Vec<String> {
510        options.iter().map(|option| option.join(",")).collect()
511    }
512
513    #[test]
514    fn a_meter_is_read_with_its_word() {
515        let read = slash_to_tuple("7/32").unwrap();
516        assert_eq!((read.numerator, read.denominator), (7, 32));
517        assert_eq!(read.division, MeterDivision::None);
518        assert_eq!(
519            slash_to_tuple("Fast 6/8").unwrap().division,
520            MeterDivision::Fast
521        );
522        assert_eq!(
523            slash_to_tuple("3.0/4.0").unwrap_err(),
524            SlashError::Meter("slashToTuple() cannot find two part fraction for 3.0/4.0".into())
525        );
526    }
527
528    #[test]
529    fn a_mixed_meter_fails_as_music21_fails() {
530        let (parts, summed) = slash_mixed_to_fraction("3+2+5/8+3/4+2+1+4/16").unwrap();
531        assert_eq!(
532            parts,
533            [(3, 8), (2, 8), (5, 8), (3, 4), (2, 16), (1, 16), (4, 16)]
534        );
535        assert!(summed);
536        assert_eq!(
537            slash_mixed_to_fraction("4/4").unwrap(),
538            (vec![(4, 4)], false)
539        );
540        assert_eq!(
541            slash_mixed_to_fraction("3+2+5/8+3/4+2+1+4").unwrap_err(),
542            SlashError::Meter("cannot match denominator to numerator in: 3+2+5/8+3/4+2+1+4".into())
543        );
544        assert_eq!(
545            slash_mixed_to_fraction("3.0/4.0").unwrap_err(),
546            SlashError::TimeSignature("Cannot create time signature from \"3.0/4.0\"".into())
547        );
548        assert!(matches!(
549            slash_mixed_to_fraction("x+3/4"),
550            Err(SlashError::Unreadable(_))
551        ));
552    }
553
554    #[test]
555    fn fractions_sum_without_reducing() {
556        let big = |pairs: &[(i32, i32)]| -> Vec<(BigInt, BigInt)> {
557            pairs
558                .iter()
559                .map(|(n, d)| (BigInt::from(*n), BigInt::from(*d)))
560                .collect()
561        };
562        let sum = |pairs: &[(i32, i32)]| fraction_sum(&big(pairs));
563        assert_eq!(
564            sum(&[(1, 13), (2, 17)]),
565            (BigInt::from(43), BigInt::from(221))
566        );
567        assert_eq!(sum(&[(3, 4), (1, 2)]), (BigInt::from(5), BigInt::from(4)));
568        assert_eq!(sum(&[]), (BigInt::from(0), BigInt::from(1)));
569        assert_eq!(
570            proportion_to_fraction(0.83333),
571            Some((BigInt::from(5), BigInt::from(6)))
572        );
573        assert_eq!(proportion_to_fraction(FloatType::NAN), None);
574    }
575
576    #[test]
577    fn the_options_are_music21s() {
578        assert_eq!(
579            strings(&division_options_algo(12, 8)),
580            [
581                "3/8,3/8,3/8,3/8",
582                "1/8,1/8,1/8,1/8,1/8,1/8,1/8,1/8,1/8,1/8,1/8,1/8",
583                "1/4,1/4,1/4,1/4,1/4,1/4",
584                "1/2,1/2,1/2",
585                "12/8",
586                "6/8,6/8",
587                "6/4",
588                "3/2",
589                "24/16",
590                "48/32",
591                "96/64",
592                "192/128",
593            ]
594        );
595        assert_eq!(
596            strings(&division_options_algo(3, 128)),
597            ["1/128,1/128,1/128", "3/128"]
598        );
599        assert_eq!(fractions_downward(12, 16), ["6/8", "3/4"]);
600        assert_eq!(strings(&additive_multiples(6, 4)), ["3/4,3/4"]);
601        assert!(additive_multiples_halved(3, 4).is_empty());
602    }
603}