Skip to main content

music21/meter/
mod.rs

1//! Time signatures, ported from music21's `meter` package.
2//!
3//! [`TimeSignature`] covers the part of music21's meter handling that is a pure
4//! function of the numerator and denominator: how long a bar is, how many beats
5//! it carries, how long each beat is, and how that beat subdivides.
6//!
7//! music21 derives all of this from a `MeterSequence` partition tree, and so
8//! does this: a meter carries the four sequences music21 hangs off one — the
9//! display, the beats, the beams and the accents — and answers from them.
10//! [`TimeSignature::beams_for`] beams a run of notes against the beam
11//! sequence, and the weights come off the accent sequence, so a caller who
12//! sets them reads their own back. The partition rule is music21's
13//! `_setDefaultBeatPartitions`, verified
14//! against upstream by the `meter_parity` fixture.
15
16pub mod sequence;
17pub mod tools;
18
19pub use sequence::{MeterTerminal, OffsetAlign};
20
21use crate::defaults::{FloatType, UnsignedIntegerType};
22use crate::duration::Duration;
23use crate::duration::DurationType;
24use crate::error::{Error, Result};
25use crate::notation::{BeamType, Beams};
26
27/// What a partition of `count` parts is called: music21's `partitionStr`,
28/// `"Duple"` for two and `"Triple"` for three. Counts above eight are spelled
29/// `"<n>-uple"`, as music21 spells them.
30#[must_use]
31pub fn partition_name(count: usize) -> String {
32    BEAT_COUNT_NAMES
33        .get(count)
34        .map_or_else(|| format!("{count}-uple"), |name| (*name).to_string())
35}
36
37/// Names music21 gives a partition count, indexed by the count itself.
38///
39/// Index 0 is music21's `Empty`, which a valid time signature never reaches.
40const BEAT_COUNT_NAMES: [&str; 9] = [
41    "Empty",
42    "Single",
43    "Duple",
44    "Triple",
45    "Quadruple",
46    "Quintuple",
47    "Sextuple",
48    "Septuple",
49    "Octuple",
50];
51
52/// How the beat of a meter subdivides.
53///
54/// Mirrors music21's `beatDivisionCountName`.
55#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
56#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
57pub enum BeatDivision {
58    /// A single-beat meter, which music21 reports as `Other` rather than as a
59    /// division — there is no lower level to divide.
60    Other,
61    /// Beats divide in two.
62    Simple,
63    /// Beats divide in three.
64    Compound,
65}
66
67impl BeatDivision {
68    /// Returns music21's name for this division.
69    pub fn music21_name(&self) -> &'static str {
70        match self {
71            Self::Other => "Other",
72            Self::Simple => "Simple",
73            Self::Compound => "Compound",
74        }
75    }
76
77    /// Returns the number of divisions in one beat.
78    ///
79    /// Matches music21's `beatDivisionCount`, which reports `1` rather than
80    /// raising for a single-beat meter.
81    pub fn count(&self) -> UnsignedIntegerType {
82        match self {
83            Self::Other => 1,
84            Self::Simple => 2,
85            Self::Compound => 3,
86        }
87    }
88}
89
90/// A time signature, such as `4/4` or `6/8`.
91///
92/// ```
93/// use music21::TimeSignature;
94///
95/// let six_eight = TimeSignature::from_ratio_string("6/8")?;
96/// assert_eq!(six_eight.beat_count(), 2);
97/// assert_eq!(six_eight.beat_quarter_length(), 1.5);
98/// assert_eq!(six_eight.classification(), "Compound Duple");
99/// # Ok::<(), music21::Error>(())
100/// ```
101/// Not `Copy`, `Eq` or `Hash`: a meter is about to carry the partitions it
102/// is felt in, and those weigh their parts in floats.
103#[derive(Clone, Debug, PartialEq)]
104#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
105#[must_use]
106pub struct TimeSignature {
107    numerator: UnsignedIntegerType,
108    denominator: UnsignedIntegerType,
109    favor_compound: bool,
110    display_sequence: MeterTerminal,
111    beat_sequence: MeterTerminal,
112    beam_sequence: MeterTerminal,
113    accent_sequence: MeterTerminal,
114    /// How the signature is drawn where it is not drawn as numbers.
115    #[cfg_attr(feature = "serde", serde(default))]
116    symbol: Option<String>,
117    #[cfg_attr(feature = "serde", serde(default))]
118    symbolize_denominator: bool,
119    #[cfg_attr(feature = "serde", serde(default))]
120    color: crate::display::Color,
121    /// Whether this is an earlier measure's meter standing a second time.
122    #[cfg_attr(feature = "serde", serde(default))]
123    restated: crate::display::Drawn<bool>,
124    #[cfg_attr(feature = "serde", serde(default))]
125    hidden: crate::display::Drawn<bool>,
126    /// A bar length written over the meter's own: music21's
127    /// `_overriddenBarDuration`, which contradicts the meter on purpose.
128    #[cfg_attr(feature = "serde", serde(default))]
129    overridden_bar_duration: Option<Duration>,
130}
131
132impl Default for TimeSignature {
133    /// Returns `4/4`, matching music21's default `TimeSignature()`.
134    fn default() -> Self {
135        Self::common()
136    }
137}
138
139/// The largest numerator a [`TimeSignature`] takes. A meter is built with
140/// a part for each beat it counts, so the limit bounds the work one
141/// signature costs; meters in use count far fewer.
142pub const MAX_NUMERATOR: UnsignedIntegerType = 10_000;
143
144impl TimeSignature {
145    /// Creates a time signature from a numerator and denominator.
146    ///
147    /// Both must be non-zero, and the numerator no more than
148    /// [`MAX_NUMERATOR`]. The denominator need not be a power of two —
149    /// music21 accepts irrational meters such as `4/3`, and so does this.
150    pub fn new(numerator: UnsignedIntegerType, denominator: UnsignedIntegerType) -> Result<Self> {
151        if numerator == 0 {
152            return Err(Error::Meter(
153                "time signature numerator must be non-zero".to_string(),
154            ));
155        }
156        if denominator == 0 {
157            return Err(Error::Meter(
158                "time signature denominator must be non-zero".to_string(),
159            ));
160        }
161        if numerator > MAX_NUMERATOR {
162            return Err(Error::Meter(format!(
163                "time signature numerator {numerator} is more than {MAX_NUMERATOR}"
164            )));
165        }
166        let mut signature = Self {
167            numerator,
168            denominator,
169            favor_compound: favor_compound(numerator, denominator, None),
170            display_sequence: whole_bar(numerator, denominator)?,
171            beat_sequence: whole_bar(numerator, denominator)?,
172            beam_sequence: whole_bar(numerator, denominator)?,
173            accent_sequence: whole_bar(numerator, denominator)?,
174            symbol: None,
175            symbolize_denominator: false,
176            color: crate::display::Drawn(None),
177            restated: crate::display::Drawn(false),
178            hidden: crate::display::Drawn(false),
179            overridden_bar_duration: None,
180        };
181        signature.set_default_partitions()?;
182        Ok(signature)
183    }
184
185    /// How the signature is drawn where it is not drawn as numbers: music21's
186    /// `symbol`, `common` for the C of `4/4` or `cut` for the struck C of
187    /// `2/2`, and nothing where it is written as numbers.
188    pub fn symbol(&self) -> Option<&str> {
189        self.symbol.as_deref()
190    }
191
192    /// Says how the signature is drawn, or that it is written as numbers.
193    pub fn set_symbol(&mut self, symbol: Option<String>) {
194        self.symbol = symbol.filter(|symbol| !symbol.is_empty());
195    }
196
197    /// Whether this is the meter an earlier measure states, standing again
198    /// in a later one, rather than a meter of its own.
199    ///
200    /// music21 holds a meter as an object, and one object may stand in
201    /// several measures: its ABC reader gives a measure the meter in force
202    /// back, the very object, after cutting an overlong measure in two.
203    /// music21's `makeTies` then finds that meter only where it stands last,
204    /// which decides where it cuts, so a reader that restates a meter says
205    /// so here. Two meters differing only in this are equal.
206    pub fn is_restated(&self) -> bool {
207        self.restated.0
208    }
209
210    /// Says whether this is an earlier measure's meter standing again.
211    pub fn set_restated(&mut self, restated: bool) {
212        self.restated.0 = restated;
213    }
214
215    /// Whether the denominator is drawn as a note rather than a number:
216    /// music21's `symbolizeDenominator`.
217    pub fn symbolize_denominator(&self) -> bool {
218        self.symbolize_denominator
219    }
220
221    /// Says whether the denominator is drawn as a note.
222    pub fn set_symbolize_denominator(&mut self, symbolize: bool) {
223        self.symbolize_denominator = symbolize;
224    }
225
226    /// The colour the signature is drawn in, if one was said. Two meters
227    /// differing only in colour are equal.
228    pub fn color(&self) -> Option<&str> {
229        self.color.0.as_deref()
230    }
231
232    /// Sets the colour the signature is drawn in.
233    pub fn set_color(&mut self, color: Option<String>) {
234        self.color.0 = color;
235    }
236
237    /// Whether the signature is left off the page while still in force:
238    /// music21's `style.hideObjectOnPrint`. Two meters differing only in
239    /// this are equal.
240    pub fn is_hidden(&self) -> bool {
241        self.hidden.0
242    }
243
244    /// Says whether the signature is left off the page.
245    pub fn set_hidden(&mut self, hidden: bool) {
246        self.hidden.0 = hidden;
247    }
248
249    /// How the bar is written, before anything divides it: music21's
250    /// `displaySequence`. A meter written additively as `"3/8+2/8"` is two
251    /// parts here, and that is what makes the beats fall where they are
252    /// written rather than where the numerator alone would put them.
253    #[must_use]
254    pub fn display_sequence(&self) -> &MeterTerminal {
255        &self.display_sequence
256    }
257
258    /// How the bar is counted: music21's `beatSequence`, one part per beat,
259    /// each divided again into what the beat is felt in.
260    #[must_use]
261    pub fn beat_sequence(&self) -> &MeterTerminal {
262        &self.beat_sequence
263    }
264
265    /// How the bar is beamed: music21's `beamSequence`, the groups a run of
266    /// short notes is written in.
267    #[must_use]
268    pub fn beam_sequence(&self) -> &MeterTerminal {
269        &self.beam_sequence
270    }
271
272    /// How the bar is weighted: music21's `accentSequence`, one part per
273    /// accent partition, each carrying the weight [`Self::accent_weights`]
274    /// gives it.
275    #[must_use]
276    pub fn accent_sequence(&self) -> &MeterTerminal {
277        &self.accent_sequence
278    }
279
280    /// Whether the bar is felt in compound beats: music21's `favorCompound`,
281    /// which is what counts a `6/8` in two and a `slow 6/8` in six.
282    #[must_use]
283    pub fn favors_compound(&self) -> bool {
284        self.favor_compound
285    }
286
287    /// Counts the bar the way a sequence says: music21's `beatSequence`
288    /// assigned, as `ts.beatSequence = ts.beatSequence.partitioned(2)`.
289    pub fn set_beat_sequence(&mut self, sequence: MeterTerminal) {
290        self.beat_sequence = sequence;
291    }
292
293    /// Beams the bar the way a sequence says: music21's `beamSequence`
294    /// assigned.
295    pub fn set_beam_sequence(&mut self, sequence: MeterTerminal) {
296        self.beam_sequence = sequence;
297    }
298
299    /// Weighs the bar the way a sequence says: music21's `accentSequence`
300    /// assigned.
301    pub fn set_accent_sequence(&mut self, sequence: MeterTerminal) {
302        self.accent_sequence = sequence;
303    }
304
305    /// Writes the bar the way a sequence says: music21's `displaySequence`
306    /// assigned.
307    pub fn set_display_sequence(&mut self, sequence: MeterTerminal) {
308        self.display_sequence = sequence;
309    }
310
311    /// Writes the bar a different way without changing what it counts:
312    /// music21's `setDisplay`.
313    ///
314    /// A bar of `3/4` set to display as `"2/8+2/8+2/8"` is still three
315    /// quarters long and still counted in three; what changes is how it is
316    /// written. The value has to come to the same length as the bar, since a
317    /// bar cannot be written as something it is not.
318    pub fn set_display(&mut self, value: &str) -> Result<()> {
319        let parts = Self::parts(value)?;
320        let denominator = parts
321            .iter()
322            .map(|(_, part)| *part)
323            .max()
324            .unwrap_or(self.denominator);
325        let numerator = parts
326            .iter()
327            .fold(0, |sum: UnsignedIntegerType, (count, part)| {
328                sum.saturating_add(count.saturating_mul(denominator / part))
329            });
330        let display = whole_bar(numerator, denominator)?;
331        if (display.quarter_length() - self.bar_quarter_length()).abs() > OFFSET_TOLERANCE {
332            return Err(Error::Meter(format!(
333                "cannot write a {} bar as {value:?}: that is {} quarter lengths, not {}",
334                self.ratio_string(),
335                display.quarter_length(),
336                self.bar_quarter_length()
337            )));
338        }
339        if parts.len() > 1 {
340            let written: Vec<String> = parts
341                .iter()
342                .map(|(count, part)| format!("{count}/{part}"))
343                .collect();
344            let borrowed: Vec<&str> = written.iter().map(String::as_str).collect();
345            self.display_sequence = display.partitioned_by_parts(&borrowed)?;
346            return Ok(());
347        }
348        self.display_sequence = display;
349        Ok(())
350    }
351
352    /// Divides the beats into `count` parts, leaving each part undivided:
353    /// the `divisions` a meter is built with.
354    ///
355    /// This is not [`Self::set_beat_count`]: music21 partitions the beats
356    /// here and stops, so `TimeSignature("6/8", 2)` is `{3/8+3/8}` where
357    /// counting a `6/8` in two gives `{{1/8+1/8+1/8}+{1/8+1/8+1/8}}`.
358    pub fn divide_beats(&mut self, count: UnsignedIntegerType) -> Result<()> {
359        if count == 0 {
360            return Err(Error::Meter(
361                "a bar cannot be divided into no parts".to_string(),
362            ));
363        }
364        let divided = whole_bar(self.numerator, self.denominator)?
365            .partitioned_by_count(count as usize, false)?;
366        // music21 divides the beats, the accents and the beams alike here,
367        // and leaves the display saying what the bar was written as.
368        self.beat_sequence = divided.clone();
369        self.accent_sequence = divided.clone();
370        self.beam_sequence = divided;
371        Ok(())
372    }
373
374    /// Counts the bar in a different number of beats: music21's settable
375    /// `beatCount`.
376    ///
377    /// The beats are repartitioned and each divided again, so a `6/8`
378    /// counted in six is six eighths rather than two dotted quarters. A
379    /// count the bar cannot be divided into is an error.
380    pub fn set_beat_count(&mut self, count: UnsignedIntegerType) -> Result<()> {
381        if count == 0 {
382            return Err(Error::Meter(
383                "a bar cannot be counted in no beats".to_string(),
384            ));
385        }
386        let mut beats = MeterTerminal::new(self.numerator, self.denominator)?
387            .partitioned_by_count(count as usize, false)?;
388        if beats.len() > 1 {
389            beats = beats.subdivided_partitions_equal(None)?;
390        }
391        self.beat_sequence = beats;
392        Ok(())
393    }
394
395    /// Builds the beam, beat and accent partitions the way music21 does when
396    /// nobody has said how: `_setDefaultBeamPartitions`,
397    /// `_setDefaultBeatPartitions` and `_setDefaultAccentWeights`.
398    fn set_default_partitions(&mut self) -> Result<()> {
399        self.set_default_beam_partitions()?;
400        self.set_default_beat_partitions()?;
401        self.set_default_accent_weights();
402        Ok(())
403    }
404
405    /// music21's `_setDefaultBeamPartitions`: a short bar of short notes is
406    /// beamed all together, and anything else in the groups its numerator is
407    /// felt in.
408    ///
409    /// A meter written additively is beamed by these rules too — music21
410    /// beams `"3/8+2/8"` as `{2/8+3/8}`, by the rule for a five, and not in
411    /// the parts it was written in. One written with its numerators summed,
412    /// `"3+2/8"`, is the exception: it is left in the parts it was written in.
413    fn set_default_beam_partitions(&mut self) -> Result<()> {
414        let numerator = self.numerator;
415        let denominator = self.denominator;
416        if self.beam_sequence.summed_numerator() {
417            return Ok(());
418        }
419        if (denominator == 8 && matches!(numerator, 1..=3))
420            || (denominator == 16 && matches!(numerator, 1..=5))
421            || (denominator == 32 && matches!(numerator, 1..=11))
422        {
423            return Ok(());
424        }
425        let beams = &self.beam_sequence;
426        self.beam_sequence = match numerator {
427            2..=4 => {
428                let mut beams = beams.partitioned_by_count(numerator as usize, false)?;
429                if denominator == 4 {
430                    for index in 0..beams.len() {
431                        let divided = beams.parts()[index].subdivide_by_count(2)?;
432                        beams = beams.set_index(index, divided)?;
433                    }
434                }
435                beams
436            }
437            5 => {
438                let mut beams = beams.partitioned_by_list(&[2, 3])?;
439                if denominator == 4 {
440                    for (index, count) in [2, 3].into_iter().enumerate() {
441                        let divided = beams.parts()[index].subdivide_by_count(count)?;
442                        beams = beams.set_index(index, divided)?;
443                    }
444                }
445                beams
446            }
447            7 => beams.partitioned_by_count(3, false)?,
448            // Every compound numerator is beamed in threes.
449            other if other >= 6 && other.is_multiple_of(3) => {
450                beams.partitioned_by_list(&vec![3; (other / 3) as usize])?
451            }
452            _ => return Ok(()),
453        };
454        Ok(())
455    }
456
457    /// music21's `_setDefaultBeatPartitions`: the top-level count of the bar,
458    /// then each beat divided into what it is felt in.
459    ///
460    /// A meter written additively is counted in the parts it was written in,
461    /// each keeping the note it was written in — `"2/4+3/8"` is counted
462    /// `{{1/4+1/4}+{1/8+1/8+1/8}}`.
463    fn set_default_beat_partitions(&mut self) -> Result<()> {
464        let numerator = self.numerator;
465        let compound = self.favor_compound;
466        let beats = &self.beat_sequence;
467        self.beat_sequence = if self.display_sequence.len() == 1 {
468            match numerator {
469                2 => beats.partitioned_by_count(2, false)?,
470                6 if compound => beats.partitioned_by_count(2, false)?,
471                3 if compound => beats.partitioned_by_count(1, false)?,
472                3 => beats.partitioned_by_list(&[1, 1, 1])?,
473                9 if compound => beats.partitioned_by_list(&[3, 3, 3])?,
474                4 => beats.partitioned_by_count(4, false)?,
475                12 if compound => beats.partitioned_by_count(4, false)?,
476                other if other >= 15 && other.is_multiple_of(3) && compound => {
477                    beats.partitioned_by_list(&vec![3; (other / 3) as usize])?
478                }
479                other => beats.partitioned_by_count(other as usize, false)?,
480            }
481        } else {
482            let written: Vec<String> = self
483                .display_sequence
484                .parts()
485                .iter()
486                .map(|part| format!("{}/{}", part.numerator(), part.denominator()))
487                .collect();
488            let borrowed: Vec<&str> = written.iter().map(String::as_str).collect();
489            beats.partitioned_by_parts(&borrowed)?
490        };
491        if self.beat_sequence.len() > 1 {
492            // music21 forgives a bar written in notes shorter than a 128th
493            // for being too short to divide again, and nothing else.
494            match self.beat_sequence.subdivided_partitions_equal(None) {
495                Ok(divided) => self.beat_sequence = divided,
496                Err(error) if self.denominator >= 128 => {
497                    let _ = error;
498                }
499                Err(error) => return Err(error),
500            }
501        }
502        Ok(())
503    }
504
505    /// music21's `_setDefaultAccentWeights`, read off the weights this meter
506    /// already gives its accent partitions rather than derived a second time
507    /// from a nested hierarchy: one part per weight, carrying that weight.
508    fn set_default_accent_weights(&mut self) {
509        let weights = self.default_accent_weights();
510        let ones = vec![1; weights.len()];
511        let Ok(partitioned) = self.accent_sequence.partitioned_by_list(&ones) else {
512            return;
513        };
514        let weighed: Vec<MeterTerminal> = partitioned
515            .parts()
516            .iter()
517            .zip(weights)
518            .map(|(part, weight)| part.with_weight(weight))
519            .collect();
520        if let Ok(sequence) =
521            MeterTerminal::sequence(partitioned.numerator(), partitioned.denominator(), weighed)
522        {
523            self.accent_sequence = sequence.with_summed_numerator(partitioned.summed_numerator());
524        }
525    }
526
527    /// Parses a `"numerator/denominator"` string such as `"6/8"`.
528    ///
529    /// music21 writes more than a bare ratio here. A word before the ratio
530    /// says how the beat is felt — `"slow 6/8"` is counted in six and
531    /// `"fast 6/8"` in two — and a meter can be written additively, as
532    /// `"3/8+2/8"` or `"3+2/8"`, where a numerator with no denominator of
533    /// its own takes the next one written. What the parts add up to is the
534    /// meter this returns; how they are grouped is [`Self::parts`].
535    pub fn from_ratio_string(ratio: &str) -> Result<Self> {
536        let parts = Self::parts(ratio)?;
537        if parts.iter().any(|(_, part)| *part == 0) {
538            return Err(Error::Meter(format!(
539                "time signature denominator must be non-zero: {ratio}"
540            )));
541        }
542        let word = division_word(ratio);
543        let summed = ratio.split('+').any(|part| !part.contains('/'));
544        let denominator = parts[0].1;
545        if parts.iter().all(|(_, part)| *part == denominator) {
546            let numerator = parts
547                .iter()
548                .fold(0, |sum: UnsignedIntegerType, (count, _)| {
549                    sum.saturating_add(*count)
550                });
551            let mut signature = Self::new(numerator, denominator)?;
552            signature.write_as(&parts, word, summed)?;
553            return Ok(signature);
554        }
555        // Parts measured in different notes: what they come to together is
556        // the meter, over the shortest note any of them is written in.
557        let denominator = parts
558            .iter()
559            .map(|(_, part)| *part)
560            .max()
561            .unwrap_or(denominator);
562        let numerator = parts
563            .iter()
564            .fold(0, |sum: UnsignedIntegerType, (count, part)| {
565                sum.saturating_add(count.saturating_mul(denominator / part))
566            });
567        let mut signature = Self::new(numerator, denominator)?;
568        signature.write_as(&parts, word, summed)?;
569        Ok(signature)
570    }
571
572    /// Records how the meter was written — the parts it was written in, and
573    /// the word saying how it is counted — and rebuilds what depends on
574    /// either.
575    fn write_as(
576        &mut self,
577        parts: &[(UnsignedIntegerType, UnsignedIntegerType)],
578        word: Option<&str>,
579        summed: bool,
580    ) -> Result<()> {
581        self.favor_compound = favor_compound(self.numerator, self.denominator, word);
582        self.beat_sequence = whole_bar(self.numerator, self.denominator)?;
583        self.beam_sequence = whole_bar(self.numerator, self.denominator)?;
584        self.accent_sequence = whole_bar(self.numerator, self.denominator)?;
585        if parts.len() > 1 {
586            // music21 reads every sequence out of the one string, and a
587            // sequence read from its parts weighs one for each of them --
588            // which is not what partitioning a bar into the same parts
589            // gives, since that shares out the one the bar weighed. The
590            // beams and the beats begin as written; the rules by numerator
591            // then either replace those parts or leave them standing.
592            let written = parts
593                .iter()
594                .map(|(count, part)| format!("{count}/{part}"))
595                .collect::<Vec<_>>()
596                .join("+");
597            let loaded = MeterTerminal::from_partition_string(&written)?;
598            self.display_sequence = loaded.clone();
599            self.beat_sequence = loaded.clone();
600            self.beam_sequence = loaded;
601        }
602        // Every sequence is read from the one string, so each says how that
603        // string was written.
604        for sequence in [
605            &mut self.display_sequence,
606            &mut self.beat_sequence,
607            &mut self.beam_sequence,
608            &mut self.accent_sequence,
609        ] {
610            *sequence = sequence.with_summed_numerator(summed);
611        }
612        self.set_default_partitions()
613    }
614
615    /// Whether the meter was written with its numerators summed over one
616    /// denominator, `3+2/8`, rather than part by part: music21's
617    /// `summedNumerator`, which it reads off how the bar is displayed.
618    #[must_use]
619    pub fn summed_numerator(&self) -> bool {
620        self.display_sequence.summed_numerator()
621    }
622
623    /// Says whether the numerators are written summed, which changes how the
624    /// meter is printed and nothing about how it is counted.
625    pub fn set_summed_numerator(&mut self, summed: bool) {
626        self.display_sequence = self.display_sequence.with_summed_numerator(summed);
627    }
628
629    /// The `(numerator, denominator)` pairs a meter string is written in,
630    /// in the order written: music21's `slashMixedToFraction`.
631    ///
632    /// `"3/8+2/8"` is two parts and `"6/8"` is one. A part written as a bare
633    /// numerator takes the denominator of the next part that has one, which
634    /// is how `"3+2/8"` is two eighth-note parts; a string whose last part
635    /// says no denominator at all says nothing about how it is measured, and
636    /// is refused.
637    pub fn parts(ratio: &str) -> Result<Vec<(UnsignedIntegerType, UnsignedIntegerType)>> {
638        let unworded = without_division_word(ratio);
639        let written = unworded.trim();
640        if written.is_empty() {
641            return Err(Error::Meter("a time signature says nothing".to_string()));
642        }
643        let mut pre: Vec<(UnsignedIntegerType, Option<UnsignedIntegerType>)> = Vec::new();
644        for part in written.split('+') {
645            let part = part.trim();
646            match part.split_once('/') {
647                Some((numerator, denominator)) => pre.push((
648                    Self::count(numerator, "numerator", written)?,
649                    Some(Self::count(denominator, "denominator", written)?),
650                )),
651                None => pre.push((Self::count(part, "numerator", written)?, None)),
652            }
653        }
654        let mut out = Vec::with_capacity(pre.len());
655        for (index, (numerator, denominator)) in pre.iter().enumerate() {
656            let denominator = match denominator {
657                Some(denominator) => *denominator,
658                None => pre[index + 1..]
659                    .iter()
660                    .find_map(|(_, later)| *later)
661                    .ok_or_else(|| {
662                        Error::Meter(format!(
663                            "cannot match a denominator to every numerator in {written:?}"
664                        ))
665                    })?,
666            };
667            out.push((*numerator, denominator));
668        }
669        Ok(out)
670    }
671
672    /// One number out of a meter string, with the word music21 allows before
673    /// it — `"slow 6"` is six — taken off first.
674    fn count(part: &str, label: &str, ratio: &str) -> Result<UnsignedIntegerType> {
675        let digits = part
676            .trim()
677            .rsplit(|character: char| character.is_whitespace())
678            .next()
679            .unwrap_or("")
680            .trim();
681        digits
682            .parse::<UnsignedIntegerType>()
683            .map_err(|_| Error::Meter(format!("cannot read a {label} from {part:?} in {ratio:?}")))
684    }
685
686    /// Returns common time, `4/4`.
687    pub fn common() -> Self {
688        Self::new(4, 4).expect("4/4 is a meter")
689    }
690
691    /// Returns cut time, `2/2`.
692    pub fn cut() -> Self {
693        Self::new(2, 2).expect("2/2 is a meter")
694    }
695
696    /// Returns the numerator.
697    pub fn numerator(&self) -> UnsignedIntegerType {
698        self.numerator
699    }
700
701    /// Returns the denominator.
702    pub fn denominator(&self) -> UnsignedIntegerType {
703        self.denominator
704    }
705
706    /// Returns the `"numerator/denominator"` spelling.
707    pub fn ratio_string(&self) -> String {
708        // music21 reads this off the display sequence, so a bar written
709        // additively says what it was written as. The parts come back in
710        // the order they were written, which is what makes `2/8+3/8` and
711        // `3/8+2/8` different meters rather than two spellings of `5/8`.
712        if self.display_sequence.len() > 1 {
713            return self.display_sequence.partition_display();
714        }
715        format!("{}/{}", self.numerator, self.denominator)
716    }
717
718    /// Returns the length of one bar in quarter lengths.
719    pub fn bar_quarter_length(&self) -> FloatType {
720        FloatType::from(self.numerator) * 4.0 / FloatType::from(self.denominator)
721    }
722
723    /// Returns the length of one bar as a [`Duration`]: the one written
724    /// with [`TimeSignature::set_bar_duration`] where there is one, else the
725    /// meter's own.
726    pub fn bar_duration(&self) -> Duration {
727        if let Some(written) = &self.overridden_bar_duration {
728            return written.clone();
729        }
730        Duration::new(self.bar_quarter_length())
731            .expect("a non-zero numerator and denominator give a positive finite bar length")
732    }
733
734    /// Writes a bar length over the meter's own, or clears it with `None`:
735    /// music21's `barDuration` setter. Only the bar this meter reports
736    /// changes; its beats and partitions stay the meter's.
737    ///
738    /// ```
739    /// use music21::{Duration, TimeSignature};
740    ///
741    /// let mut meter = TimeSignature::new(3, 8)?;
742    /// meter.set_bar_duration(Some(Duration::new(1.75)?));
743    /// assert_eq!(meter.bar_duration().quarter_length(), 1.75);
744    /// # Ok::<(), music21::Error>(())
745    /// ```
746    pub fn set_bar_duration(&mut self, written: Option<Duration>) {
747        self.overridden_bar_duration = written;
748    }
749
750    /// The bar length written over the meter's own with
751    /// [`TimeSignature::set_bar_duration`], if any.
752    pub fn written_bar_duration(&self) -> Option<&Duration> {
753        self.overridden_bar_duration.as_ref()
754    }
755
756    /// Where an element falls in the bar this meter measures: music21's
757    /// `getMeasureOffsetOrMeterModulusOffset`, given the two offsets music21
758    /// reads off the stream.
759    ///
760    /// `element_offset` is the element's offset in its measure, or in its
761    /// stream where it has no measure; `meter_offset` is the meter's own.
762    /// Still inside the bar, the element's offset is the answer. Past it,
763    /// the meter's place is taken off and the rest wraps at the bar:
764    ///
765    /// ```text
766    ///   3/4 at 0:  element at 4.0  ->  (4.0 - 0.0) % 3.0 = 1.0
767    ///   3/4 at 1:  element at 2.5  ->  (2.5 - 1.0) % 3.0 = 1.5
768    /// ```
769    pub fn offset_in_bar(&self, element_offset: FloatType, meter_offset: FloatType) -> FloatType {
770        // music21 wraps at `barDuration`, a length written over the meter's
771        // own included.
772        let bar = self.bar_duration().quarter_length();
773
774        // music21 adds to test and subtracts to wrap; the two differ where
775        // the meter does not start the bar.
776        // music21 counts in fractions, so a meter at a third of a beat
777        // still wraps on whole bars.
778        let op_frac = crate::makenotation::op_frac;
779        if op_frac(element_offset + meter_offset) < bar {
780            return element_offset;
781        }
782        op_frac(op_frac(element_offset - meter_offset).rem_euclid(bar))
783    }
784
785    /// Returns how many beats one bar carries.
786    ///
787    /// This is music21's `beatCount`, which follows the numerator rather than
788    /// the denominator — except at `3`, where `3/4` is three beats but `3/8` is
789    /// one.
790    pub fn beat_count(&self) -> UnsignedIntegerType {
791        self.beat_sequence.len() as UnsignedIntegerType
792    }
793
794    /// Returns music21's name for the beat count, such as `"Duple"`.
795    ///
796    /// Counts above eight are spelled as `"<n>-uple"`, as music21 does.
797    pub fn beat_count_name(&self) -> String {
798        partition_name(self.beat_count() as usize)
799    }
800
801    /// Returns the length of the first beat in quarter lengths: music21's
802    /// `beatDuration`. Where the beats differ in length, as in `3/16+1/4`,
803    /// this is the first of them; [`Self::beat_duration_at`] reads any beat.
804    pub fn beat_quarter_length(&self) -> FloatType {
805        let (start, end) = self.beat_spans()[0];
806        end - start
807    }
808
809    /// Returns the length of the first beat as a [`Duration`].
810    pub fn beat_duration(&self) -> Duration {
811        Duration::new(self.beat_quarter_length())
812            .expect("a beat of a meter is a positive finite length")
813    }
814
815    /// Returns how the beat subdivides.
816    pub fn beat_division(&self) -> BeatDivision {
817        let parts = self.beat_sequence.parts();
818        if parts.len() <= 1 {
819            return BeatDivision::Other;
820        }
821        let mut counts = parts.iter().map(MeterTerminal::len);
822        let Some(first) = counts.next() else {
823            return BeatDivision::Other;
824        };
825        if first == 0 || !counts.all(|count| count == first) {
826            // The beats of a bar written additively need not divide alike;
827            // music21 reports such a meter as Other and counts one.
828            return BeatDivision::Other;
829        }
830        match first {
831            2 => BeatDivision::Simple,
832            3 => BeatDivision::Compound,
833            _ => BeatDivision::Other,
834        }
835    }
836
837    /// Returns the number of divisions in one beat.
838    pub fn beat_division_count(&self) -> UnsignedIntegerType {
839        self.beat_division().count()
840    }
841
842    /// Returns `true` when beats divide in three.
843    pub fn is_compound(&self) -> bool {
844        self.beat_division() == BeatDivision::Compound
845    }
846
847    /// Returns music21's `classification`, such as `"Compound Duple"`.
848    pub fn classification(&self) -> String {
849        format!(
850            "{} {}",
851            self.beat_division().music21_name(),
852            self.beat_count_name()
853        )
854    }
855
856    /// Returns music21's `beatDivisionCountName`: `Simple`, `Compound` or
857    /// `Other`.
858    pub fn beat_division_count_name(&self) -> &'static str {
859        self.beat_division().music21_name()
860    }
861
862    /// Returns whether two time signatures have the same numerator and
863    /// denominator: music21's `ratioEqual`, so `4/4` and `2/2` differ.
864    pub fn ratio_equal(&self, other: &TimeSignature) -> bool {
865        self.numerator == other.numerator && self.denominator == other.denominator
866    }
867
868    /// Returns how many quarter lengths one unit of the denominator lasts:
869    /// `0.5` in `6/8`, `2.0` in `2/2`.
870    pub fn beat_length_to_quarter_length_ratio(&self) -> FloatType {
871        4.0 / FloatType::from(self.denominator)
872    }
873
874    /// Returns how many denominator units make one quarter length, the
875    /// inverse of [`Self::beat_length_to_quarter_length_ratio`].
876    pub fn quarter_length_to_beat_length_ratio(&self) -> FloatType {
877        FloatType::from(self.denominator) / 4.0
878    }
879
880    /// Returns the quarter length of each division of one beat, in order:
881    /// two eighths in `4/4`, three in `6/8`, the whole dotted-quarter beat
882    /// in `3/8` where the beat does not divide.
883    ///
884    /// Read off the beat sequence as music21 reads it: the divisions of
885    /// every beat must agree, but the beats need not, so `2+3/8` divides
886    /// into eighths though its beats are a quarter and a dotted quarter.
887    ///
888    /// # Errors
889    ///
890    /// Beats that divide differently, as the quarters and eighths of
891    /// `2/4+3/8` do, which music21 refuses too.
892    pub fn beat_division_quarter_lengths(&self) -> Result<Vec<FloatType>> {
893        let beat_sequence = self.beat_sequence();
894        let beats = match beat_sequence.parts() {
895            [] => std::slice::from_ref(beat_sequence),
896            beats => beats,
897        };
898
899        // A beat with parts divides into them; one without is its own
900        // division.
901        let divisions = |beat: &MeterTerminal| -> Vec<FloatType> {
902            match beat.parts() {
903                [] => vec![beat.quarter_length()],
904                parts => parts.iter().map(MeterTerminal::quarter_length).collect(),
905            }
906        };
907
908        let every: Vec<FloatType> = beats.iter().flat_map(divisions).collect();
909        if every.windows(2).any(|pair| pair[0] != pair[1]) {
910            return Err(Error::Meter(format!(
911                "non uniform beat division: {every:?}"
912            )));
913        }
914        Ok(beats.first().map(divisions).unwrap_or_default())
915    }
916
917    /// Returns [`Self::beat_division_quarter_lengths`] as durations: music21's
918    /// `beatDivisionDurations`.
919    pub fn beat_division_durations(&self) -> Result<Vec<Duration>> {
920        self.beat_division_quarter_lengths()?
921            .into_iter()
922            .map(Duration::new)
923            .collect()
924    }
925
926    /// Returns each division of the beat halved: music21's
927    /// `beatSubDivisionDurations`, four sixteenths in `4/4`.
928    pub fn beat_sub_division_durations(&self) -> Result<Vec<Duration>> {
929        let mut out = Vec::new();
930        for quarter_length in self.beat_division_quarter_lengths()? {
931            let half = Duration::new(quarter_length / 2.0)?;
932            out.push(half.clone());
933            out.push(half);
934        }
935        Ok(out)
936    }
937
938    /// Returns the quarter-length offset of a one-based, possibly fractional
939    /// beat: music21's `getOffsetFromBeat`, so beat `2.5` of `4/4` is `1.5`
940    /// and beat `1.5` of `6/8` is `0.75`. A beat past the bar is an error.
941    pub fn offset_from_beat(&self, beat: FloatType) -> Result<FloatType> {
942        let whole = beat.floor();
943        if !beat.is_finite() || whole < 1.0 || whole > FloatType::from(self.beat_count()) {
944            return Err(Error::Meter(format!(
945                "requested beat value ({beat}) not found in the {} beats of {}",
946                self.beat_count(),
947                self.ratio_string()
948            )));
949        }
950        let (start, end) = self.beat_spans()[whole as usize - 1];
951        let fraction = snapped_fraction(beat - whole);
952        Ok(start + fraction * (end - start))
953    }
954
955    /// Returns the one-based beat containing `offset` and how far into that
956    /// beat it lies, in quarter lengths: music21's `getBeatProgress`.
957    pub fn beat_progress(&self, offset: FloatType) -> Result<(UnsignedIntegerType, FloatType)> {
958        let index = self.beat_index(offset)?;
959        let (start, _) = self.beat_spans()[index];
960        // Through `opFrac`, as music21's: a third of a beat is a sixth.
961        Ok((
962            index as UnsignedIntegerType + 1,
963            crate::makenotation::op_frac(offset - start),
964        ))
965    }
966
967    /// Returns the position within the bar as a fractional beat: music21's
968    /// `getBeatProportion`, `2.5` for the second eighth of beat two in `4/4`
969    /// and `1.333…` for the second eighth of `6/8`.
970    pub fn beat_proportion(&self, offset: FloatType) -> Result<FloatType> {
971        let (beat, progress) = self.beat_progress(offset)?;
972        let (start, end) = self.beat_spans()[beat as usize - 1];
973        Ok(crate::makenotation::op_frac(
974            FloatType::from(beat) + progress / (end - start),
975        ))
976    }
977
978    /// Returns [`Self::beat_proportion`] the way music21's
979    /// `getBeatProportionStr` writes it: the beat alone on the beat, otherwise
980    /// the beat and the fraction of it elapsed, `2 1/2`, with the fraction's
981    /// denominator limited to 16.
982    pub fn beat_proportion_string(&self, offset: FloatType) -> Result<String> {
983        let (beat, progress) = self.beat_progress(offset)?;
984        let (start, end) = self.beat_spans()[beat as usize - 1];
985        let proportion = progress / (end - start);
986        if proportion == 0.0 {
987            return Ok(beat.to_string());
988        }
989        let (numerator, denominator) = closest_fraction(proportion, 16);
990        Ok(format!("{beat} {numerator}/{denominator}"))
991    }
992
993    /// Where each beat starts and ends, in quarter lengths from the start of
994    /// the bar. The beats of a meter written additively are not all the same
995    /// length, so this is read off the beat sequence rather than divided out.
996    fn beat_spans(&self) -> Vec<(FloatType, FloatType)> {
997        let mut spans = Vec::new();
998        let mut position = 0.0;
999        for part in self.beat_sequence.parts() {
1000            let end = position + part.quarter_length();
1001            spans.push((position, end));
1002            position = end;
1003        }
1004        if spans.is_empty() {
1005            spans.push((0.0, self.bar_quarter_length()));
1006        }
1007        spans
1008    }
1009
1010    /// How long the beat holding an offset is: music21's `getBeatDuration`.
1011    ///
1012    /// A meter written additively answers differently along the bar — the
1013    /// first beat of `2/4+3/8` is two quarters long and the second is three
1014    /// eighths.
1015    pub fn beat_duration_at(&self, offset: FloatType) -> Result<Duration> {
1016        let index = self.beat_index(offset)?;
1017        let (start, end) = self.beat_spans()[index];
1018        Duration::new(end - start)
1019    }
1020
1021    /// Which beat holds an offset, counted from nought.
1022    fn beat_index(&self, offset: FloatType) -> Result<usize> {
1023        if !offset.is_finite() || offset < 0.0 || offset >= self.bar_quarter_length() {
1024            return Err(Error::Meter(format!(
1025                "offset {offset} is outside a {} bar of {} quarter lengths",
1026                self.ratio_string(),
1027                self.bar_quarter_length()
1028            )));
1029        }
1030        let spans = self.beat_spans();
1031        for (index, (start, end)) in spans.iter().enumerate() {
1032            let _ = start;
1033            if offset < end - OFFSET_TOLERANCE {
1034                return Ok(index);
1035            }
1036        }
1037        Ok(spans.len() - 1)
1038    }
1039
1040    /// Returns the quarter-length offset of each beat within one bar.
1041    pub fn beat_offsets(&self) -> Vec<FloatType> {
1042        self.beat_spans()
1043            .into_iter()
1044            .map(|(start, _)| start)
1045            .collect()
1046    }
1047
1048    /// Returns the one-based beat containing `offset` quarter lengths into a bar.
1049    ///
1050    /// Matches music21's `getBeat`. Offsets at or beyond the end of the bar are
1051    /// rejected rather than wrapping.
1052    pub fn beat_at_offset(&self, offset: FloatType) -> Result<UnsignedIntegerType> {
1053        if !offset.is_finite() || offset < 0.0 || offset >= self.bar_quarter_length() {
1054            return Err(Error::Meter(format!(
1055                "offset {offset} is outside a {} bar of {} quarter lengths",
1056                self.ratio_string(),
1057                self.bar_quarter_length()
1058            )));
1059        }
1060        Ok(self.beat_index(offset)? as UnsignedIntegerType + 1)
1061    }
1062}
1063
1064/// The fraction closest to `value` with a denominator no larger than
1065/// `max_denominator`, as Python's `Fraction.limit_denominator` finds it for
1066/// the proportions music21 prints. Ties go to the smaller denominator.
1067fn closest_fraction(value: FloatType, max_denominator: u32) -> (u32, u32) {
1068    let mut best = (value.round() as u32, 1);
1069    let mut best_error = (value - value.round()).abs();
1070    for denominator in 2..=max_denominator {
1071        let numerator = (value * FloatType::from(denominator)).round();
1072        let error = (value - numerator / FloatType::from(denominator)).abs();
1073        if error < best_error {
1074            best = (numerator as u32, denominator);
1075            best_error = error;
1076        }
1077    }
1078    best
1079}
1080
1081impl std::fmt::Display for TimeSignature {
1082    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1083        f.write_str(&self.ratio_string())
1084    }
1085}
1086
1087/// How far an offset may sit from a partition boundary and still be read as
1088/// on it.
1089const OFFSET_TOLERANCE: FloatType = 1e-9;
1090
1091/// The shortest accent partition music21 can write, a 128th note.
1092const SHORTEST_PARTITION: FloatType = 4.0 / 128.0;
1093
1094/// The longest, a whole note.
1095const LONGEST_PARTITION: FloatType = 4.0;
1096
1097impl TimeSignature {
1098    /// How music21's default accent hierarchy divides the bar, three levels
1099    /// deep: how many parts the bar divides into, how many each of those
1100    /// divides into, and how many each of those divides into.
1101    ///
1102    /// music21 builds the hierarchy by subdividing a `MeterSequence`. The top
1103    /// level takes the beat count, except that one, two, four, eight, sixteen
1104    /// and thirty-two beats divide in two and three beats divide in three; a
1105    /// single beat takes the numerator's place in that rule. Below that, each
1106    /// span divides the way music21 divides a span by default: two or more
1107    /// triples into its triples, an even count of anything in two, a single
1108    /// unit in two, and an odd count into its units.
1109    fn accent_hierarchy(
1110        &self,
1111    ) -> (
1112        UnsignedIntegerType,
1113        UnsignedIntegerType,
1114        UnsignedIntegerType,
1115    ) {
1116        let beats = self.beat_count();
1117        let first = if beats > 1 { beats } else { self.numerator };
1118        let top = match first {
1119            1 | 2 | 4 | 8 | 16 | 32 => 2,
1120            3 => 3,
1121            other => other,
1122        };
1123        // A unit too short to count is shorter than a 128th, so the bar is
1124        // one partition.
1125        let Some((span, unit)) = split_span(self.numerator, self.denominator, top) else {
1126            return (1, 1, 1);
1127        };
1128        let second = default_division(span, unit);
1129        let Some((span, unit)) = split_span(span, unit, second) else {
1130            return (1, 1, 1);
1131        };
1132        let third = default_division(span, unit);
1133        // music21 partitions the accent sequence into that many equal parts
1134        // written as whole numbers of a note value, and gives up — leaving
1135        // the bar as one partition — when a part would be longer than a
1136        // whole note or shorter than a 128th.
1137        let partition = self.bar_quarter_length() / FloatType::from(top * second * third);
1138        if !(SHORTEST_PARTITION..=LONGEST_PARTITION).contains(&partition) {
1139            return (1, 1, 1);
1140        }
1141        (top, second, third)
1142    }
1143
1144    /// The length of one partition of music21's default accent hierarchy, the
1145    /// finest level the accent weights are given at.
1146    pub fn accent_partition_quarter_length(&self) -> FloatType {
1147        let parts = self.accent_sequence.parts();
1148        if parts.len() > 1 {
1149            return parts[0].quarter_length();
1150        }
1151        let (top, second, third) = self.accent_hierarchy();
1152        self.bar_quarter_length() / FloatType::from(top * second * third)
1153    }
1154
1155    /// The accent weight of every partition of the bar, music21's default
1156    /// `accentSequence`: `1.0` on the downbeat, halving with every level of
1157    /// the hierarchy a partition's start is not a boundary of, so `4/4` reads
1158    /// `1.0, 0.125, 0.25, 0.125, 0.5, 0.125, 0.25, 0.125`.
1159    pub fn accent_weights(&self) -> Vec<FloatType> {
1160        let carried: Vec<FloatType> = self
1161            .accent_sequence
1162            .parts()
1163            .iter()
1164            .map(MeterTerminal::weight)
1165            .collect();
1166        if carried.len() > 1 {
1167            return carried;
1168        }
1169        self.default_accent_weights()
1170    }
1171
1172    /// The weights music21's default hierarchy gives the bar, which is what
1173    /// the accent sequence is built carrying. Kept apart from
1174    /// [`Self::accent_weights`], which reads the sequence, so that weights a
1175    /// caller has set are the ones read back.
1176    fn default_accent_weights(&self) -> Vec<FloatType> {
1177        if !self.beat_sequence.is_uniform_partition(0)
1178            && let Some(weights) = self.accent_weights_from_the_beats()
1179        {
1180            return weights;
1181        }
1182        let (top, second, third) = self.accent_hierarchy();
1183        let count = top * second * third;
1184        (0..count)
1185            .map(|index| {
1186                let depth = 1
1187                    + UnsignedIntegerType::from(index.is_multiple_of(third))
1188                    + UnsignedIntegerType::from(index.is_multiple_of(second * third))
1189                    + UnsignedIntegerType::from(index == 0);
1190                FloatType::from(2u32.pow(depth - 1)) / 8.0
1191            })
1192            .collect()
1193    }
1194
1195    /// The default weights of a bar whose beats are not all one length,
1196    /// `3+2/8` say, which no rule over the numerator can give: the bar is
1197    /// nested three levels deep beginning from the beats as they are, and
1198    /// each partition weighs by how many of those levels begin where it does.
1199    /// This is the branch of music21's `_setDefaultAccentWeights` that is
1200    /// handed the beat sequence itself.
1201    ///
1202    /// `None` where the bar cannot be nested that far, which music21 also
1203    /// gives up on; the rule for a uniform bar answers then.
1204    fn accent_weights_from_the_beats(&self) -> Option<Vec<FloatType>> {
1205        let nested = MeterTerminal::new(self.numerator, self.denominator)
1206            .ok()?
1207            .subdivided_nested_hierarchy_by(3, &self.beat_sequence, true)
1208            .ok()?;
1209        let levels = nested.depth();
1210        if levels == 0 {
1211            return None;
1212        }
1213        let starts: Vec<Vec<FloatType>> = (0..levels)
1214            .map(|level| {
1215                nested
1216                    .level_span(level)
1217                    .into_iter()
1218                    .map(|(start, _)| start)
1219                    .collect()
1220            })
1221            .collect();
1222        // A partition of the finest level weighs by how many levels have a
1223        // part beginning where it begins.
1224        let depths: Vec<usize> = starts[levels - 1]
1225            .iter()
1226            .map(|start| {
1227                starts
1228                    .iter()
1229                    .filter(|level| {
1230                        level
1231                            .iter()
1232                            .any(|other| (other - start).abs() < OFFSET_TOLERANCE)
1233                    })
1234                    .count()
1235            })
1236            .collect();
1237        let deepest = depths.iter().copied().max()?;
1238        Some(
1239            depths
1240                .into_iter()
1241                .map(|depth| {
1242                    FloatType::from(2u32.pow(depth as u32 - 1))
1243                        / FloatType::from(2u32.pow(deepest as u32 - 1))
1244                })
1245                .collect(),
1246        )
1247    }
1248
1249    /// Whether an offset in quarter lengths starts an accent partition:
1250    /// music21's `getAccent`, which is false for any offset off the grid,
1251    /// beyond the bar included.
1252    pub fn accent(&self, offset: FloatType) -> bool {
1253        let parts = match self.accent_sequence.parts() {
1254            [] => std::slice::from_ref(&self.accent_sequence),
1255            parts => parts,
1256        };
1257        let mut position = 0.0;
1258        for part in parts {
1259            if (position - offset).abs() < OFFSET_TOLERANCE {
1260                return true;
1261            }
1262            position += part.quarter_length();
1263        }
1264        false
1265    }
1266
1267    /// The accent weight at an offset in quarter lengths: music21's
1268    /// `getAccentWeight`, the weight of the partition the offset falls in.
1269    /// An offset outside the bar is an error.
1270    pub fn accent_weight(&self, offset: FloatType) -> Result<FloatType> {
1271        self.accent_weight_with(offset, false, false)
1272    }
1273
1274    /// The accent weight at an offset, read at a level of the accent
1275    /// sequence: music21's `getAccentWeight` with its `level`.
1276    pub fn accent_weight_at_level(
1277        &self,
1278        offset: FloatType,
1279        level: usize,
1280        force_position_match: bool,
1281        permit_meter_modulus: bool,
1282    ) -> Result<FloatType> {
1283        let bar = self.bar_quarter_length();
1284        let offset = if permit_meter_modulus {
1285            offset.rem_euclid(bar)
1286        } else {
1287            offset
1288        };
1289        let offset = offset_within(offset, bar)?;
1290        let terminals = self.accent_sequence.level_list(level, true);
1291        if terminals.len() <= 1 {
1292            return self.accent_weight_with(offset, force_position_match, permit_meter_modulus);
1293        }
1294        let spans = self.accent_sequence.level_span(level);
1295        let smallest = terminals
1296            .iter()
1297            .map(MeterTerminal::weight)
1298            .fold(FloatType::INFINITY, FloatType::min);
1299        for (index, (start, end)) in spans.iter().enumerate() {
1300            if offset < end - OFFSET_TOLERANCE {
1301                if force_position_match && (offset - start).abs() >= OFFSET_TOLERANCE {
1302                    return Ok(smallest * 0.5);
1303                }
1304                return Ok(terminals[index].weight());
1305            }
1306        }
1307        Ok(terminals[terminals.len() - 1].weight())
1308    }
1309
1310    /// Weighs the accent partitions of a level, looping the weights given
1311    /// over them: music21's `setAccentWeight`.
1312    pub fn set_accent_weight(&mut self, weights: &[FloatType], level: usize) -> Result<()> {
1313        self.accent_sequence = self.accent_sequence.with_level_weight(level, weights)?;
1314        Ok(())
1315    }
1316
1317    /// [`Self::accent_weight`] with music21's two options. With
1318    /// `force_position_match` an offset that does not start a partition
1319    /// answers half the smallest weight rather than its partition's; with
1320    /// `permit_meter_modulus` an offset beyond the bar is read within it.
1321    pub fn accent_weight_with(
1322        &self,
1323        offset: FloatType,
1324        force_position_match: bool,
1325        permit_meter_modulus: bool,
1326    ) -> Result<FloatType> {
1327        let bar = self.bar_quarter_length();
1328        let offset = if permit_meter_modulus {
1329            offset.rem_euclid(bar)
1330        } else {
1331            offset
1332        };
1333        let offset = offset_within(offset, bar)?;
1334        let weights = self.accent_weights();
1335        let partition = self.accent_partition_quarter_length();
1336        let index = ((offset + OFFSET_TOLERANCE) / partition).floor() as usize;
1337        let index = index.min(weights.len() - 1);
1338        if force_position_match
1339            && (offset - index as FloatType * partition).abs() >= OFFSET_TOLERANCE
1340        {
1341            let smallest = weights
1342                .iter()
1343                .copied()
1344                .fold(FloatType::INFINITY, FloatType::min);
1345            return Ok(smallest * 0.5);
1346        }
1347        Ok(weights[index])
1348    }
1349
1350    /// The mean accent weight of what a stream holds: music21's
1351    /// `averageBeatStrength`, each element weighed where it falls in the
1352    /// bar, with an element off the accent grid counting half the smallest
1353    /// weight. Only the stream's own elements are weighed, not what the
1354    /// measures or voices inside it hold; `notes_only` weighs its notes and
1355    /// chords alone. A stream with nothing to weigh weighs nothing.
1356    pub fn average_beat_strength(&self, stream: &crate::Stream, notes_only: bool) -> FloatType {
1357        let bar = self.bar_quarter_length();
1358        let offsets: Vec<FloatType> = stream
1359            .events()
1360            .iter()
1361            .filter(|event| !notes_only || crate::makenotation::is_not_rest(event.element()))
1362            .map(crate::stream::StreamEvent::offset)
1363            .collect();
1364        if offsets.is_empty() {
1365            return 0.0;
1366        }
1367        let total: FloatType = offsets
1368            .iter()
1369            .map(|offset| {
1370                self.accent_weight_with(offset.rem_euclid(bar), true, false)
1371                    .unwrap_or(0.0)
1372            })
1373            .sum();
1374        total / offsets.len() as FloatType
1375    }
1376
1377    /// How many levels of the beat hierarchy start at an offset: music21's
1378    /// `getBeatDepth`, which quantizes the offset to the beat's division and
1379    /// then counts the beat level and the division level. A meter of one beat
1380    /// has one level and answers one everywhere in the bar; an offset outside
1381    /// the bar is an error.
1382    pub fn beat_depth(&self, offset: FloatType) -> Result<u8> {
1383        let bar = self.bar_quarter_length();
1384        if offset.is_nan() || offset < 0.0 || offset >= bar {
1385            return Err(Error::Meter(format!(
1386                "cannot access from qLenPos {}",
1387                offset_repr(offset)
1388            )));
1389        }
1390        let depth = self
1391            .beat_sequence
1392            .offset_to_depth(offset, crate::meter::OffsetAlign::Quantize)?;
1393        Ok(depth as u8)
1394    }
1395}
1396
1397/// A fractional beat read as the fraction it suggests: music21's
1398/// `addFloatPrecision`, which snaps a third, two thirds, a sixth or five
1399/// sixths written as decimals onto the fraction itself.
1400///
1401/// It is what makes the offset of beat 2.33 the same as the offset of beat
1402/// two and a third.
1403#[must_use]
1404pub fn snapped_fraction(value: FloatType) -> FloatType {
1405    const GRAIN: FloatType = 1e-2;
1406    let thirds = [1.0 / 3.0, 2.0 / 3.0, 1.0 / 6.0, 5.0 / 6.0];
1407    for candidate in thirds {
1408        if (value - candidate).abs() <= GRAIN {
1409            return candidate;
1410        }
1411    }
1412    value
1413}
1414
1415/// One of a run of notes to be beamed: where it sits in the bar, how long it
1416/// lasts, what it is written as, and whether it sounds.
1417///
1418/// A rest is beamed alongside the notes — music21 works its beams out and
1419/// then declines to write them on it — so what matters here is the written
1420/// value and whether the thing sounds, not what kind of object it is.
1421#[derive(Clone, Copy, Debug, PartialEq)]
1422pub struct BeamedNote {
1423    /// Where it starts, in quarter lengths from the start of its measure.
1424    pub offset: FloatType,
1425    /// How long it lasts, in quarter lengths.
1426    pub quarter_length: FloatType,
1427    /// The value it is written as, which says how many beams it can carry.
1428    pub duration_type: DurationType,
1429    /// Whether it sounds. A rest carries no beam however it is written.
1430    pub sounds: bool,
1431}
1432
1433impl TimeSignature {
1434    /// Beams a run of notes: music21's `getBeams`.
1435    ///
1436    /// The notes are taken as adjoining, which is how music21 takes them —
1437    /// their offsets are read only against `measure_start_offset`, for a run
1438    /// that begins part way through a bar. `measure_padding` is the measure's
1439    /// `paddingRight` where the run came from one, and `None` where it did
1440    /// not; a run that ends an incomplete measure does not get its last beam
1441    /// stopped.
1442    ///
1443    /// A run of one is beamed as nothing at all, as music21 does.
1444    pub fn beams_for(
1445        &self,
1446        notes: &[BeamedNote],
1447        measure_start_offset: FloatType,
1448        measure_padding: Option<FloatType>,
1449    ) -> Result<Vec<Option<Beams>>> {
1450        if notes.len() <= 1 {
1451            return Ok(notes.iter().map(|_| None).collect());
1452        }
1453
1454        // music21's `naiveBeams`: the fullest set of beams each written value
1455        // can carry, with what each one does left undecided.
1456        let mut beamed: Vec<Option<Beams>> = notes
1457            .iter()
1458            .map(|note| Beams::naive(Some(note.duration_type), note.sounds))
1459            .collect();
1460        crate::notation::remove_sandwiched_unbeamables(&mut beamed);
1461
1462        for depth in 0..Beams::LEVELS {
1463            for index in 0..notes.len() {
1464                self.fix_one_beam(
1465                    &mut beamed,
1466                    notes,
1467                    index,
1468                    depth,
1469                    measure_start_offset,
1470                    measure_padding,
1471                )?;
1472            }
1473        }
1474
1475        crate::notation::sanitize_partial_beams(&mut beamed);
1476        crate::notation::merge_connecting_partial_beams(&mut beamed);
1477        Ok(beamed)
1478    }
1479
1480    /// What one note's beam does at one depth: music21's
1481    /// `fixBeamsOneElementDepth`.
1482    fn fix_one_beam(
1483        &self,
1484        beamed: &mut [Option<Beams>],
1485        notes: &[BeamedNote],
1486        index: usize,
1487        depth: usize,
1488        measure_start_offset: FloatType,
1489        measure_padding: Option<FloatType>,
1490    ) -> Result<()> {
1491        let beam_number = depth as u32 + 1;
1492        let carries = |beams: Option<&Beams>| {
1493            beams.is_some_and(|beams| {
1494                beams
1495                    .numbers()
1496                    .into_iter()
1497                    .flatten()
1498                    .any(|n| n == beam_number)
1499            })
1500        };
1501        if !carries(beamed[index].as_ref()) {
1502            return Ok(());
1503        }
1504
1505        let note = notes[index];
1506        let start = note.offset + measure_start_offset;
1507        let end = start + note.quarter_length;
1508        let start_next = end;
1509
1510        let is_first = index == 0;
1511        let is_last = index + 1 == notes.len();
1512
1513        // Everything the neighbours are asked, read before this one is
1514        // written to: music21 reads them off a list it is editing.
1515        let previous_is_none = is_first || beamed[index - 1].is_none();
1516        let next_is_none = is_last || beamed[index + 1].is_none();
1517        let previous_carries = !is_first && carries(beamed[index - 1].as_ref());
1518        let next_carries = !is_last && carries(beamed[index + 1].as_ref());
1519        let previous_broke = !is_first
1520            && beamed[index - 1].as_ref().is_some_and(|beams| {
1521                beams.by_number(beam_number).is_some_and(|beam| {
1522                    matches!(beam.beam_type(), Some(BeamType::Stop))
1523                        || (matches!(beam.beam_type(), Some(BeamType::PartialBeam))
1524                            && beam.direction() == Some(crate::notation::BeamDirection::Left))
1525                })
1526            });
1527
1528        let archetype = self.beam_sequence.level(depth, true)?;
1529        let (span_start, span_end) = archetype.offset_to_span(start, false)?;
1530        let span_next_start = if next_is_none {
1531            0.0
1532        } else {
1533            archetype.offset_to_span(start_next, false)?.0
1534        };
1535
1536        let same = |a: FloatType, b: FloatType| (a - b).abs() < OFFSET_TOLERANCE;
1537
1538        // A note that fills its span exactly is not beamed at that level.
1539        if same(end, span_end)
1540            && (same(start, span_start) || (previous_is_none && beam_number == 1))
1541        {
1542            beamed[index] = None;
1543            return Ok(());
1544        }
1545
1546        let ends_the_measure = is_last && measure_padding.is_none_or(|padding| padding == 0.0);
1547
1548        let (beam_type, direction) = if is_first && measure_start_offset == 0.0 {
1549            if next_is_none || !next_carries {
1550                (
1551                    BeamType::PartialBeam,
1552                    Some(crate::notation::BeamDirection::Right),
1553                )
1554            } else {
1555                (BeamType::Start, None)
1556            }
1557        } else if ends_the_measure {
1558            if previous_is_none || !previous_carries {
1559                (
1560                    BeamType::PartialBeam,
1561                    Some(crate::notation::BeamDirection::Left),
1562                )
1563            } else {
1564                (BeamType::Stop, None)
1565            }
1566        } else if previous_is_none || !previous_carries {
1567            // Neither the first nor the last, and nothing to beam back to.
1568            if beam_number == 1 && next_is_none {
1569                beamed[index] = None;
1570                return Ok(());
1571            } else if (next_is_none && beam_number > 1) || start_next >= span_end - OFFSET_TOLERANCE
1572            {
1573                // music21 writes these as two branches. They answer alike,
1574                // and the second subsumes the first: with nothing after it,
1575                // a note runs to the end of its span or past it.
1576                (
1577                    BeamType::PartialBeam,
1578                    Some(crate::notation::BeamDirection::Left),
1579                )
1580            } else if next_is_none || !next_carries {
1581                (
1582                    BeamType::PartialBeam,
1583                    Some(crate::notation::BeamDirection::Right),
1584                )
1585            } else {
1586                (BeamType::Start, None)
1587            }
1588        } else if previous_broke {
1589            if next_is_none {
1590                (
1591                    BeamType::PartialBeam,
1592                    Some(crate::notation::BeamDirection::Left),
1593                )
1594            } else if next_carries {
1595                (BeamType::Start, None)
1596            } else {
1597                (
1598                    BeamType::PartialBeam,
1599                    Some(crate::notation::BeamDirection::Right),
1600                )
1601            }
1602        } else if next_is_none || !next_carries {
1603            (BeamType::Stop, None)
1604        } else if start_next < span_end - OFFSET_TOLERANCE {
1605            (BeamType::Continue, None)
1606        } else if start_next >= span_next_start - OFFSET_TOLERANCE {
1607            (BeamType::Stop, None)
1608        } else {
1609            return Err(Error::Meter("cannot match beamType".to_string()));
1610        };
1611
1612        if let Some(beams) = beamed[index].as_mut() {
1613            beams.set_by_number(beam_number, beam_type, direction)?;
1614        }
1615        Ok(())
1616    }
1617}
1618
1619/// A whole bar as a sequence of one part, which is what music21 starts each
1620/// of a meter's four sequences as: `6/8` undivided is `{6/8}`, not a bare
1621/// span, so a sequence nobody has divided still has one part.
1622fn whole_bar(
1623    numerator: UnsignedIntegerType,
1624    denominator: UnsignedIntegerType,
1625) -> Result<MeterTerminal> {
1626    let whole = format!("{numerator}/{denominator}");
1627    MeterTerminal::new(numerator, denominator)?.partitioned_by_parts(&[whole.as_str()])
1628}
1629
1630/// The word music21 allows beside a ratio, saying how the bar is counted:
1631/// `"slow 6/8"` is counted in six and `"fast 6/8"` in two. music21 looks for
1632/// it anywhere in the string and in any case, so `"6/8 Fast"` says it too.
1633fn division_word(ratio: &str) -> Option<&'static str> {
1634    let lower = ratio.to_ascii_lowercase();
1635    if lower.contains("slow") {
1636        Some("slow")
1637    } else if lower.contains("fast") {
1638        Some("fast")
1639    } else {
1640        None
1641    }
1642}
1643
1644/// The ratio with the word saying how it is counted taken out.
1645fn without_division_word(ratio: &str) -> String {
1646    let mut out = ratio.to_string();
1647    for word in ["slow", "fast"] {
1648        while let Some(at) = out.to_ascii_lowercase().find(word) {
1649            out.replace_range(at..at + word.len(), " ");
1650        }
1651    }
1652    out
1653}
1654
1655/// Whether a bar is felt in compound beats: music21's `favorCompound`.
1656///
1657/// The word written before the ratio decides it where there is one. Where
1658/// there is not, a bare three written in quarters or longer is felt slow,
1659/// which is what counts `3/4` in three while `3/8` is counted in one.
1660fn favor_compound(
1661    numerator: UnsignedIntegerType,
1662    denominator: UnsignedIntegerType,
1663    word: Option<&str>,
1664) -> bool {
1665    match word {
1666        Some("slow") => false,
1667        Some("fast") => true,
1668        _ => !(numerator == 3 && denominator < 8),
1669    }
1670}
1671
1672/// The time signature that fits what a measure holds: music21's
1673/// `bestTimeSignature`.
1674///
1675/// The shortest note value in the measure that is not a tuplet is the
1676/// denominator, halved until it divides the measure's length evenly, and the
1677/// count of it in the measure is the numerator, reduced to lowest terms with
1678/// the whole and half taken up to quarters. A measure that reads as `3/4` is
1679/// `6/8` instead when that weighs its notes at least as strongly, and one
1680/// that reads as `6/4` is whichever of `6/4`, `12/8` and `3/2` weighs them
1681/// most. A measure whose length is no binary fraction — tuplets — takes the
1682/// fraction itself.
1683pub fn best_time_signature(measure: &crate::Stream) -> Result<TimeSignature> {
1684    let elements = measure.recurse();
1685    let sum = elements
1686        .iter()
1687        .filter(|(_, element)| element.as_stream().is_none())
1688        .map(|(offset, element)| offset + element.quarter_length())
1689        .fold(0.0, FloatType::max);
1690
1691    // The shortest sounding value that is not a tuplet, with its dots.
1692    let mut min_dur = 4.0;
1693    let mut min_dots = 0;
1694    for (_, element) in &elements {
1695        let sounds =
1696            element.is_note_or_chord() || matches!(element, crate::stream::StreamElement::Rest(_));
1697        let quarter_length = element.quarter_length();
1698        if sounds && quarter_length != 0.0 && quarter_length < min_dur && is_binary(quarter_length)
1699        {
1700            min_dur = quarter_length;
1701            min_dots = element.duration().map_or(0, Duration::dots);
1702        }
1703    }
1704
1705    let (numerator, denominator) = if is_binary(sum) {
1706        binary_signature(sum, min_dur, min_dots)?
1707    } else {
1708        let (numerator, denominator) = crate::duration::limited_fraction(sum, 65535)
1709            .ok_or_else(|| Error::Meter("Cannot find a good match for this measure".to_string()))?;
1710        (
1711            numerator as UnsignedIntegerType,
1712            denominator as UnsignedIntegerType,
1713        )
1714    };
1715    let (numerator, denominator) = simplified_signature(numerator, denominator)
1716        .ok_or_else(|| Error::Meter("Cannot find a good match for this measure".to_string()))?;
1717
1718    let strength =
1719        |ratio: (UnsignedIntegerType, UnsignedIntegerType)| -> Result<(TimeSignature, FloatType)> {
1720            let signature = TimeSignature::new(ratio.0, ratio.1)?;
1721            let strength = signature.average_beat_strength(measure, true);
1722            Ok((signature, strength))
1723        };
1724    match (numerator, denominator) {
1725        // Three-four or six-eight, whichever weighs the notes more strongly.
1726        (3, 4) => {
1727            let (three_four, simple) = strength((3, 4))?;
1728            let (six_eight, compound) = strength((6, 8))?;
1729            Ok(if simple <= compound {
1730                six_eight
1731            } else {
1732                three_four
1733            })
1734        }
1735        // Six-four, twelve-eight or three-two, the same way.
1736        (6, 4) => {
1737            let (six_four, first) = strength((6, 4))?;
1738            let (twelve_eight, second) = strength((12, 8))?;
1739            let (three_two, third) = strength((3, 2))?;
1740            let most = first.max(second).max(third);
1741            Ok(if most == first {
1742                six_four
1743            } else if most == third {
1744                three_two
1745            } else {
1746                twelve_eight
1747            })
1748        }
1749        _ => TimeSignature::new(numerator, denominator),
1750    }
1751}
1752
1753/// The numerator and denominator of a measure whose length is a binary
1754/// fraction: the shortest value halved, dot and all, until it divides the
1755/// length evenly, named as a note value for the denominator and counted for
1756/// the numerator, in lowest terms.
1757fn binary_signature(
1758    sum: FloatType,
1759    min_dur: FloatType,
1760    min_dots: u32,
1761) -> Result<(UnsignedIntegerType, UnsignedIntegerType)> {
1762    let no_match = || Error::Meter("Cannot find a good match for this measure".to_string());
1763    let smallest_type = crate::duration::DurationType::from_music21_name("128th")
1764        .expect("music21 names the 128th note");
1765    let limit = smallest_type.quarter_length();
1766    let dot_multiplier =
1767        FloatType::from(2u32.pow(min_dots + 1) - 1) / FloatType::from(2u32.pow(min_dots));
1768
1769    let mut min_test = min_dur;
1770    let mut remaining = 10;
1771    while remaining > 0 {
1772        let parts = sum / min_test;
1773        if parts.floor() == parts || min_test <= limit {
1774            break;
1775        }
1776        min_test /= 2.0 * dot_multiplier;
1777        remaining -= 1;
1778    }
1779    let mut remaining = 10;
1780    while remaining > 0 {
1781        if min_test < limit {
1782            min_test = limit;
1783            break;
1784        }
1785        let (duration_type, matched) =
1786            crate::duration::quarter_length_to_closest_type(min_test).map_err(|_| no_match())?;
1787        if matched || duration_type == smallest_type {
1788            break;
1789        }
1790        min_test /= 2.0 * dot_multiplier;
1791        remaining -= 1;
1792    }
1793    let (duration_type, matched) =
1794        crate::duration::quarter_length_to_closest_type(min_test).map_err(|_| no_match())?;
1795    if !matched {
1796        return Err(Error::Meter(format!(
1797            "cannot find a type for denominator {min_test}"
1798        )));
1799    }
1800    let mut float_denominator = duration_type.type_number().unwrap_or(1.0);
1801    let mut multiplier = 1.0;
1802    let mut numerator_float = 0.0;
1803    while remaining > 0 {
1804        numerator_float = multiplier * sum / min_test;
1805        if numerator_float == numerator_float.floor() {
1806            break;
1807        }
1808        multiplier *= 2.0;
1809        remaining -= 1;
1810    }
1811    float_denominator *= multiplier;
1812    let numerator = numerator_float as UnsignedIntegerType;
1813    let denominator = float_denominator as UnsignedIntegerType;
1814    let divisor = num::integer::gcd(numerator, denominator).max(1);
1815    Ok((numerator / divisor, denominator / divisor))
1816}
1817
1818/// The rare signatures written the usual way: sixteen-sixteen and one-one
1819/// are four-four, and a whole or half denominator is written in quarters.
1820/// Nothing when the quarters are too many to count.
1821fn simplified_signature(
1822    numerator: UnsignedIntegerType,
1823    denominator: UnsignedIntegerType,
1824) -> Option<(UnsignedIntegerType, UnsignedIntegerType)> {
1825    if numerator == denominator && !matches!(numerator, 2 | 4) {
1826        Some((4, 4))
1827    } else if numerator != denominator && denominator == 1 {
1828        Some((numerator.checked_mul(4)?, 4))
1829    } else if numerator != denominator && denominator == 2 {
1830        Some((numerator.checked_mul(2)?, 4))
1831    } else {
1832        Some((numerator, denominator))
1833    }
1834}
1835
1836/// Whether a quarter length is a binary fraction music21 keeps as a float
1837/// rather than turning into a `Fraction`: one whose exact denominator is a
1838/// power of two no larger than its `DENOM_LIMIT`.
1839fn is_binary(quarter_length: FloatType) -> bool {
1840    (quarter_length * 32768.0).fract() == 0.0
1841}
1842
1843/// A span of `count` units of `1/unit`, divided into `parts` equal spans, as
1844/// a count of a unit: `6/8` in two is `3/8`, and `1/4` in two is `1/8`.
1845/// Nothing when the unit is too short to count.
1846fn split_span(
1847    count: UnsignedIntegerType,
1848    unit: UnsignedIntegerType,
1849    parts: UnsignedIntegerType,
1850) -> Option<(UnsignedIntegerType, UnsignedIntegerType)> {
1851    if count.is_multiple_of(parts) {
1852        Some((count / parts, unit))
1853    } else {
1854        Some((count, unit.checked_mul(parts)?))
1855    }
1856}
1857
1858/// How music21 divides a span by default when nothing says otherwise: its
1859/// `MeterSequence.subdivide` with no count given, which takes the first of
1860/// the span's division options.
1861fn default_division(count: UnsignedIntegerType, unit: UnsignedIntegerType) -> UnsignedIntegerType {
1862    let _ = unit;
1863    if count > 3 && count.is_multiple_of(3) {
1864        count / 3
1865    } else if count == 1 || count.is_multiple_of(2) {
1866        2
1867    } else {
1868        count
1869    }
1870}
1871
1872/// An offset written the way music21 writes one in a message: a whole number
1873/// as `3.0`, anything else as it is.
1874pub(crate) fn offset_repr(offset: FloatType) -> String {
1875    if offset.fract() == 0.0 {
1876        format!("{offset:.1}")
1877    } else {
1878        offset.to_string()
1879    }
1880}
1881
1882/// The offset back when it lies within `0..length`, or music21's error for
1883/// one that does not.
1884fn offset_within(offset: FloatType, length: FloatType) -> Result<FloatType> {
1885    if offset.is_nan() || offset < 0.0 || offset >= length {
1886        return Err(Error::Meter(format!(
1887            "cannot access from qLenPos {} where total duration is {}",
1888            offset_repr(offset),
1889            offset_repr(length)
1890        )));
1891    }
1892    Ok(offset)
1893}
1894
1895#[cfg(test)]
1896mod tests {
1897
1898    #[test]
1899    fn a_meter_counting_more_beats_than_the_limit_is_refused() {
1900        use super::{MAX_NUMERATOR, TimeSignature};
1901
1902        assert!(TimeSignature::new(MAX_NUMERATOR, 4).is_ok());
1903        assert!(TimeSignature::new(MAX_NUMERATOR + 1, 4).is_err());
1904        assert!(TimeSignature::from_ratio_string("99999999/1").is_err());
1905        assert!(TimeSignature::from_ratio_string("6000/4+6000/4").is_err());
1906        assert!(TimeSignature::from_ratio_string("4000000000/4+4000000000/4").is_err());
1907        assert!(TimeSignature::from_ratio_string("4000000000/4+1/8").is_err());
1908    }
1909
1910    #[test]
1911    fn a_meter_with_a_part_over_nought_is_refused() {
1912        use super::TimeSignature;
1913
1914        assert!(TimeSignature::from_ratio_string("3/8+2/0").is_err());
1915        assert!(TimeSignature::from_ratio_string("3/0+2/8").is_err());
1916    }
1917
1918    #[test]
1919    fn a_meter_of_the_shortest_units_is_one_accent() {
1920        use super::TimeSignature;
1921
1922        let signature = TimeSignature::new(1, 1 << 31).unwrap();
1923        assert_eq!(signature.accent_weights(), [1.0]);
1924    }
1925
1926    #[test]
1927    fn an_offset_past_the_bar_wraps_from_where_the_meter_stands() {
1928        // music21's own examples: a 3/4 bar and a 5/4 stream, the meter at 0.
1929        let three = TimeSignature::from_ratio_string("3/4").unwrap();
1930        assert_eq!(three.offset_in_bar(2.0, 0.0), 2.0);
1931        assert_eq!(three.offset_in_bar(4.0, 0.0), 1.0);
1932        let five = TimeSignature::from_ratio_string("5/4").unwrap();
1933        assert_eq!(five.offset_in_bar(3.0, 0.0), 3.0);
1934        assert_eq!(five.offset_in_bar(5.0, 0.0), 0.0);
1935
1936        // A meter a beat into the bar: the sum decides, the difference wraps.
1937        assert_eq!(three.offset_in_bar(1.5, 1.0), 1.5);
1938        assert_eq!(three.offset_in_bar(2.5, 1.0), 1.5);
1939    }
1940
1941    #[test]
1942    fn beat_divisions_are_read_off_the_beats_as_music21_reads_them() {
1943        // music21 asks only that the divisions agree: every beat of 2+3/8
1944        // divides into eighths, though the beats themselves differ.
1945        let cases: [(&str, &[FloatType], &[FloatType]); 9] = [
1946            ("2+3/8", &[0.5, 0.5], &[0.25; 4]),
1947            ("3+3+2/8", &[0.5; 3], &[0.25; 6]),
1948            ("5/8", &[0.25, 0.25], &[0.125; 4]),
1949            ("7/8", &[0.25, 0.25], &[0.125; 4]),
1950            ("4/4", &[0.5, 0.5], &[0.25; 4]),
1951            ("6/8", &[0.5; 3], &[0.25; 6]),
1952            ("5/4", &[0.5, 0.5], &[0.25; 4]),
1953            ("9/8", &[0.5; 3], &[0.25; 6]),
1954            ("3/2", &[1.0, 1.0], &[0.5; 4]),
1955        ];
1956        for (ratio, divisions, subdivisions) in cases {
1957            let meter = TimeSignature::from_ratio_string(ratio).unwrap();
1958            let lengths = |durations: Vec<Duration>| -> Vec<FloatType> {
1959                durations.iter().map(Duration::quarter_length).collect()
1960            };
1961            assert_eq!(
1962                lengths(meter.beat_division_durations().unwrap()),
1963                divisions,
1964                "{ratio}"
1965            );
1966            assert_eq!(
1967                lengths(meter.beat_sub_division_durations().unwrap()),
1968                subdivisions,
1969                "{ratio}"
1970            );
1971        }
1972
1973        // Divisions that differ are refused, as music21 refuses them.
1974        for ratio in ["3/4+3/8", "2/4+3/8", "1/4+1/8"] {
1975            let meter = TimeSignature::from_ratio_string(ratio).unwrap();
1976            assert!(meter.beat_division_durations().is_err(), "{ratio}");
1977        }
1978    }
1979    /// music21 writes a word before the ratio to say how the beat is felt,
1980    /// and writes an additive meter as parts that add up. Both were read as
1981    /// nonsense here, which is ten of music21's own meter examples.
1982    #[test]
1983    fn a_meter_is_read_as_music21_writes_it() {
1984        use crate::meter::TimeSignature;
1985
1986        // The word before the ratio is not decoration: music21 counts a
1987        // `slow 6/8` in six and a plain one in two, so the two are different
1988        // meters that happen to be written over the same numbers.
1989        let plain = TimeSignature::from_ratio_string("6/8").unwrap();
1990        let slow = TimeSignature::from_ratio_string("slow 6/8").unwrap();
1991        assert_eq!(TimeSignature::from_ratio_string("fast 6/8").unwrap(), plain);
1992        assert_ne!(slow, plain);
1993        assert_eq!(
1994            (slow.numerator(), slow.denominator()),
1995            (plain.numerator(), plain.denominator())
1996        );
1997        assert_eq!(plain.beat_sequence().len(), 2);
1998        assert_eq!(slow.beat_sequence().len(), 6);
1999
2000        let additive = TimeSignature::from_ratio_string("3/8+2/8").unwrap();
2001        assert_eq!((additive.numerator(), additive.denominator()), (5, 8));
2002        assert_eq!(
2003            TimeSignature::parts("3/8+2/8").unwrap(),
2004            vec![(3, 8), (2, 8)]
2005        );
2006        // A numerator with no denominator of its own takes the next one.
2007        assert_eq!(TimeSignature::parts("3+2/8").unwrap(), vec![(3, 8), (2, 8)]);
2008        assert_eq!(
2009            TimeSignature::parts("3+2+5/8+3/4").unwrap(),
2010            vec![(3, 8), (2, 8), (5, 8), (3, 4)]
2011        );
2012        // Parts in different notes come to what they add up to.
2013        let mixed = TimeSignature::from_ratio_string("3/8+1/4").unwrap();
2014        assert_eq!((mixed.numerator(), mixed.denominator()), (5, 8));
2015
2016        assert!(TimeSignature::parts("3+2+5").is_err());
2017        assert!(TimeSignature::from_ratio_string("").is_err());
2018        assert!(TimeSignature::from_ratio_string("3.0/4.0").is_err());
2019    }
2020
2021    #[test]
2022    fn a_summed_numerator_is_beamed_as_it_was_written() {
2023        use crate::meter::TimeSignature;
2024
2025        // Read off music21 11.0.0b9: `summedNumerator` and the parts of
2026        // `beamSequence`. A bar written part by part is beamed by the rule
2027        // for its numerator where there is one, and as written where there
2028        // is not; one written with its numerators summed is left alone.
2029        let expected = [
2030            ("3+2/8", true, "{3/8+2/8}"),
2031            ("3/8+2/8", false, "{2/8+3/8}"),
2032            ("2+3/8", true, "{2/8+3/8}"),
2033            ("3+2+2/8", true, "{3/8+2/8+2/8}"),
2034            ("3/8+2/8+2/8", false, "{2/8+2/8+3/8}"),
2035            ("2+2+3/16", true, "{2/16+2/16+3/16}"),
2036            ("3/16+2/16", false, "{3/16+2/16}"),
2037            ("6/8", false, "{3/8+3/8}"),
2038        ];
2039        for (written, summed, beams) in expected {
2040            let signature = TimeSignature::from_ratio_string(written).unwrap();
2041            assert_eq!(signature.summed_numerator(), summed, "{written}");
2042            assert_eq!(signature.beam_sequence().to_string(), beams, "{written}");
2043        }
2044
2045        let mut signature = TimeSignature::from_ratio_string("3/8+2/8").unwrap();
2046        signature.set_summed_numerator(true);
2047        assert!(signature.summed_numerator());
2048        assert!(signature.display_sequence().summed_numerator());
2049    }
2050
2051    #[test]
2052    fn the_sequences_are_partitioned_as_music21_partitions_them() {
2053        use crate::meter::TimeSignature;
2054
2055        // Read off music21 11.0.0b9 directly: `str(TimeSignature(r).beatSequence)`
2056        // and `.beamSequence` for each meter below.
2057        let expected = [
2058            ("1/4", "{1/4}", "{1/4}"),
2059            ("2/4", "{{1/8+1/8}+{1/8+1/8}}", "{{1/8+1/8}+{1/8+1/8}}"),
2060            (
2061                "3/4",
2062                "{{1/8+1/8}+{1/8+1/8}+{1/8+1/8}}",
2063                "{{1/8+1/8}+{1/8+1/8}+{1/8+1/8}}",
2064            ),
2065            (
2066                "4/4",
2067                "{{1/8+1/8}+{1/8+1/8}+{1/8+1/8}+{1/8+1/8}}",
2068                "{{1/8+1/8}+{1/8+1/8}+{1/8+1/8}+{1/8+1/8}}",
2069            ),
2070            (
2071                "5/4",
2072                "{{1/8+1/8}+{1/8+1/8}+{1/8+1/8}+{1/8+1/8}+{1/8+1/8}}",
2073                "{{1/4+1/4}+{1/4+1/4+1/4}}",
2074            ),
2075            ("6/4", "{{1/4+1/4+1/4}+{1/4+1/4+1/4}}", "{3/4+3/4}"),
2076            ("2/2", "{{1/4+1/4}+{1/4+1/4}}", "{1/2+1/2}"),
2077            ("3/2", "{{1/4+1/4}+{1/4+1/4}+{1/4+1/4}}", "{1/2+1/2+1/2}"),
2078            ("3/8", "{3/8}", "{3/8}"),
2079            (
2080                "5/8",
2081                "{{1/16+1/16}+{1/16+1/16}+{1/16+1/16}+{1/16+1/16}+{1/16+1/16}}",
2082                "{2/8+3/8}",
2083            ),
2084            ("6/8", "{{1/8+1/8+1/8}+{1/8+1/8+1/8}}", "{3/8+3/8}"),
2085            (
2086                "9/8",
2087                "{{1/8+1/8+1/8}+{1/8+1/8+1/8}+{1/8+1/8+1/8}}",
2088                "{3/8+3/8+3/8}",
2089            ),
2090            (
2091                "12/8",
2092                "{{1/8+1/8+1/8}+{1/8+1/8+1/8}+{1/8+1/8+1/8}+{1/8+1/8+1/8}}",
2093                "{3/8+3/8+3/8+3/8}",
2094            ),
2095            (
2096                "5/16",
2097                "{{1/32+1/32}+{1/32+1/32}+{1/32+1/32}+{1/32+1/32}+{1/32+1/32}}",
2098                "{5/16}",
2099            ),
2100            (
2101                "slow 6/8",
2102                "{{1/16+1/16}+{1/16+1/16}+{1/16+1/16}+{1/16+1/16}+{1/16+1/16}+{1/16+1/16}}",
2103                "{3/8+3/8}",
2104            ),
2105            ("fast 6/8", "{{1/8+1/8+1/8}+{1/8+1/8+1/8}}", "{3/8+3/8}"),
2106            ("6/8 fast", "{{1/8+1/8+1/8}+{1/8+1/8+1/8}}", "{3/8+3/8}"),
2107            (
2108                "6/8 Slow",
2109                "{{1/16+1/16}+{1/16+1/16}+{1/16+1/16}+{1/16+1/16}+{1/16+1/16}+{1/16+1/16}}",
2110                "{3/8+3/8}",
2111            ),
2112            ("3/8+2/8", "{{1/8+1/8+1/8}+{1/8+1/8}}", "{2/8+3/8}"),
2113            ("2/4+3/8", "{{1/4+1/4}+{1/8+1/8+1/8}}", "{2/8+2/8+3/8}"),
2114        ];
2115        for (ratio, beats, beams) in expected {
2116            let signature = TimeSignature::from_ratio_string(ratio).unwrap();
2117            assert_eq!(
2118                signature.beat_sequence().to_string(),
2119                beats,
2120                "beats of {ratio}"
2121            );
2122            assert_eq!(
2123                signature.beam_sequence().to_string(),
2124                beams,
2125                "beams of {ratio}"
2126            );
2127        }
2128    }
2129
2130    /// Read off music21's default `accentSequence` and `getBeatDepth`.
2131    #[test]
2132    fn accent_weights_and_beat_depths_follow_the_default_hierarchy() {
2133        let weights = |ratio: &str| {
2134            TimeSignature::from_ratio_string(ratio)
2135                .unwrap()
2136                .accent_weights()
2137        };
2138        assert_eq!(
2139            weights("4/4"),
2140            [1.0, 0.125, 0.25, 0.125, 0.5, 0.125, 0.25, 0.125]
2141        );
2142        assert_eq!(
2143            weights("6/8"),
2144            [
2145                1.0, 0.125, 0.25, 0.125, 0.25, 0.125, 0.5, 0.125, 0.25, 0.125, 0.25, 0.125
2146            ]
2147        );
2148        assert_eq!(
2149            weights("12/8"),
2150            [
2151                1.0, 0.125, 0.125, 0.25, 0.125, 0.125, 0.5, 0.125, 0.125, 0.25, 0.125, 0.125
2152            ]
2153        );
2154        assert_eq!(weights("3/4").len(), 12);
2155        assert_eq!(weights("24/8").len(), 24);
2156        assert_eq!(
2157            TimeSignature::new(1, 4)
2158                .unwrap()
2159                .accent_partition_quarter_length(),
2160            0.125
2161        );
2162
2163        let three_four = TimeSignature::new(3, 4).unwrap();
2164        let read: Vec<FloatType> = (0..3)
2165            .map(|beat| three_four.accent_weight(FloatType::from(beat)).unwrap())
2166            .collect();
2167        assert_eq!(read, [1.0, 0.5, 0.5]);
2168        let beyond = three_four.accent_weight(3.0).unwrap_err().to_string();
2169        assert!(beyond.ends_with("cannot access from qLenPos 3.0 where total duration is 3.0"));
2170        // A bar whose parts would be longer than a whole note, or shorter
2171        // than a 128th, is one partition.
2172        assert_eq!(weights("16/1"), [1.0]);
2173        assert_eq!(weights("1/32"), [1.0]);
2174        assert_eq!(
2175            TimeSignature::new(24, 4)
2176                .unwrap()
2177                .accent_partition_quarter_length(),
2178            1.0
2179        );
2180        assert_eq!(
2181            three_four.accent_weight_with(4.0, false, true).unwrap(),
2182            0.5
2183        );
2184        assert_eq!(
2185            three_four.accent_weight_with(0.1, true, false).unwrap(),
2186            0.0625
2187        );
2188        assert_eq!(
2189            three_four.accent_weight_with(0.1, false, false).unwrap(),
2190            1.0
2191        );
2192        assert!(three_four.accent(2.0));
2193        assert!(!three_four.accent(0.1));
2194        assert!(!three_four.accent(3.0));
2195
2196        assert_eq!(three_four.beat_depth(0.0).unwrap(), 2);
2197        assert_eq!(three_four.beat_depth(0.25).unwrap(), 2);
2198        assert_eq!(three_four.beat_depth(0.5).unwrap(), 1);
2199        assert_eq!(three_four.beat_depth(1.0).unwrap(), 2);
2200        assert!(three_four.beat_depth(3.0).is_err());
2201        assert_eq!(
2202            TimeSignature::new(3, 8).unwrap().beat_depth(0.5).unwrap(),
2203            1
2204        );
2205        assert_eq!(
2206            TimeSignature::new(6, 8).unwrap().beat_depth(1.0).unwrap(),
2207            1
2208        );
2209        assert_eq!(
2210            TimeSignature::new(6, 8).unwrap().beat_depth(1.5).unwrap(),
2211            2
2212        );
2213    }
2214
2215    /// music21's own `bestTimeSignature` examples.
2216    #[test]
2217    fn the_best_time_signature_fits_what_the_measure_holds() {
2218        use crate::{Note, Pitch, Stream};
2219
2220        let measure = |lengths: &[FloatType]| {
2221            let mut stream = Stream::new();
2222            for length in lengths {
2223                let mut note = Note::from_pitch(Pitch::from_name("C4").unwrap());
2224                note.set_duration(Duration::new(*length).unwrap());
2225                stream.push(note);
2226            }
2227            stream
2228        };
2229        let best = |lengths: &[FloatType]| {
2230            best_time_signature(&measure(lengths))
2231                .unwrap()
2232                .ratio_string()
2233        };
2234        assert_eq!(best(&[1.0, 1.0, 0.5, 0.5]), "3/4");
2235        assert_eq!(best(&[0.75, 0.25, 0.5, 0.75, 0.25, 0.5]), "6/8");
2236        assert_eq!(best(&[2.0, 2.0, 2.0]), "3/2");
2237        assert_eq!(best(&[0.75, 0.25, 0.5, 0.75, 0.25, 0.5, 1.5, 1.5]), "12/8");
2238        assert_eq!(best(&[1.0, 2.0, 1.0, 2.0]), "6/4");
2239        assert_eq!(best(&[1.0, 0.375]), "11/32");
2240        assert_eq!(best(&[3.5, 5.5]), "9/4");
2241        assert_eq!(best(&[1.0, 1.0, 1.0, 1.0]), "4/4");
2242        assert_eq!(best(&[4.0]), "4/4");
2243        // Tuplets are passed over when the shortest value is looked for.
2244        assert_eq!(best(&[1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0, 1.0]), "2/4");
2245    }
2246
2247    #[test]
2248    fn a_measure_too_long_for_any_signature_has_none() {
2249        use crate::{Note, Pitch, Stream};
2250
2251        let mut note = Note::from_pitch(Pitch::from_name("C4").unwrap());
2252        note.set_duration(Duration::new(4_294_967_296.0).unwrap());
2253        let mut measure = Stream::new();
2254        measure.push(note);
2255        assert!(best_time_signature(&measure).is_err());
2256    }
2257
2258    /// music21's own `averageBeatStrength` example: `C4 D4 E8 F8` under
2259    /// six-eight and three-four.
2260    #[test]
2261    fn beat_strength_is_averaged_over_a_stream() {
2262        use crate::{Note, Pitch, Stream};
2263
2264        let mut stream = Stream::new();
2265        for (name, length) in [("C4", 1.0), ("D4", 1.0), ("E4", 0.5), ("F4", 0.5)] {
2266            let mut note = Note::from_pitch(Pitch::from_name(name).unwrap());
2267            note.set_duration(Duration::new(length).unwrap());
2268            stream.push(note);
2269        }
2270        assert_eq!(
2271            TimeSignature::new(6, 8)
2272                .unwrap()
2273                .average_beat_strength(&stream, true),
2274            0.4375
2275        );
2276        assert_eq!(
2277            TimeSignature::new(3, 4)
2278                .unwrap()
2279                .average_beat_strength(&stream, true),
2280            0.5625
2281        );
2282        stream.insert(0.0, TimeSignature::new(3, 4).unwrap());
2283        stream.insert(0.0, TimeSignature::new(6, 8).unwrap());
2284        assert_eq!(
2285            TimeSignature::new(6, 8)
2286                .unwrap()
2287                .average_beat_strength(&stream, false),
2288            0.625
2289        );
2290        assert_eq!(
2291            TimeSignature::new(4, 4)
2292                .unwrap()
2293                .average_beat_strength(&Stream::new(), true),
2294            0.0
2295        );
2296    }
2297
2298    /// music21 weighs a measure's own notes, so one whose notes all stand in
2299    /// a voice weighs nothing, and a half and a quarter there read as six-
2300    /// eight where the same two notes in the measure itself read as
2301    /// three-four.
2302    #[test]
2303    fn a_measure_weighs_its_own_notes_and_not_its_voices() {
2304        use crate::stream::StreamKind;
2305        use crate::{Note, Pitch, Stream};
2306
2307        let mut voice = Stream::with_kind(StreamKind::Voice);
2308        for (name, length) in [("C5", 2.0), ("B4", 1.0)] {
2309            let mut note = Note::from_pitch(Pitch::from_name(name).unwrap());
2310            note.set_duration(Duration::new(length).unwrap());
2311            voice.push(note);
2312        }
2313        let mut plain = voice.clone();
2314        plain.set_kind(StreamKind::Measure);
2315        let mut voiced = Stream::with_kind(StreamKind::Measure);
2316        voiced.insert(0.0, voice);
2317
2318        let three_four = TimeSignature::new(3, 4).unwrap();
2319        assert_eq!(three_four.average_beat_strength(&voiced, true), 0.0);
2320        assert_eq!(best_time_signature(&plain).unwrap().ratio_string(), "3/4");
2321        assert_eq!(best_time_signature(&voiced).unwrap().ratio_string(), "6/8");
2322    }
2323
2324    #[test]
2325    fn a_signature_reports_its_two_numbers_and_its_bar() {
2326        let six_eight = TimeSignature::new(6, 8).unwrap();
2327        assert_eq!((six_eight.numerator(), six_eight.denominator()), (6, 8));
2328        assert_eq!(six_eight.bar_duration().quarter_length(), 3.0);
2329    }
2330
2331    /// music21 reads the progress through `opFrac`, so a third of a beat
2332    /// is a sixth exactly, not the float the subtraction leaves.
2333    #[test]
2334    fn beat_progress_is_read_through_op_frac() {
2335        let six_eight = TimeSignature::new(6, 8).unwrap();
2336        let (beat, progress) = six_eight.beat_progress(5.0 / 3.0).unwrap();
2337        assert_eq!(beat, 2);
2338        assert_eq!(progress, crate::makenotation::op_frac(1.0 / 6.0));
2339    }
2340
2341    #[test]
2342    fn a_written_bar_length_stands_over_the_meters_own() {
2343        let mut three_eight = TimeSignature::new(3, 8).unwrap();
2344        three_eight.set_bar_duration(Some(Duration::new(1.75).unwrap()));
2345        assert_eq!(three_eight.bar_duration().quarter_length(), 1.75);
2346        // The meter itself is unchanged: only the bar it reports.
2347        assert_eq!(three_eight.bar_quarter_length(), 1.5);
2348
2349        three_eight.set_bar_duration(None);
2350        assert_eq!(three_eight.bar_duration().quarter_length(), 1.5);
2351    }
2352
2353    #[test]
2354    fn division_helpers_match_music21() {
2355        let quarter_lengths = |durations: Vec<Duration>| -> Vec<FloatType> {
2356            durations.into_iter().map(|d| d.quarter_length()).collect()
2357        };
2358        let cases: [(&str, FloatType, &str, &[FloatType], usize); 7] = [
2359            ("4/4", 1.0, "Simple", &[0.5, 0.5], 4),
2360            ("6/8", 0.5, "Compound", &[0.5, 0.5, 0.5], 6),
2361            ("2/2", 2.0, "Simple", &[1.0, 1.0], 4),
2362            ("3/8", 0.5, "Other", &[1.5], 2),
2363            ("7/8", 0.5, "Simple", &[0.25, 0.25], 4),
2364            ("12/16", 0.25, "Compound", &[0.25, 0.25, 0.25], 6),
2365            ("1/4", 1.0, "Other", &[1.0], 2),
2366        ];
2367        for (ratio, beat_to_quarter, division_name, divisions, sub_divisions) in cases {
2368            let ts = ts(ratio);
2369            assert_eq!(
2370                ts.beat_length_to_quarter_length_ratio(),
2371                beat_to_quarter,
2372                "{ratio}"
2373            );
2374            assert_eq!(
2375                ts.quarter_length_to_beat_length_ratio(),
2376                1.0 / beat_to_quarter,
2377                "{ratio}"
2378            );
2379            assert_eq!(ts.beat_division_count_name(), division_name, "{ratio}");
2380            assert_eq!(
2381                quarter_lengths(ts.beat_division_durations().unwrap()),
2382                divisions,
2383                "{ratio}"
2384            );
2385            let subs = quarter_lengths(ts.beat_sub_division_durations().unwrap());
2386            assert_eq!(subs.len(), sub_divisions, "{ratio}");
2387            assert!(subs.iter().all(|ql| *ql == divisions[0] / 2.0), "{ratio}");
2388        }
2389        assert!(ts("4/4").ratio_equal(&ts("4/4")));
2390        assert!(!ts("4/4").ratio_equal(&ts("2/2")));
2391    }
2392
2393    #[test]
2394    fn beat_positions_match_music21() {
2395        let common = ts("4/4");
2396        let cases: [(FloatType, UnsignedIntegerType, FloatType, FloatType, &str); 7] = [
2397            (0.0, 1, 0.0, 1.0, "1"),
2398            (0.5, 1, 0.5, 1.5, "1 1/2"),
2399            (1.25, 2, 0.25, 2.25, "2 1/4"),
2400            (2.75, 3, 0.75, 3.75, "3 3/4"),
2401            (3.0, 4, 0.0, 4.0, "4"),
2402            (3.75, 4, 0.75, 4.75, "4 3/4"),
2403            (3.9, 4, 0.9, 4.9, "4 9/10"),
2404        ];
2405        for (offset, beat, progress, proportion, text) in cases {
2406            let (actual_beat, actual_progress) = common.beat_progress(offset).unwrap();
2407            assert_eq!(actual_beat, beat, "{offset}");
2408            assert!((actual_progress - progress).abs() < 1e-9, "{offset}");
2409            assert!(
2410                (common.beat_proportion(offset).unwrap() - proportion).abs() < 1e-9,
2411                "{offset}"
2412            );
2413            assert_eq!(
2414                common.beat_proportion_string(offset).unwrap(),
2415                text,
2416                "{offset}"
2417            );
2418        }
2419
2420        let compound = ts("6/8");
2421        assert_eq!(compound.beat_proportion_string(0.5).unwrap(), "1 1/3");
2422        assert_eq!(compound.beat_proportion_string(1.0).unwrap(), "1 2/3");
2423        assert_eq!(compound.beat_proportion_string(2.5).unwrap(), "2 2/3");
2424        assert!((compound.beat_proportion(2.0).unwrap() - 7.0 / 3.0).abs() < 1e-9);
2425        assert_eq!(ts("3/8").beat_proportion_string(1.0).unwrap(), "1 2/3");
2426        assert!(common.beat_progress(4.0).is_err());
2427    }
2428
2429    #[test]
2430    fn offset_from_beat_matches_music21() {
2431        let common = ts("4/4");
2432        for (beat, offset) in [
2433            (1.0, 0.0),
2434            (1.5, 0.5),
2435            (2.5, 1.5),
2436            (3.25, 2.25),
2437            (4.75, 3.75),
2438        ] {
2439            assert_eq!(common.offset_from_beat(beat).unwrap(), offset, "{beat}");
2440        }
2441        assert!(common.offset_from_beat(5.0).is_err());
2442        assert!(common.offset_from_beat(0.5).is_err());
2443        let compound = ts("6/8");
2444        assert_eq!(compound.offset_from_beat(1.5).unwrap(), 0.75);
2445        assert_eq!(compound.offset_from_beat(2.5).unwrap(), 2.25);
2446        assert!((compound.offset_from_beat(2.999).unwrap() - 2.9985).abs() < 1e-9);
2447        assert_eq!(ts("3/8").offset_from_beat(1.5).unwrap(), 0.75);
2448    }
2449
2450    #[test]
2451    fn closest_fraction_limits_the_denominator_like_python() {
2452        assert_eq!(closest_fraction(0.5, 16), (1, 2));
2453        assert_eq!(closest_fraction(1.0 / 3.0, 16), (1, 3));
2454        assert_eq!(closest_fraction(0.9, 16), (9, 10));
2455        assert_eq!(closest_fraction(0.75, 16), (3, 4));
2456        assert_eq!(closest_fraction(0.1234, 16), (1, 8));
2457    }
2458    use super::*;
2459
2460    fn ts(ratio: &str) -> TimeSignature {
2461        TimeSignature::from_ratio_string(ratio).expect("valid time signature")
2462    }
2463
2464    #[test]
2465    fn common_and_cut_time_match_their_ratios() {
2466        assert_eq!(TimeSignature::common().ratio_string(), "4/4");
2467        assert_eq!(TimeSignature::cut().ratio_string(), "2/2");
2468        assert_eq!(TimeSignature::default(), TimeSignature::common());
2469    }
2470
2471    #[test]
2472    fn bar_and_beat_lengths_follow_the_ratio() {
2473        assert_eq!(ts("4/4").bar_quarter_length(), 4.0);
2474        assert_eq!(ts("5/16").bar_quarter_length(), 1.25);
2475        assert_eq!(ts("3/8").bar_quarter_length(), 1.5);
2476        assert_eq!(ts("6/8").beat_quarter_length(), 1.5);
2477        assert_eq!(ts("4/4").beat_quarter_length(), 1.0);
2478        assert_eq!(ts("2/2").beat_duration().quarter_length(), 2.0);
2479    }
2480
2481    #[test]
2482    fn compound_meters_beat_in_threes() {
2483        for (ratio, beats, division) in [
2484            ("6/8", 2, BeatDivision::Compound),
2485            ("9/8", 3, BeatDivision::Compound),
2486            ("12/8", 4, BeatDivision::Compound),
2487            ("15/8", 5, BeatDivision::Compound),
2488            ("18/8", 6, BeatDivision::Compound),
2489            ("24/8", 8, BeatDivision::Compound),
2490        ] {
2491            assert_eq!(ts(ratio).beat_count(), beats, "{ratio}");
2492            assert_eq!(ts(ratio).beat_division(), division, "{ratio}");
2493            assert!(ts(ratio).is_compound(), "{ratio}");
2494        }
2495    }
2496
2497    #[test]
2498    fn three_is_the_one_denominator_sensitive_numerator() {
2499        // 3/2 and 3/4 read as three beats; 3/8 and shorter read as one.
2500        assert_eq!(ts("3/2").beat_count(), 3);
2501        assert_eq!(ts("3/4").beat_count(), 3);
2502        assert_eq!(ts("3/8").beat_count(), 1);
2503        assert_eq!(ts("3/16").beat_count(), 1);
2504        assert_eq!(ts("3/32").beat_count(), 1);
2505        // The cut is at an eighth rather than at a power of two: music21
2506        // counts 3/3 and 3/6 in three, and 3/12 in one.
2507        assert_eq!(ts("3/3").beat_count(), 3);
2508        assert_eq!(ts("3/6").beat_count(), 3);
2509        assert_eq!(ts("3/12").beat_count(), 1);
2510        // Every other numerator ignores the denominator entirely.
2511        for denominator in [2, 4, 8, 16] {
2512            assert_eq!(TimeSignature::new(6, denominator).unwrap().beat_count(), 2);
2513            assert_eq!(TimeSignature::new(5, denominator).unwrap().beat_count(), 5);
2514        }
2515    }
2516
2517    #[test]
2518    fn a_bar_written_in_unequal_parts_is_counted_along_its_own_beats() {
2519        use crate::meter::TimeSignature;
2520
2521        // Read off music21 11.0.0b9. `2/4+3/8` is two beats, of two quarters
2522        // and of three eighths, so nothing here is the bar divided evenly.
2523        let mixed = TimeSignature::from_ratio_string("2/4+3/8").unwrap();
2524        assert_eq!(mixed.bar_quarter_length(), 3.5);
2525        assert_eq!(mixed.beat_count(), 2);
2526        assert_eq!(mixed.beat_offsets(), vec![0.0, 2.0]);
2527        assert_eq!(mixed.beat_at_offset(2.5).unwrap(), 2);
2528        assert_eq!(mixed.beat_duration_at(0.0).unwrap().quarter_length(), 2.0);
2529        assert_eq!(mixed.beat_duration_at(2.5).unwrap().quarter_length(), 1.5);
2530        assert_eq!(mixed.offset_from_beat(2.0).unwrap(), 2.0);
2531        // Half way through the first beat is half of *that* beat, not half of
2532        // an averaged one.
2533        assert_eq!(mixed.offset_from_beat(1.5).unwrap(), 1.0);
2534        assert_eq!(mixed.beat_proportion_string(2.5).unwrap(), "2 1/3");
2535        assert_eq!(mixed.beat_depth(0.0).unwrap(), 2);
2536
2537        let other = TimeSignature::from_ratio_string("3/8+2/8").unwrap();
2538        assert_eq!(other.beat_offsets(), vec![0.0, 1.5]);
2539        assert_eq!(other.offset_from_beat(2.0).unwrap(), 1.5);
2540        assert_eq!(other.offset_from_beat(1.5).unwrap(), 0.75);
2541        // The bar is 2.5 long, so 2.5 is past the end of it.
2542        assert!(other.beat_proportion_string(2.5).is_err());
2543
2544        // An evenly divided bar answers exactly as it did.
2545        let common = TimeSignature::common();
2546        assert_eq!(common.beat_offsets(), vec![0.0, 1.0, 2.0, 3.0]);
2547        assert_eq!(common.offset_from_beat(2.0).unwrap(), 1.0);
2548        assert_eq!(common.offset_from_beat(1.5).unwrap(), 0.5);
2549        assert_eq!(common.beat_proportion_string(2.5).unwrap(), "3 1/2");
2550    }
2551
2552    #[test]
2553    fn a_bar_whose_beats_differ_answers_its_first_beat_length() {
2554        use crate::meter::TimeSignature;
2555
2556        // music21 answers the first beat's length here and reports the
2557        // division as Other, counting one.
2558        let mixed = TimeSignature::from_ratio_string("2/4+3/8").unwrap();
2559        assert_eq!(mixed.beat_quarter_length(), 2.0);
2560        assert_eq!(mixed.beat_duration().quarter_length(), 2.0);
2561        assert!(mixed.beat_division_durations().is_err());
2562        assert_eq!(mixed.beat_division_count(), 1);
2563        assert_eq!(mixed.beat_division_count_name(), "Other");
2564        assert_eq!(mixed.classification(), "Other Duple");
2565
2566        let other = TimeSignature::from_ratio_string("3/8+2/8").unwrap();
2567        assert_eq!(other.beat_quarter_length(), 1.5);
2568        assert_eq!(other.beat_division_count(), 1);
2569        assert_eq!(other.classification(), "Other Duple");
2570
2571        // An evenly divided bar still answers, and answers as it did.
2572        assert_eq!(TimeSignature::common().beat_quarter_length(), 1.0);
2573        assert_eq!(
2574            TimeSignature::from_ratio_string("6/8")
2575                .unwrap()
2576                .beat_quarter_length(),
2577            1.5
2578        );
2579    }
2580
2581    #[test]
2582    fn weights_a_caller_sets_are_the_weights_read_back() {
2583        use crate::meter::TimeSignature;
2584
2585        let mut common = TimeSignature::common();
2586        let default = common.accent_weights();
2587        assert_eq!(default[0], 1.0);
2588
2589        // music21 loops a shorter list over the partitions.
2590        common.set_accent_weight(&[0.8, 0.2], 0).unwrap();
2591        let set = common.accent_weights();
2592        assert_eq!(set.len(), default.len());
2593        assert!((set[0] - 0.8).abs() < 1e-9);
2594        assert!((set[1] - 0.2).abs() < 1e-9);
2595        assert!((set[2] - 0.8).abs() < 1e-9);
2596
2597        // And the reading at an offset comes off the same sequence.
2598        assert!((common.accent_weight(0.0).unwrap() - 0.8).abs() < 1e-9);
2599
2600        // A fresh meter is untouched by that.
2601        assert_eq!(TimeSignature::common().accent_weights()[0], 1.0);
2602    }
2603
2604    #[test]
2605    fn a_bar_can_be_counted_in_a_different_number_of_beats() {
2606        use crate::meter::TimeSignature;
2607
2608        // Read off music21 11.0.0b9 by assigning to `beatCount`.
2609        for (ratio, count, partitioned) in [
2610            (
2611                "6/8",
2612                6,
2613                "{{1/16+1/16}+{1/16+1/16}+{1/16+1/16}+{1/16+1/16}+{1/16+1/16}+{1/16+1/16}}",
2614            ),
2615            ("6/8", 2, "{{1/8+1/8+1/8}+{1/8+1/8+1/8}}"),
2616            ("4/4", 2, "{{1/4+1/4}+{1/4+1/4}}"),
2617            ("3/4", 1, "{3/4}"),
2618            (
2619                "2/4",
2620                4,
2621                "{{1/16+1/16}+{1/16+1/16}+{1/16+1/16}+{1/16+1/16}}",
2622            ),
2623        ] {
2624            let mut signature = TimeSignature::from_ratio_string(ratio).unwrap();
2625            signature.set_beat_count(count).unwrap();
2626            assert_eq!(
2627                signature.beat_sequence().to_string(),
2628                partitioned,
2629                "{ratio} in {count}"
2630            );
2631            assert_eq!(signature.beat_count(), count, "{ratio} in {count}");
2632        }
2633    }
2634
2635    #[test]
2636    fn a_bar_can_be_written_a_different_way_than_it_is_counted() {
2637        use crate::meter::TimeSignature;
2638
2639        // music21's own `setDisplay` docstring: a 3/4 written in three
2640        // groups of two eighths.
2641        let mut signature = TimeSignature::from_ratio_string("3/4").unwrap();
2642        let counted = signature.beat_sequence().to_string();
2643        signature.set_display("2/8+2/8+2/8").unwrap();
2644        assert_eq!(signature.display_sequence().to_string(), "{2/8+2/8+2/8}");
2645        assert_eq!(
2646            signature.display_sequence().partition_display(),
2647            "2/8+2/8+2/8"
2648        );
2649        // What it counts is untouched; only how it is written changed.
2650        assert_eq!(signature.beat_sequence().to_string(), counted);
2651        assert_eq!(signature.beat_count(), 3);
2652        // music21 reads `ratioString` off the display sequence, so there it
2653        // becomes "2/8+2/8+2/8". The crate still writes it from the
2654        // numerator and the denominator; see issues.md.
2655
2656        // A bar cannot be written as a length it is not.
2657        assert!(signature.set_display("2/4").is_err());
2658
2659        // The sequences can be partitioned through.
2660        let mut common = TimeSignature::common();
2661        common.set_beat_sequence(
2662            common
2663                .beat_sequence()
2664                .partitioned_by_count(2, true)
2665                .unwrap(),
2666        );
2667        assert_eq!(common.beat_count(), 2);
2668    }
2669
2670    #[test]
2671    fn the_divisions_a_meter_is_built_with_partition_its_beats() {
2672        use crate::meter::TimeSignature;
2673
2674        // Read off music21 11.0.0b9: TimeSignature(ratio, divisions).
2675        for (ratio, divisions, partitioned) in [
2676            ("3/4", 1, "{3/4}"),
2677            ("6/8", 2, "{3/8+3/8}"),
2678            ("4/4", 2, "{1/2+1/2}"),
2679            ("3/4", 3, "{1/4+1/4+1/4}"),
2680        ] {
2681            let mut signature = TimeSignature::from_ratio_string(ratio).unwrap();
2682            signature.divide_beats(divisions).unwrap();
2683            assert_eq!(
2684                signature.beat_sequence().to_string(),
2685                partitioned,
2686                "{ratio} in {divisions}"
2687            );
2688        }
2689
2690        // Unlike counting the bar, which divides each beat again.
2691        let mut counted = TimeSignature::from_ratio_string("6/8").unwrap();
2692        counted.set_beat_count(2).unwrap();
2693        assert_eq!(
2694            counted.beat_sequence().to_string(),
2695            "{{1/8+1/8+1/8}+{1/8+1/8+1/8}}"
2696        );
2697    }
2698
2699    #[test]
2700    fn a_fractional_beat_is_read_as_the_fraction_it_suggests() {
2701        use crate::meter::TimeSignature;
2702
2703        // Read off music21 11.0.0b9: getOffsetFromBeat snaps through
2704        // addFloatPrecision, so a third written as .33 is a third.
2705        // A 6/8 beat lasts 1.5, so beat 2.33 starts a third of the way
2706        // into the second beat: 1.5 + 1.5/3. music21 answers 2.0 and 2.5.
2707        let compound = TimeSignature::from_ratio_string("6/8").unwrap();
2708        assert!((compound.offset_from_beat(2.33).unwrap() - 2.0).abs() < 1e-9);
2709        assert!((compound.offset_from_beat(2.66).unwrap() - 2.5).abs() < 1e-9);
2710        assert!((compound.offset_from_beat(1.66).unwrap() - 1.0).abs() < 1e-9);
2711
2712        // A simple beat lasts one quarter, so the same beats land on thirds
2713        // of it: music21 answers 4/3, 5/3 and 2/3 for a 4/4 bar.
2714        let simple = TimeSignature::common();
2715        let third = 1.0 / 3.0;
2716        assert!((simple.offset_from_beat(2.33).unwrap() - (1.0 + third)).abs() < 1e-9);
2717        assert!((simple.offset_from_beat(2.66).unwrap() - (1.0 + 2.0 * third)).abs() < 1e-9);
2718        assert!((simple.offset_from_beat(1.66).unwrap() - (2.0 * third)).abs() < 1e-9);
2719
2720        // The divisions reach the accents and the beams, not the beats alone.
2721        let mut divided = TimeSignature::common();
2722        divided.divide_beats(4).unwrap();
2723        assert_eq!(divided.beat_sequence().to_string(), "{1/4+1/4+1/4+1/4}");
2724        assert_eq!(divided.accent_sequence().to_string(), "{1/4+1/4+1/4+1/4}");
2725        assert_eq!(divided.beam_sequence().to_string(), "{1/4+1/4+1/4+1/4}");
2726        assert_eq!(divided.display_sequence().to_string(), "{4/4}");
2727
2728        // Weighing them then loops over four parts, not eight.
2729        divided.set_accent_weight(&[0.8, 0.2], 0).unwrap();
2730        let weights = divided.accent_weights();
2731        assert_eq!(weights.len(), 4);
2732        assert!((weights[0] - 0.8).abs() < 1e-9);
2733        assert!((weights[1] - 0.2).abs() < 1e-9);
2734    }
2735
2736    #[test]
2737    fn classification_joins_division_and_count() {
2738        assert_eq!(ts("4/4").classification(), "Simple Quadruple");
2739        assert_eq!(ts("6/8").classification(), "Compound Duple");
2740        assert_eq!(ts("3/8").classification(), "Other Single");
2741        assert_eq!(ts("5/4").classification(), "Simple Quintuple");
2742        assert_eq!(ts("13/8").classification(), "Simple 13-uple");
2743        assert_eq!(ts("21/16").classification(), "Compound Septuple");
2744    }
2745
2746    #[test]
2747    fn beat_offsets_partition_the_bar() {
2748        assert_eq!(ts("4/4").beat_offsets(), [0.0, 1.0, 2.0, 3.0]);
2749        assert_eq!(ts("6/8").beat_offsets(), [0.0, 1.5]);
2750        assert_eq!(ts("5/8").beat_offsets(), [0.0, 0.5, 1.0, 1.5, 2.0]);
2751    }
2752
2753    #[test]
2754    fn beat_at_offset_is_one_based_and_bounded() {
2755        assert_eq!(ts("4/4").beat_at_offset(1.5).unwrap(), 2);
2756        assert_eq!(ts("6/8").beat_at_offset(1.5).unwrap(), 2);
2757        assert_eq!(ts("5/8").beat_at_offset(1.5).unwrap(), 4);
2758        assert_eq!(ts("4/4").beat_at_offset(0.0).unwrap(), 1);
2759        assert!(ts("4/4").beat_at_offset(4.0).is_err());
2760        assert!(ts("4/4").beat_at_offset(-0.5).is_err());
2761        assert!(ts("4/4").beat_at_offset(FloatType::NAN).is_err());
2762    }
2763
2764    #[test]
2765    fn irrational_denominators_are_accepted_as_music21_accepts_them() {
2766        let four_three = ts("4/3");
2767        assert!((four_three.bar_quarter_length() - 16.0 / 3.0).abs() < 1e-12);
2768        assert_eq!(four_three.beat_count(), 4);
2769    }
2770
2771    #[test]
2772    fn malformed_ratios_error_instead_of_panicking() {
2773        for ratio in [
2774            "", "4", "4/", "/4", "4/4/4", "x/4", "4/x", "0/4", "4/0", "-1/4",
2775        ] {
2776            assert!(
2777                TimeSignature::from_ratio_string(ratio).is_err(),
2778                "{ratio:?} should not parse"
2779            );
2780        }
2781    }
2782
2783    #[test]
2784    fn display_is_the_ratio_string() {
2785        assert_eq!(ts("7/8").to_string(), "7/8");
2786    }
2787
2788    #[test]
2789    fn a_meter_says_how_it_was_written() {
2790        use crate::meter::TimeSignature;
2791
2792        // music21 reads `ratioString` off the display sequence.
2793        let written = TimeSignature::from_ratio_string("2/4+3/8").unwrap();
2794        assert_eq!(written.ratio_string(), "2/4+3/8");
2795        assert_eq!(written.to_string(), "2/4+3/8");
2796        // What it comes to is unchanged.
2797        assert_eq!((written.numerator(), written.denominator()), (7, 8));
2798
2799        // The order it was written in is part of what it is, which is what
2800        // stops these being two spellings of one meter.
2801        let two_three = TimeSignature::from_ratio_string("2/8+3/8").unwrap();
2802        let three_two = TimeSignature::from_ratio_string("3/8+2/8").unwrap();
2803        assert_eq!(two_three.ratio_string(), "2/8+3/8");
2804        assert_eq!(three_two.ratio_string(), "3/8+2/8");
2805        assert_ne!(two_three, three_two);
2806        // Though they do come to the same ratio, which is music21's
2807        // `ratioEqual`.
2808        assert!(two_three.ratio_equal(&three_two));
2809
2810        // The string re-reads as the meter it came from.
2811        let again = TimeSignature::from_ratio_string(&written.ratio_string()).unwrap();
2812        assert_eq!(again.ratio_string(), written.ratio_string());
2813
2814        // The word before the ratio is not part of the string, though it
2815        // does still make a different meter.
2816        let slow = TimeSignature::from_ratio_string("slow 6/8").unwrap();
2817        let fast = TimeSignature::from_ratio_string("6/8").unwrap();
2818        assert_eq!(slow.ratio_string(), "6/8");
2819        assert_eq!(fast.ratio_string(), "6/8");
2820        assert_ne!(slow, fast);
2821
2822        // A bar written as one ratio is unmoved.
2823        assert_eq!(TimeSignature::common().ratio_string(), "4/4");
2824    }
2825}