Skip to main content

music21/meter/
sequence.rs

1//! How a bar divides: music21's `MeterTerminal` and `MeterSequence`.
2//!
3//! A terminal is a span of a bar written as a ratio, with a weight. A
4//! sequence is a terminal that is made of other terminals, so a bar of `4/4`
5//! partitioned in two is `{1/2+1/2}`, and either half may be partitioned
6//! again. music21 hangs four of these off every time signature — the beats,
7//! the beams, the accents and what is displayed — and this is the part of it
8//! that is arithmetic rather than notation.
9//!
10//! What a sequence may be partitioned into is not free: music21 keeps a list
11//! of the ways each meter is conventionally divided, in priority order, and
12//! partitioning by a count takes the first of those with that many parts.
13//! That is why `5/8` in two is `{2/8+3/8}` and not `{2.5/8+2.5/8}`.
14
15use std::collections::HashMap;
16use std::sync::{Arc, LazyLock, Mutex, PoisonError};
17
18use crate::defaults::{FloatType, UnsignedIntegerType};
19use crate::error::{Error, Result};
20use crate::meter::tools;
21
22/// The partition options of each ratio asked for so far, as music21 keeps
23/// its `getPartitionOptions` in an `lru_cache`: every time signature
24/// divides its spans several levels deep, and building the options as text
25/// each time was most of what making one cost.
26type Options = Arc<[Vec<String>]>;
27static OPTIONS: LazyLock<Mutex<HashMap<(UnsignedIntegerType, UnsignedIntegerType), Options>>> =
28    LazyLock::new(Mutex::default);
29
30/// The ways a ratio divides: [`MeterTerminal::partition_options`], kept.
31fn options_of(numerator: UnsignedIntegerType, denominator: UnsignedIntegerType) -> Options {
32    let key = (numerator, denominator);
33    let mut kept = OPTIONS.lock().unwrap_or_else(PoisonError::into_inner);
34    if let Some(found) = kept.get(&key) {
35        return Arc::clone(found);
36    }
37    let made: Options = built_options(numerator, denominator).into();
38    kept.insert(key, Arc::clone(&made));
39    made
40}
41
42/// The options built afresh: the algorithmic ones, then the presets, each
43/// once and none empty.
44fn built_options(
45    numerator: UnsignedIntegerType,
46    denominator: UnsignedIntegerType,
47) -> Vec<Vec<String>> {
48    let mut options = tools::division_options_algo(numerator, denominator);
49    options.extend(tools::division_options_preset(numerator, denominator));
50    let mut seen = Vec::new();
51    options.retain(|option| {
52        if option.is_empty() || seen.contains(option) {
53            return false;
54        }
55        seen.push(option.clone());
56        true
57    });
58    options
59}
60
61/// How close two quarter lengths must be to count as the same boundary.
62const OFFSET_TOLERANCE: FloatType = 1e-9;
63
64/// How an offset is matched against the boundaries of a level: music21's
65/// `align` argument to `offsetToDepth`.
66#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
67#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
68pub enum OffsetAlign {
69    /// Move the offset back to the start of the finest part holding it, then
70    /// count the levels beginning there. music21's default.
71    #[default]
72    Quantize,
73    /// Count only the levels whose part begins exactly at the offset.
74    Start,
75    /// Count the levels whose part ends exactly at the offset.
76    End,
77}
78
79/// One span of a bar: a ratio, and how strongly it is felt.
80///
81/// A span is a value: every method that divides or weighs it hands back a
82/// new span and leaves this one as it was, as music21's immutable
83/// `MeterTerminal` and `MeterSequence` do.
84#[derive(Clone, Debug)]
85#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
86pub struct MeterTerminal {
87    numerator: UnsignedIntegerType,
88    denominator: UnsignedIntegerType,
89    weight: FloatType,
90    /// What this span is itself divided into, if anything. A terminal with
91    /// parts is music21's `MeterSequence`; one without is a leaf.
92    parts: Vec<MeterTerminal>,
93    /// Whether this was written with its numerators summed over one
94    /// denominator, `3+2/8`, rather than part by part, `3/8+2/8`: music21's
95    /// `summedNumerator`.
96    #[cfg_attr(feature = "serde", serde(default))]
97    summed_numerator: bool,
98}
99
100impl MeterTerminal {
101    /// A span of `numerator/denominator`, undivided, weighing one. A
102    /// numerator of nought is a span of no length, which is what music21's
103    /// `MeterTerminal()` given nothing is.
104    pub fn new(numerator: UnsignedIntegerType, denominator: UnsignedIntegerType) -> Result<Self> {
105        if denominator == 0 {
106            return Err(Error::Meter(
107                "a meter terminal denominator must be non-zero".to_string(),
108            ));
109        }
110        Ok(Self {
111            numerator,
112            denominator,
113            weight: 1.0,
114            parts: Vec::new(),
115            summed_numerator: false,
116        })
117    }
118
119    /// The same, read from `"3/8"`.
120    pub fn from_ratio_string(ratio: &str) -> Result<Self> {
121        let (numerator, denominator) = split_ratio(ratio)?;
122        Self::new(numerator, denominator)
123    }
124
125    /// A span written as parts joined by `+`, each part a ratio: music21's
126    /// `MeterSequence('2/4+2/4')`, which is a bar of four quarters divided in
127    /// two. A part written as a bare numerator takes the denominator of the
128    /// next part that gives one, so `3+2/8` is three eighths and two eighths.
129    ///
130    /// The span itself is written over the denominator its parts share, or
131    /// the least one they all divide into: `3/4+2/4+1/8` is `11/8`.
132    ///
133    /// A span written with a bare numerator is one whose numerators were
134    /// summed, and says so: [`Self::summed_numerator`].
135    pub fn from_partition_string(written: &str) -> Result<Self> {
136        let mut parts = Vec::new();
137        let tokens: Vec<&str> = written.split('+').map(str::trim).collect();
138        // Read from the right, so a bare numerator can take the denominator
139        // of the part that follows it.
140        let mut denominators: Vec<UnsignedIntegerType> = vec![0; tokens.len()];
141        let mut carried = None;
142        for (index, token) in tokens.iter().enumerate().rev() {
143            if let Some((_, denominator)) = token.split_once('/') {
144                carried = Some(parse_number(denominator)?);
145            }
146            denominators[index] = carried.ok_or_else(|| {
147                Error::Meter(format!(
148                    "cannot read a denominator from {token:?} in {written:?}"
149                ))
150            })?;
151        }
152
153        parts.reserve(tokens.len());
154        for (token, denominator) in tokens.iter().zip(denominators) {
155            let numerator = parse_number(token.split('/').next().unwrap_or(token))?;
156            parts.push(Self::new(numerator, denominator)?);
157        }
158        let mut span = Self::from_parts(parts, written)?;
159        span.summed_numerator = tokens.iter().any(|token| !token.contains('/'));
160        Ok(span)
161    }
162
163    /// Whether this span was written with its numerators summed over one
164    /// denominator, as `3+2/8` is and `3/8+2/8` is not: music21's
165    /// `summedNumerator`. The two are the same parts; what differs is how
166    /// the meter is printed, and that a bar written this way is beamed in the
167    /// parts it was written in.
168    #[must_use]
169    pub fn summed_numerator(&self) -> bool {
170        self.summed_numerator
171    }
172
173    /// The same span, saying whether its numerators are written summed:
174    /// music21's `modify(summedNumerator=...)`.
175    pub fn with_summed_numerator(&self, summed: bool) -> Self {
176        let mut out = self.clone();
177        out.summed_numerator = summed;
178        out
179    }
180
181    /// A span of `numerator/denominator` divided into `parts`, taken as
182    /// given: music21's `makeSequence`, which does not check that the parts
183    /// come to the ratio. No parts at all is an undivided span.
184    pub fn sequence(
185        numerator: UnsignedIntegerType,
186        denominator: UnsignedIntegerType,
187        parts: Vec<Self>,
188    ) -> Result<Self> {
189        let mut span = Self::new(numerator, denominator)?;
190        span.parts = parts;
191        Ok(span)
192    }
193
194    /// The same span with a different weight: music21's
195    /// `MeterTerminal.modify(weight=...)` and `MeterSequence.withWeight`.
196    pub fn with_weight(&self, weight: FloatType) -> Self {
197        let mut out = self.clone();
198        out.set_weight(weight);
199        out
200    }
201
202    /// A span made of the parts given, which is what they come to: music21's
203    /// `MeterSequence` given a list of spans. The span is written over the
204    /// denominator its parts share, or the least one they all divide into.
205    ///
206    /// One part alone is that part, undivided, as music21 reads `'4/4'`.
207    pub fn from_parts_given(parts: Vec<Self>) -> Result<Self> {
208        Self::from_parts(parts, "a list of spans")
209    }
210
211    fn from_parts(mut parts: Vec<Self>, written: &str) -> Result<Self> {
212        if parts.len() == 1 {
213            // One part joined to nothing is just that span, as music21 reads
214            // `MeterSequence('4/4')` -- the sequence wrapping is the caller's.
215            return Ok(parts.remove(0));
216        }
217        Self::joining(parts, written)
218    }
219
220    /// A span written over what its parts come to, divided into them: the
221    /// ratio is read off the parts rather than given, which is music21's
222    /// `_updateRatio`.
223    fn joining(parts: Vec<Self>, written: &str) -> Result<Self> {
224        let shared = parts
225            .iter()
226            .map(Self::denominator)
227            .reduce(num::integer::lcm)
228            .ok_or_else(|| Error::Meter(format!("{written:?} is no meter at all")))?;
229        let total = parts
230            .iter()
231            .map(|part| part.numerator() * (shared / part.denominator()))
232            .sum();
233        Self::sequence(total, shared, parts)
234    }
235
236    /// The numerator this span is written with.
237    #[must_use]
238    pub fn numerator(&self) -> UnsignedIntegerType {
239        self.numerator
240    }
241
242    /// The denominator this span is written with.
243    #[must_use]
244    pub fn denominator(&self) -> UnsignedIntegerType {
245        self.denominator
246    }
247
248    /// How long this span is in quarter notes.
249    #[must_use]
250    pub fn quarter_length(&self) -> FloatType {
251        FloatType::from(self.numerator) * (4.0 / FloatType::from(self.denominator))
252    }
253
254    /// Every index it takes to reach the terminal sounding at an offset:
255    /// music21's `offsetToAddress`. Its length is how deep that terminal
256    /// lies, so a span nothing divides answers one index.
257    pub fn offset_to_address(&self, offset: FloatType) -> Result<Vec<usize>> {
258        let length = self.quarter_length();
259        if offset.is_nan() || offset < 0.0 || offset >= length {
260            return Err(Error::Meter(format!(
261                "cannot access from qLenPos {}",
262                super::offset_repr(offset)
263            )));
264        }
265        let index = self.offset_to_index(offset)?;
266        let mut address = vec![index];
267        let (start, _) = self.offset_to_span(offset, false)?;
268        let part = &self.parts[index];
269        if !part.is_empty() {
270            address.extend(part.offset_to_address(offset - start)?);
271        }
272        Ok(address)
273    }
274
275    /// How strongly this span is felt: music21's `weight`.
276    ///
277    /// A span with parts weighs what its parts weigh together, so weight is
278    /// kept on the terminals and read back up the tree.
279    #[must_use]
280    pub fn weight(&self) -> FloatType {
281        if self.parts.is_empty() {
282            self.weight
283        } else {
284            self.parts.iter().map(Self::weight).sum()
285        }
286    }
287
288    /// A span with parts shares the weight out among them in proportion to
289    /// how long each is, as music21 does: the four quarters of a bar weighing
290    /// one take a quarter each, where `{3/4+1/4}` takes three quarters and a
291    /// quarter.
292    fn set_weight(&mut self, weight: FloatType) {
293        self.weight = weight;
294        let whole = self.quarter_length();
295        if self.parts.is_empty() || whole == 0.0 {
296            return;
297        }
298        for part in &mut self.parts {
299            let share = part.quarter_length() / whole;
300            part.set_weight(weight * share);
301        }
302    }
303
304    /// What this span is divided into. Empty where it is a leaf.
305    #[must_use]
306    pub fn parts(&self) -> &[MeterTerminal] {
307        &self.parts
308    }
309
310    /// The same span with the part at `index` replaced by `value`, which has
311    /// to be written over the same ratio: music21's `setIndex`.
312    pub fn set_index(&self, index: usize, value: Self) -> Result<Self> {
313        let current = self
314            .parts
315            .get(index)
316            .ok_or_else(|| Error::Meter(format!("MeterSequence does not have entry {index}.")))?;
317        if !value.ratio_equal(current) {
318            return Err(Error::Meter(format!(
319                "cannot insert {value} into space of {current}"
320            )));
321        }
322        let mut out = self.clone();
323        out.parts[index] = value;
324        Ok(out)
325    }
326
327    /// How many parts this span has at its top level, music21's `len`.
328    #[must_use]
329    pub fn len(&self) -> usize {
330        self.parts.len()
331    }
332
333    /// Whether this span is divided at all.
334    #[must_use]
335    pub fn is_empty(&self) -> bool {
336        self.parts.is_empty()
337    }
338
339    /// How many levels of division this span has: music21's `depth`. A leaf
340    /// is nought.
341    #[must_use]
342    pub fn depth(&self) -> usize {
343        self.parts
344            .iter()
345            .map(|part| 1 + part.depth())
346            .max()
347            .unwrap_or(0)
348    }
349
350    /// Every leaf of this span, in order, which is what `flatten` is made
351    /// of: music21's `_getFlatList`.
352    #[must_use]
353    pub fn flattened(&self) -> Vec<MeterTerminal> {
354        if self.parts.is_empty() {
355            return vec![self.clone()];
356        }
357        self.parts
358            .iter()
359            .flat_map(MeterTerminal::flattened)
360            .collect()
361    }
362
363    /// This span divided into all of its leaves at once, however deeply
364    /// each was divided: music21's `flatten`.
365    pub fn flatten(&self) -> Result<Self> {
366        // Written over what the leaves come to, so a `4/4` bar in eighths
367        // flattens to `8/8`, as music21's does.
368        Self::joining(self.flattened(), "a flattened span")
369    }
370
371    /// What each leaf of this span weighs: music21's `flatWeight`.
372    #[must_use]
373    pub fn flat_weights(&self) -> Vec<FloatType> {
374        self.flattened().iter().map(MeterTerminal::weight).collect()
375    }
376
377    /// Whether another span is written over the same ratio: music21's
378    /// `ratioEqual`. Two spans may weigh differently and be divided
379    /// differently and still be the same meter.
380    #[must_use]
381    pub fn ratio_equal(&self, other: &Self) -> bool {
382        self.numerator == other.numerator && self.denominator == other.denominator
383    }
384
385    /// This span divided into the parts named, as `["2/8", "3/8"]`: music21's
386    /// `partitionedByList` given ratios.
387    ///
388    /// The parts must come to what this span already is; a partition that
389    /// lengthened or shortened the bar would not be one.
390    pub fn partitioned_by_parts(&self, parts: &[&str]) -> Result<Self> {
391        let mut built = Vec::with_capacity(parts.len());
392        for part in parts {
393            built.push(MeterTerminal::from_ratio_string(part)?);
394        }
395        let total: FloatType = built.iter().map(MeterTerminal::quarter_length).sum();
396        if (total - self.quarter_length()).abs() > OFFSET_TOLERANCE {
397            return Err(Error::Meter(format!(
398                "Cannot set partition by {}",
399                python_list(parts)
400            )));
401        }
402        let mut out = self.clone();
403        out.parts = built;
404        out.set_weight(self.weight());
405        Ok(out)
406    }
407
408    /// This span divided into `count` parts, the way music21 divides it:
409    /// music21's `partitionedByCount`.
410    ///
411    /// The first of [`Self::partition_options`] with that many parts wins. A
412    /// count nothing divides into leaves the first option standing, which is
413    /// music21's `loadDefault`.
414    pub fn partitioned_by_count(&self, count: usize, load_default: bool) -> Result<Self> {
415        let options = options_of(self.numerator, self.denominator);
416        let chosen = options.iter().find(|option| option.len() == count);
417        let chosen = match chosen {
418            Some(option) => option,
419            None => {
420                if !load_default || options.is_empty() {
421                    return Err(Error::Meter(format!(
422                        "Cannot set partition by {count} ({}/{})",
423                        self.numerator, self.denominator
424                    )));
425                }
426                &options[0]
427            }
428        };
429        let borrowed: Vec<&str> = chosen.iter().map(String::as_str).collect();
430        self.partitioned_by_parts(&borrowed)
431    }
432
433    /// This span divided by a list of numerators, as `[3, 1]` for
434    /// `{3/4+1/4}`: music21's `partitionedByList`.
435    ///
436    /// music21 reads the list against this span's own denominator where the
437    /// numerators come to its numerator, and against a finer one where they
438    /// come to a multiple of it — `[1, 1, 1, 1]` of a `2/4` bar is four
439    /// eighths, not four quarters.
440    ///
441    /// Failing both, it looks for a division of its own whose numerators are
442    /// the ones asked for, which is how `[1, 1]` of a `4/4` bar comes out as
443    /// two halves and `[1]` as a whole.
444    pub fn partitioned_by_list(&self, numerators: &[UnsignedIntegerType]) -> Result<Self> {
445        if numerators.is_empty() {
446            return Err(Error::Meter(
447                "cannot partition a meter into nothing".to_string(),
448            ));
449        }
450        let total: UnsignedIntegerType = numerators.iter().sum();
451        for multiple in 1..=8 {
452            if total != self.numerator * multiple {
453                continue;
454            }
455            let denominator = self.denominator * multiple;
456            let parts: Vec<String> = numerators
457                .iter()
458                .map(|numerator| format!("{numerator}/{denominator}"))
459                .collect();
460            let borrowed: Vec<&str> = parts.iter().map(String::as_str).collect();
461            return self.partitioned_by_parts(&borrowed);
462        }
463        let asked: Vec<UnsignedIntegerType> = numerators.to_vec();
464        let options = options_of(self.numerator, self.denominator);
465        let matching = options.iter().find(|option| {
466            option
467                .iter()
468                .map(|part| {
469                    part.split('/')
470                        .next()
471                        .and_then(|numerator| numerator.parse().ok())
472                })
473                .collect::<Option<Vec<UnsignedIntegerType>>>()
474                == Some(asked.clone())
475        });
476        if let Some(option) = matching {
477            let borrowed: Vec<&str> = option.iter().map(String::as_str).collect();
478            return self.partitioned_by_parts(&borrowed);
479        }
480        Err(Error::Meter(format!(
481            "Cannot set partition by {} ({}/{})",
482            python_list(numerators),
483            self.numerator,
484            self.denominator
485        )))
486    }
487
488    /// This span with every part divided again, the way music21 divides it
489    /// when nobody has said how: music21's `subdividedPartitionsEqual`.
490    ///
491    /// `divisions` says how many parts each part becomes; `None` asks for
492    /// the division each part conventionally takes — two for a part written
493    /// in a binary numerator, three for one written in three, and threes for
494    /// the compound numerators. A part nothing divides into is an error,
495    /// which is what music21 raises and what a meter written in notes
496    /// shorter than a 128th is forgiven.
497    pub fn subdivided_partitions_equal(&self, divisions: Option<usize>) -> Result<Self> {
498        let mut out = self.clone();
499        for part in &mut out.parts {
500            let count = match divisions {
501                Some(count) => count,
502                None => match part.numerator {
503                    1 | 2 | 4 | 8 | 16 | 32 | 64 => 2,
504                    3 => 3,
505                    6 | 9 | 12 | 15 | 18 | 21 | 24 | 27 => (part.numerator / 3) as usize,
506                    other => other as usize,
507                },
508            };
509            *part = part.partitioned_by_count(count, false)?;
510        }
511        Ok(out)
512    }
513
514    /// The part a path of indices names, and the parts it holds.
515    fn part_at(&self, path: &[usize]) -> &Self {
516        path.iter().fold(self, |span, index| &span.parts[*index])
517    }
518
519    fn part_at_mut(&mut self, path: &[usize]) -> &mut Self {
520        path.iter()
521            .fold(self, |span, index| &mut span.parts[*index])
522    }
523
524    /// Divides the parts of every span named, and answers where those parts
525    /// now are: music21's `_subdivideNested`, which is one level of
526    /// [`Self::subdivided_nested_hierarchy`].
527    fn subdivide_parts_of(
528        &mut self,
529        spans: &[Vec<usize>],
530        divisions: Option<usize>,
531    ) -> Result<Vec<Vec<usize>>> {
532        let mut deeper = Vec::new();
533        for path in spans {
534            let span = self.part_at_mut(path);
535            *span = span.subdivided_partitions_equal(divisions)?;
536            for index in 0..span.len() {
537                let mut child = path.clone();
538                child.push(index);
539                deeper.push(child);
540            }
541        }
542        Ok(deeper)
543    }
544
545    /// This span nested down to a depth: music21's
546    /// `subdividedNestedHierarchy`.
547    ///
548    /// The whole span becomes one part, that part is divided by two, by three
549    /// or by its own numerator, and every division after that is by two or
550    /// three again — so a bar of four quarters at depth two is two halves of
551    /// two quarters each. Whatever partitions the span had are gone.
552    ///
553    /// `normalize_denominators` keeps the parts of a level written over one
554    /// denominator: where they differ, the longer ones are divided again
555    /// until they agree, which is why six eighths come out as sixteenths.
556    ///
557    /// ```
558    /// use music21::meter::MeterTerminal;
559    ///
560    /// let bar = MeterTerminal::new(4, 4)?.subdivided_nested_hierarchy(2, None, true)?;
561    /// assert_eq!(bar.to_string(), "{{{1/4+1/4}+{1/4+1/4}}}");
562    /// # Ok::<(), music21::Error>(())
563    /// ```
564    pub fn subdivided_nested_hierarchy(
565        &self,
566        depth: usize,
567        first_partition_form: Option<UnsignedIntegerType>,
568        normalize_denominators: bool,
569    ) -> Result<Self> {
570        let mut out = self.partitioned_by_count(1, false)?;
571        if depth == 0 {
572            return Ok(out);
573        }
574        let form = first_partition_form.unwrap_or(self.numerator);
575        let first = match form {
576            1 | 2 | 4 | 8 | 16 | 32 => 2,
577            3 => 3,
578            other => other as usize,
579        };
580        out = out.subdivided_partitions_equal(Some(first))?;
581        out.subdivide_nested_below_the_first(depth, normalize_denominators)?;
582        Ok(out)
583    }
584
585    /// The same, with the first division taken from another sequence rather
586    /// than from a count: music21's `subdivideNestedHierarchy` handed a
587    /// `MeterSequence` as its `firstPartitionForm`.
588    ///
589    /// This is how a bar whose beats are not all one length is nested — the
590    /// five eighths of `3+2/8` divide first into a three and a two, which no
591    /// count can say. The form has to come to the same length as this span.
592    ///
593    /// ```
594    /// use music21::meter::MeterTerminal;
595    ///
596    /// let beats = MeterTerminal::from_partition_string("3/8+2/8")?;
597    /// let bar = MeterTerminal::new(5, 8)?.subdivided_nested_hierarchy_by(2, &beats, true)?;
598    /// assert_eq!(bar.to_string(), "{{{1/8+1/8+1/8}+{1/8+1/8}}}");
599    /// # Ok::<(), music21::Error>(())
600    /// ```
601    pub fn subdivided_nested_hierarchy_by(
602        &self,
603        depth: usize,
604        first_partition_form: &Self,
605        normalize_denominators: bool,
606    ) -> Result<Self> {
607        let mut out = self.partitioned_by_count(1, false)?;
608        if depth == 0 {
609            return Ok(out);
610        }
611        let ratio = |span: &Self| format!("{}/{}", span.numerator, span.denominator);
612        let written: Vec<String> = if first_partition_form.parts.is_empty() {
613            vec![ratio(first_partition_form)]
614        } else {
615            first_partition_form.parts.iter().map(ratio).collect()
616        };
617        let borrowed: Vec<&str> = written.iter().map(String::as_str).collect();
618        out.parts[0] = out.parts[0].partitioned_by_parts(&borrowed)?;
619        out.subdivide_nested_below_the_first(depth, normalize_denominators)?;
620        Ok(out)
621    }
622
623    /// Every level of a nested hierarchy below the first division, which is
624    /// by two or three however the first was made.
625    fn subdivide_nested_below_the_first(
626        &mut self,
627        depth: usize,
628        normalize_denominators: bool,
629    ) -> Result<()> {
630        let mut frontier = vec![vec![0]];
631        for _ in 1..depth {
632            frontier = self.subdivide_parts_of(&frontier, None)?;
633            if !normalize_denominators {
634                continue;
635            }
636            // Where a level is written over more than one denominator, the
637            // longer parts are divided again until it is written over one.
638            loop {
639                let denominators: Vec<UnsignedIntegerType> = frontier
640                    .iter()
641                    .map(|path| self.part_at(path).denominator())
642                    .collect();
643                let Some(shortest) = denominators.iter().min().copied() else {
644                    break;
645                };
646                if denominators
647                    .iter()
648                    .all(|denominator| *denominator == shortest)
649                {
650                    break;
651                }
652                let mut evened = Vec::new();
653                for path in &frontier {
654                    if self.part_at(path).denominator() == shortest {
655                        evened.extend(self.subdivide_parts_of(std::slice::from_ref(path), None)?);
656                    } else {
657                        evened.push(path.clone());
658                    }
659                }
660                frontier = evened;
661            }
662        }
663        Ok(())
664    }
665
666    /// The ways music21 conventionally divides this meter, in the order it
667    /// prefers them: music21's `getPartitionOptions`.
668    #[must_use]
669    pub fn partition_options(&self) -> Vec<Vec<String>> {
670        options_of(self.numerator, self.denominator).to_vec()
671    }
672
673    /// The terminals at one level of this sequence: music21's `getLevelList`.
674    ///
675    /// A part that is not divided is taken as it stands. A part that is gets
676    /// recursed into while there are levels left to descend, and at the level
677    /// asked for is either kept whole or, when `flat`, flattened into a
678    /// single terminal carrying that part's own weight.
679    #[must_use]
680    pub fn level_list(&self, level: usize, flat: bool) -> Vec<MeterTerminal> {
681        let mut out = Vec::new();
682        for part in &self.parts {
683            if part.parts.is_empty() {
684                out.push(part.clone());
685            } else if level > 0 {
686                out.extend(part.level_list(level - 1, flat));
687            } else if flat {
688                let mut flattened = part.clone();
689                flattened.weight = part.weight();
690                flattened.parts.clear();
691                out.push(flattened);
692            } else {
693                out.push(part.clone());
694            }
695        }
696        out
697    }
698
699    /// One level of this sequence as a sequence of its own: music21's
700    /// `getLevel`.
701    pub fn level(&self, level: usize, flat: bool) -> Result<Self> {
702        let mut out = Self::new(self.numerator, self.denominator)?;
703        out.weight = self.weight;
704        out.parts = self.level_list(level, flat);
705        Ok(out)
706    }
707
708    /// Where each terminal of a level starts and ends, in quarter lengths
709    /// from the start of this span: music21's `getLevelSpan`.
710    #[must_use]
711    pub fn level_span(&self, level: usize) -> Vec<(FloatType, FloatType)> {
712        let mut spans = Vec::new();
713        let mut position = 0.0;
714        for part in self.level_list(level, true) {
715            let end = position + part.quarter_length();
716            spans.push((position, end));
717            position = end;
718        }
719        spans
720    }
721
722    /// How many levels of this sequence start at an offset: music21's
723    /// `offsetToDepth`.
724    ///
725    /// A level counts when one of its parts begins where the offset does.
726    /// Under [`OffsetAlign::Quantize`] the offset is first moved back to the
727    /// start of the finest part holding it, so an offset inside a part still
728    /// counts the levels that part begins.
729    pub fn offset_to_depth(&self, offset: FloatType, align: OffsetAlign) -> Result<usize> {
730        let length = self.quarter_length();
731        if offset.is_nan() || offset < 0.0 || offset >= length {
732            return Err(Error::Meter(format!(
733                "cannot access from qLenPos {}",
734                super::offset_repr(offset)
735            )));
736        }
737        let depth = self.depth();
738        if depth == 0 {
739            return Ok(0);
740        }
741        let finest = self.level(depth - 1, true)?;
742        let index = finest.offset_to_index(offset)?;
743        let spans = self.level_span(depth - 1);
744        let position = match align {
745            OffsetAlign::Quantize => spans[index].0,
746            OffsetAlign::Start | OffsetAlign::End => offset,
747        };
748        let mut score = 0;
749        for level in 0..depth {
750            for (start, end) in self.level_span(level) {
751                let boundary = match align {
752                    OffsetAlign::Start | OffsetAlign::Quantize => start,
753                    OffsetAlign::End => end,
754                };
755                if (boundary - position).abs() < OFFSET_TOLERANCE {
756                    score += 1;
757                }
758            }
759        }
760        Ok(score)
761    }
762
763    /// This span with the terminals of a level weighed, looping the weights
764    /// given over them: music21's `withLevelWeight`.
765    ///
766    /// A level with no terminals, or no weights to give it, is an error
767    /// rather than a silent nothing.
768    pub fn with_level_weight(&self, level: usize, weights: &[FloatType]) -> Result<Self> {
769        if weights.is_empty() {
770            return Err(Error::Meter(
771                "a weight has to be given to weigh a level with".to_string(),
772            ));
773        }
774        let mut out = self.clone();
775        let mut index = 0;
776        Self::weigh(&mut out.parts, level, weights, &mut index);
777        if index == 0 {
778            return Err(Error::Meter(format!(
779                "this meter has no level {level} to weigh"
780            )));
781        }
782        Ok(out)
783    }
784
785    /// Walks the terminals of a level in order, weighing each in turn. A part
786    /// with parts of its own at the level asked for is read as one terminal,
787    /// so it uses up a weight but has nowhere to keep it, as music21's does.
788    fn weigh(parts: &mut [MeterTerminal], level: usize, weights: &[FloatType], index: &mut usize) {
789        for part in parts.iter_mut() {
790            if part.parts.is_empty() {
791                part.weight = weights[*index % weights.len()];
792                *index += 1;
793            } else if level == 0 {
794                *index += 1;
795            } else {
796                Self::weigh(&mut part.parts, level - 1, weights, index);
797            }
798        }
799    }
800
801    /// Whether every part of a level is the same ratio: music21's
802    /// `isUniformPartition`.
803    #[must_use]
804    pub fn is_uniform_partition(&self, depth: usize) -> bool {
805        let mut numerator = None;
806        let mut denominator = None;
807        for part in self.level_list(depth, false) {
808            if *numerator.get_or_insert(part.numerator) != part.numerator
809                || *denominator.get_or_insert(part.denominator) != part.denominator
810            {
811                return false;
812            }
813        }
814        true
815    }
816
817    /// The parts written out without the braces around them: music21's
818    /// `partitionDisplay`, so a bar of `2/4+6/8` reads as it was written.
819    #[must_use]
820    pub fn partition_display(&self) -> String {
821        self.parts
822            .iter()
823            .map(MeterTerminal::to_string)
824            .collect::<Vec<String>>()
825            .join("+")
826    }
827
828    /// This span divided into `count` parts, as a new sequence: music21's
829    /// `subdivideByCount`. The weight of this span goes with it, and a count
830    /// it cannot be divided into is an error.
831    pub fn subdivide_by_count(&self, count: usize) -> Result<Self> {
832        let mut out = Self::new(self.numerator, self.denominator)?;
833        out.weight = self.weight();
834        out.partitioned_by_count(count, false)
835    }
836
837    /// This span divided the way another sequence is divided: music21's
838    /// `partitionedByOtherMeterSequence`. The two have to be written over
839    /// the same ratio, and the answer keeps the weight this span had.
840    pub fn partitioned_by_other(&self, other: &Self) -> Result<Self> {
841        if !self.ratio_equal(other) {
842            return Err(Error::Meter(
843                "Cannot set partition for unequal MeterSequences".to_string(),
844            ));
845        }
846        let mut out = self.clone();
847        out.parts = other.parts.clone();
848        out.set_weight(self.weight());
849        Ok(out)
850    }
851
852    /// What each terminal of a level weighs: music21's `getLevelWeight`.
853    #[must_use]
854    pub fn level_weight(&self, level: usize) -> Vec<FloatType> {
855        self.level_list(level, true)
856            .iter()
857            .map(MeterTerminal::weight)
858            .collect()
859    }
860
861    /// This span divided by a list of numerators, as a new sequence:
862    /// music21's `subdivideByList`.
863    pub fn subdivide_by_list(&self, numerators: &[UnsignedIntegerType]) -> Result<Self> {
864        let mut out = Self::new(self.numerator, self.denominator)?;
865        out.weight = self.weight();
866        out.partitioned_by_list(numerators)
867    }
868
869    /// Which part an offset in quarter notes falls in: music21's
870    /// `offsetToIndex`. An offset outside the span is an error.
871    pub fn offset_to_index(&self, offset: FloatType) -> Result<usize> {
872        let offset = super::offset_within(offset, self.quarter_length())?;
873        let mut start = 0.0;
874        for (index, part) in self.parts.iter().enumerate() {
875            let end = start + part.quarter_length();
876            if offset >= start - OFFSET_TOLERANCE && offset < end - OFFSET_TOLERANCE {
877                return Ok(index);
878            }
879            start = end;
880        }
881        Ok(self.parts.len().saturating_sub(1))
882    }
883
884    /// Where the part an offset falls in begins and ends: music21's
885    /// `offsetToSpan`. With `permit_meter_modulus` an offset past the end of
886    /// the span is read within it.
887    pub fn offset_to_span(
888        &self,
889        offset: FloatType,
890        permit_meter_modulus: bool,
891    ) -> Result<(FloatType, FloatType)> {
892        let length = self.quarter_length();
893        let offset = if permit_meter_modulus && offset >= length {
894            offset.rem_euclid(length)
895        } else {
896            offset
897        };
898        let index = self.offset_to_index(offset)?;
899        let mut start = 0.0;
900        for (position, part) in self.parts.iter().enumerate() {
901            let end = start + part.quarter_length();
902            if position == index {
903                return Ok((start, end));
904            }
905            start = end;
906        }
907        Ok((0.0, length))
908    }
909
910    /// The weight of the part an offset falls in: music21's `offsetToWeight`.
911    pub fn offset_to_weight(&self, offset: FloatType) -> Result<FloatType> {
912        let index = self.offset_to_index(offset)?;
913        Ok(self
914            .parts
915            .get(index)
916            .map_or(self.weight, MeterTerminal::weight))
917    }
918
919    /// How this span is written: `3/4` undivided, `{1/4+1/4+1/4}` divided.
920    #[must_use]
921    pub fn partition_string(&self) -> String {
922        if self.parts.is_empty() {
923            return format!("{}/{}", self.numerator, self.denominator);
924        }
925        let inner: Vec<String> = self
926            .parts
927            .iter()
928            .map(MeterTerminal::partition_string)
929            .collect();
930        format!("{{{}}}", inner.join("+"))
931    }
932}
933
934/// Two spans are equal when they are written over the same ratio, written
935/// the same way and divided into equal parts; a span nothing divides weighs
936/// the same as well. A span with parts weighs what they weigh, so its own
937/// weight is not compared twice.
938impl PartialEq for MeterTerminal {
939    fn eq(&self, other: &Self) -> bool {
940        self.numerator == other.numerator
941            && self.denominator == other.denominator
942            && self.summed_numerator == other.summed_numerator
943            && self.parts == other.parts
944            && (!self.parts.is_empty() || self.weight == other.weight)
945    }
946}
947
948impl std::hash::Hash for MeterTerminal {
949    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
950        self.numerator.hash(state);
951        self.denominator.hash(state);
952        self.summed_numerator.hash(state);
953        if self.parts.is_empty() {
954            // Nought and minus nought are equal, so they hash alike.
955            let weight = if self.weight == 0.0 { 0.0 } else { self.weight };
956            weight.to_bits().hash(state);
957        }
958        self.parts.hash(state);
959    }
960}
961
962impl std::fmt::Display for MeterTerminal {
963    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
964        formatter.write_str(&self.partition_string())
965    }
966}
967
968/// A list of parts as Python prints it, since music21 names a partition it
969/// cannot set by printing the list it was handed: `['3/4', '1/8']` for the
970/// written parts, `[1, 1]` for their numerators.
971fn python_list<T: std::fmt::Display>(parts: &[T]) -> String {
972    let quote = |part: &T| {
973        let written = part.to_string();
974        if written.parse::<FloatType>().is_ok() {
975            written
976        } else {
977            format!("'{written}'")
978        }
979    };
980    format!(
981        "[{}]",
982        parts.iter().map(quote).collect::<Vec<String>>().join(", ")
983    )
984}
985
986/// One of the numbers a meter is written with.
987fn parse_number(text: &str) -> Result<UnsignedIntegerType> {
988    text.trim()
989        .parse()
990        .map_err(|_| Error::Meter(format!("{text:?} is not a number a meter is written with")))
991}
992
993/// `"3/8"` as the two numbers it is written with.
994fn split_ratio(ratio: &str) -> Result<(UnsignedIntegerType, UnsignedIntegerType)> {
995    let trimmed = ratio.trim();
996    let (numerator, denominator) = trimmed.split_once('/').ok_or_else(|| {
997        Error::Meter(format!(
998            "a meter terminal is written numerator/denominator, not {ratio:?}"
999        ))
1000    })?;
1001    let read = |part: &str, label: &str| {
1002        part.trim()
1003            .parse::<UnsignedIntegerType>()
1004            .map_err(|_| Error::Meter(format!("cannot read a {label} from {part:?} in {ratio:?}")))
1005    };
1006    Ok((
1007        read(numerator, "numerator")?,
1008        read(denominator, "denominator")?,
1009    ))
1010}
1011
1012#[cfg(test)]
1013mod tests {
1014    use std::sync::Arc;
1015
1016    use super::MeterTerminal;
1017    use super::OffsetAlign;
1018    use super::options_of;
1019
1020    /// The options of a ratio are built once and kept, as music21 keeps
1021    /// them in an `lru_cache`: building them as text for every span every
1022    /// time signature divides was most of what making one cost.
1023    #[test]
1024    fn partition_options_are_kept() {
1025        let first = options_of(4, 4);
1026        assert!(Arc::ptr_eq(&first, &options_of(4, 4)));
1027        assert_eq!(
1028            MeterTerminal::new(4, 4).unwrap().partition_options(),
1029            first.to_vec()
1030        );
1031    }
1032
1033    /// music21's own `divisionOptionsAlgo(4, 4)`, in its order.
1034    ///
1035    /// The order is what decides a partition: `partition_by_count` takes the
1036    /// first option of the length asked for, so `4/4` in two is `1/2+1/2`
1037    /// and not `2/4+2/4`, which comes later in the same list.
1038    #[test]
1039    fn levels_are_read_as_music21_reads_them() {
1040        // Read off music21 11.0.0b9: TimeSignature("4/4").beatSequence.
1041        let bar = MeterTerminal::new(4, 4)
1042            .unwrap()
1043            .partitioned_by_parts(&["4/4"])
1044            .unwrap()
1045            .partitioned_by_count(4, true)
1046            .unwrap()
1047            .subdivided_partitions_equal(None)
1048            .unwrap();
1049        assert_eq!(bar.to_string(), "{{1/8+1/8}+{1/8+1/8}+{1/8+1/8}+{1/8+1/8}}");
1050
1051        // getLevelList(0, True) is four quarters; (1, True) is eight eighths.
1052        let first: Vec<String> = bar
1053            .level_list(0, true)
1054            .iter()
1055            .map(MeterTerminal::to_string)
1056            .collect();
1057        assert_eq!(first, ["1/4", "1/4", "1/4", "1/4"]);
1058        let second: Vec<String> = bar
1059            .level_list(1, true)
1060            .iter()
1061            .map(MeterTerminal::to_string)
1062            .collect();
1063        assert_eq!(second, ["1/8"; 8]);
1064
1065        // music21 reads this bar as two levels deep.
1066        assert_eq!(bar.depth(), 2);
1067        assert_eq!(bar.level_span(0).len(), 4);
1068        assert_eq!(bar.level_span(0)[1], (1.0, 2.0));
1069
1070        // Every part of either level is the same ratio.
1071        assert!(bar.is_uniform_partition(0));
1072        assert!(bar.is_uniform_partition(1));
1073        // music21 reads the depth at an offset as 2, 1, 2 across the first beat.
1074        assert_eq!(bar.offset_to_depth(0.0, OffsetAlign::Quantize).unwrap(), 2);
1075        assert_eq!(bar.offset_to_depth(0.5, OffsetAlign::Quantize).unwrap(), 1);
1076        assert_eq!(bar.offset_to_depth(1.0, OffsetAlign::Quantize).unwrap(), 2);
1077    }
1078
1079    #[test]
1080    fn a_bar_written_in_unequal_parts_is_not_uniform() {
1081        let bar = MeterTerminal::new(5, 8)
1082            .unwrap()
1083            .partitioned_by_parts(&["2/8", "3/8"])
1084            .unwrap();
1085        assert!(!bar.is_uniform_partition(0));
1086        assert_eq!(bar.partition_display(), "2/8+3/8");
1087        assert_eq!(bar.depth(), 1);
1088    }
1089
1090    #[test]
1091    fn subdividing_leaves_the_span_alone_and_returns_a_new_one() {
1092        let beat = MeterTerminal::new(1, 4).unwrap().with_weight(0.5);
1093        let divided = beat.subdivide_by_count(2).unwrap();
1094        assert_eq!(divided.to_string(), "{1/8+1/8}");
1095        // music21's subdivide does not happen in place, and carries the
1096        // weight of the span it divided.
1097        assert!(beat.is_empty());
1098        assert!((divided.weight() - 0.5).abs() < 1e-9);
1099
1100        let listed = MeterTerminal::new(5, 8)
1101            .unwrap()
1102            .subdivide_by_list(&[2, 3])
1103            .unwrap();
1104        assert_eq!(listed.to_string(), "{2/8+3/8}");
1105    }
1106
1107    #[test]
1108    fn the_options_come_in_the_order_music21_offers_them() {
1109        use crate::meter::tools::division_options_algo as division_options_algorithmic;
1110
1111        let offered: Vec<Vec<String>> = division_options_algorithmic(4, 4)
1112            .into_iter()
1113            .take(6)
1114            .collect();
1115        assert_eq!(
1116            offered,
1117            vec![
1118                vec!["1/4"; 4],
1119                vec!["1/8"; 8],
1120                vec!["1/16"; 16],
1121                vec!["1/2"; 2],
1122                vec!["4/4"],
1123                vec!["2/4"; 2],
1124            ]
1125        );
1126
1127        // A compound meter is offered its threes first, and a five the two
1128        // groupings music21 keeps for it.
1129        assert_eq!(division_options_algorithmic(6, 8)[0], vec!["3/8"; 2]);
1130        assert_eq!(
1131            division_options_algorithmic(5, 8)[0],
1132            vec!["2/8".to_string(), "3/8".to_string()]
1133        );
1134    }
1135
1136    /// music21's own examples, which is what this has to reproduce.
1137    #[test]
1138    fn a_bar_divides_the_way_music21_divides_it() {
1139        let four_four = MeterTerminal::from_ratio_string("4/4").unwrap();
1140        let four_four = four_four.partitioned_by_count(2, true).unwrap();
1141        assert_eq!(four_four.partition_string(), "{1/2+1/2}");
1142        let four_four = four_four.partitioned_by_count(4, true).unwrap();
1143        assert_eq!(four_four.partition_string(), "{1/4+1/4+1/4+1/4}");
1144
1145        // Irregular meters take the grouping music21 keeps for them.
1146        let five_eight = MeterTerminal::from_ratio_string("5/8").unwrap();
1147        let five_eight = five_eight.partitioned_by_count(2, true).unwrap();
1148        assert_eq!(five_eight.partition_string(), "{2/8+3/8}");
1149        let five_eight = five_eight.partitioned_by_count(3, true).unwrap();
1150        assert_eq!(five_eight.partition_string(), "{2/8+2/8+1/8}");
1151
1152        // A count nothing divides into falls back to the first option.
1153        let also_five = MeterTerminal::from_ratio_string("5/8")
1154            .unwrap()
1155            .partitioned_by_count(11, true)
1156            .unwrap();
1157        assert_eq!(also_five.partition_string(), "{2/8+3/8}");
1158        assert!(
1159            MeterTerminal::from_ratio_string("5/8")
1160                .unwrap()
1161                .partitioned_by_count(11, false)
1162                .is_err()
1163        );
1164
1165        // Compound meters divide into threes first.
1166        let six_eight = MeterTerminal::from_ratio_string("6/8")
1167            .unwrap()
1168            .partitioned_by_count(2, true)
1169            .unwrap();
1170        assert_eq!(six_eight.partition_string(), "{3/8+3/8}");
1171    }
1172
1173    #[test]
1174    fn a_partition_must_come_to_what_the_bar_is() {
1175        let bar = MeterTerminal::from_ratio_string("4/4").unwrap();
1176        let bar = bar.partitioned_by_parts(&["3/4", "1/8", "1/8"]).unwrap();
1177        assert_eq!(bar.partition_string(), "{3/4+1/8+1/8}");
1178        assert!(bar.partitioned_by_parts(&["3/4", "1/8", "5/8"]).is_err());
1179
1180        // A list of numerators is read against a finer note value where it
1181        // comes to a multiple of the meter's own.
1182        let halves = MeterTerminal::from_ratio_string("2/4").unwrap();
1183        let halves = halves.partitioned_by_list(&[1, 1]).unwrap();
1184        assert_eq!(halves.partition_string(), "{1/4+1/4}");
1185        let halves = halves.partitioned_by_list(&[1, 1, 1, 1]).unwrap();
1186        assert_eq!(halves.partition_string(), "{1/8+1/8+1/8+1/8}");
1187        assert!(halves.partitioned_by_list(&[1, 1, 1]).is_err());
1188    }
1189
1190    #[test]
1191    fn an_offset_finds_the_part_it_falls_in() {
1192        let bar = MeterTerminal::from_ratio_string("4/4")
1193            .unwrap()
1194            .partitioned_by_count(4, true)
1195            .unwrap();
1196        assert_eq!(bar.offset_to_index(0.0).unwrap(), 0);
1197        assert_eq!(bar.offset_to_index(1.5).unwrap(), 1);
1198        assert_eq!(bar.offset_to_index(3.99).unwrap(), 3);
1199        assert_eq!(bar.offset_to_span(1.5, false).unwrap(), (1.0, 2.0));
1200        // Past the bar is an error, or the same offset read within it.
1201        assert!(bar.offset_to_index(4.0).is_err());
1202        assert!(bar.offset_to_index(-0.5).is_err());
1203        assert_eq!(bar.offset_to_span(5.5, true).unwrap(), (1.0, 2.0));
1204    }
1205
1206    #[test]
1207    fn a_span_says_how_deep_and_how_flat_it_is() {
1208        let bar = MeterTerminal::from_ratio_string("4/4").unwrap();
1209        assert_eq!(bar.depth(), 0);
1210        let bar = bar.partitioned_by_count(2, true).unwrap();
1211        assert_eq!(bar.depth(), 1);
1212        let first = bar.parts()[0].partitioned_by_count(2, true).unwrap();
1213        let bar = bar.set_index(0, first).unwrap();
1214        assert_eq!(bar.depth(), 2);
1215        assert_eq!(bar.partition_string(), "{{1/4+1/4}+1/2}");
1216        assert_eq!(bar.flattened().len(), 3);
1217        assert!((bar.flattened()[0].quarter_length() - 1.0).abs() < 1e-9);
1218    }
1219
1220    /// Read off music21's own `MeterSequence`.
1221    #[test]
1222    fn parts_joined_by_a_plus_are_read_as_a_partition() {
1223        let joined = MeterTerminal::from_partition_string("2/4+2/4").unwrap();
1224        assert_eq!(joined.to_string(), "{2/4+2/4}");
1225        assert_eq!((joined.numerator(), joined.denominator()), (4, 4));
1226        assert_eq!(joined.len(), 2);
1227
1228        // A bare numerator takes the denominator of the part after it.
1229        let shared = MeterTerminal::from_partition_string("3+2/8").unwrap();
1230        assert_eq!(shared.to_string(), "{3/8+2/8}");
1231        assert_eq!((shared.numerator(), shared.denominator()), (5, 8));
1232
1233        // Mixed denominators are written over the least they all divide into.
1234        let mixed = MeterTerminal::from_partition_string("3/4+2/4+1/8").unwrap();
1235        assert_eq!(mixed.to_string(), "{3/4+2/4+1/8}");
1236        assert_eq!((mixed.numerator(), mixed.denominator()), (11, 8));
1237        assert!((mixed.quarter_length() - 5.5).abs() < 1e-9);
1238
1239        // One part joined to nothing is the span itself, undivided.
1240        let alone = MeterTerminal::from_partition_string("4/4").unwrap();
1241        assert_eq!(alone.to_string(), "4/4");
1242        assert!(alone.is_empty());
1243
1244        assert!(MeterTerminal::from_partition_string("2+2").is_err());
1245        assert!(MeterTerminal::from_partition_string("half/4").is_err());
1246    }
1247
1248    /// music21's own example: a bar of four quarters whose second quarter is
1249    /// divided into sixteenths.
1250    #[test]
1251    fn an_address_says_every_index_down_to_the_terminal() {
1252        let bar = MeterTerminal::new(4, 4)
1253            .unwrap()
1254            .partitioned_by_count(4, true)
1255            .unwrap();
1256        let second = bar.parts()[1].partitioned_by_count(4, true).unwrap();
1257        let bar = bar.set_index(1, second).unwrap();
1258        assert_eq!(bar.to_string(), "{1/4+{1/16+1/16+1/16+1/16}+1/4+1/4}");
1259
1260        assert_eq!(bar.offset_to_address(0.0).unwrap(), [0]);
1261        assert_eq!(bar.offset_to_address(1.0).unwrap(), [1, 0]);
1262        assert_eq!(bar.offset_to_address(1.5).unwrap(), [1, 2]);
1263        assert_eq!(bar.offset_to_address(3.0).unwrap(), [3]);
1264        // How deep the terminal lies is how long its address is.
1265        assert_eq!(bar.offset_to_address(1.5).unwrap().len(), 2);
1266        assert!(bar.offset_to_address(-1.0).is_err());
1267    }
1268
1269    /// Every expectation here was read off music21.
1270    #[test]
1271    fn a_span_flattens_to_what_its_leaves_come_to() {
1272        let bar = MeterTerminal::new(4, 4)
1273            .unwrap()
1274            .partitioned_by_count(4, true)
1275            .unwrap()
1276            .subdivided_partitions_equal(Some(2))
1277            .unwrap();
1278
1279        let flat = bar.flatten().unwrap();
1280        assert_eq!(flat.to_string(), "{1/8+1/8+1/8+1/8+1/8+1/8+1/8+1/8}");
1281        // Written over what the leaves come to, not over the bar it came from.
1282        assert_eq!((flat.numerator(), flat.denominator()), (8, 8));
1283        assert_eq!(bar.flat_weights(), vec![0.125; 8]);
1284        assert_eq!(bar.level_weight(0), vec![0.25; 4]);
1285        assert_eq!(bar.level_weight(1), vec![0.125; 8]);
1286    }
1287
1288    /// Every expectation here was read off music21.
1289    #[test]
1290    fn a_span_takes_the_division_and_the_shape_of_another() {
1291        let quarters = MeterTerminal::new(4, 4)
1292            .unwrap()
1293            .partitioned_by_count(4, true)
1294            .unwrap();
1295        let halves = MeterTerminal::new(4, 4)
1296            .unwrap()
1297            .partitioned_by_count(2, true)
1298            .unwrap();
1299
1300        let quarters = quarters.partitioned_by_other(&halves).unwrap();
1301        assert_eq!(quarters.to_string(), "{1/2+1/2}");
1302        // The weight it had, which its new parts share out between them.
1303        assert_eq!(quarters.weight(), 1.0);
1304
1305        // A division cannot relength the bar, whichever way it is asked for.
1306        let three = MeterTerminal::new(3, 4).unwrap();
1307        assert!(quarters.partitioned_by_other(&three).is_err());
1308
1309        let thirds = MeterTerminal::from_partition_string("1/4+1/4+1/4").unwrap();
1310        let sixths = MeterTerminal::from_partition_string("3/8+3/8").unwrap();
1311
1312        assert!(thirds.ratio_equal(&MeterTerminal::new(3, 4).unwrap()));
1313        assert!(!thirds.ratio_equal(&sixths));
1314    }
1315}