Skip to main content

music21/
tree.rs

1//! A stream's elements as spans of time, and the moments where what sounds
2//! changes: music21's `tree` package, its timespan trees and
3//! verticalities.
4//!
5//! [`as_timespans`] reads every element of a stream, nested ones included,
6//! as an [`ElementTimespan`] from where it starts to where it ends, with the
7//! streams it stands in; a [`TimespanTree`] answers which start, stop or
8//! sound at an offset; and a [`Verticality`] is one such offset, with the
9//! pitches sounding there.
10//!
11//! ```
12//! use music21::tinynotation::from_tiny_notation;
13//! use music21::tree::{Flatten, as_timespans};
14//!
15//! let line = from_tiny_notation("4/4 c2 e4 g")?;
16//! let tree = as_timespans(&line, Flatten::Flat, None);
17//! let third = tree.verticality_at(3.0);
18//! assert_eq!(third.start_timespans().len(), 1);
19//! assert_eq!(tree.maximum_overlap(), Some(3));
20//! # Ok::<(), music21::Error>(())
21//! ```
22
23pub mod core;
24
25use crate::{
26    chord::Chord,
27    defaults::{FloatType, IntegerType},
28    error::{Error, Result},
29    makenotation::op_frac,
30    pitch::Pitch,
31    stream::{Stream, StreamElement, StreamKind},
32    voiceleading::VoiceLeadingQuartet,
33};
34
35/// How [`as_timespans`] reads the streams a stream holds.
36#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
37pub enum Flatten {
38    /// Their elements only: music21's `flatten=True`.
39    #[default]
40    Flat,
41    /// Their elements and the streams themselves: music21's
42    /// `flatten='semiFlat'`.
43    SemiFlat,
44}
45
46/// One element of a stream, from where it starts to where it ends:
47/// music21's `ElementTimespan`, and its `PitchedTimespan` where the element
48/// is a note-like one or a stream.
49#[derive(Clone, Debug)]
50pub struct ElementTimespan<'a> {
51    element: &'a StreamElement,
52    offset: FloatType,
53    end_time: FloatType,
54    parent_offset: FloatType,
55    parent_end_time: FloatType,
56    parentage: Vec<&'a Stream>,
57    measure: Option<IntegerType>,
58    pitched: bool,
59}
60
61impl<'a> ElementTimespan<'a> {
62    /// The element.
63    pub fn element(&self) -> &'a StreamElement {
64        self.element
65    }
66
67    /// Where it starts in the stream read.
68    pub fn offset(&self) -> FloatType {
69        self.offset
70    }
71
72    /// Where it ends: music21's `endTime`.
73    pub fn end_time(&self) -> FloatType {
74        self.end_time
75    }
76
77    /// How long it lasts.
78    pub fn quarter_length(&self) -> FloatType {
79        self.end_time - self.offset
80    }
81
82    /// Where the stream holding it starts: music21's `parentOffset`.
83    pub fn parent_offset(&self) -> FloatType {
84        self.parent_offset
85    }
86
87    /// Where the stream holding it ends: music21's `parentEndTime`.
88    pub fn parent_end_time(&self) -> FloatType {
89        self.parent_end_time
90    }
91
92    /// The streams it stands in, the one holding it first and the stream
93    /// read last: music21's `parentage`.
94    pub fn parentage(&self) -> &[&'a Stream] {
95        &self.parentage
96    }
97
98    /// The part it is in, if any: music21's `part`.
99    pub fn part(&self) -> Option<&'a Stream> {
100        self.parentage
101            .iter()
102            .copied()
103            .find(|stream| matches!(stream.kind(), StreamKind::Part | StreamKind::PartStaff))
104    }
105
106    /// The number of the measure it is in, if it is in one: music21's
107    /// `measureNumber`.
108    pub fn measure_number(&self) -> Option<IntegerType> {
109        self.measure
110    }
111
112    /// Whether it is music21's `PitchedTimespan`: the element a note, chord,
113    /// chord symbol, unpitched stroke, percussion chord or stream.
114    pub fn is_pitched(&self) -> bool {
115        self.pitched
116    }
117
118    /// The pitches the element sounds, none for one that is not pitched:
119    /// music21's `pitches`.
120    pub fn pitches(&self) -> Vec<Pitch> {
121        if !self.pitched {
122            return Vec::new();
123        }
124        match self.element {
125            StreamElement::ChordSymbol(symbol) => symbol.pitches().unwrap_or_default(),
126            element => element.pitches(),
127        }
128    }
129}
130
131impl ElementTimespan<'_> {
132    /// The same element over another span: music21's `new`.
133    fn spanning(&self, offset: FloatType, end_time: FloatType) -> Self {
134        Self {
135            offset,
136            end_time,
137            ..self.clone()
138        }
139    }
140}
141
142/// Whether music21 makes a `PitchedTimespan` of an element: a `NotRest` or
143/// a stream.
144fn is_pitched(element: &StreamElement) -> bool {
145    matches!(
146        element,
147        StreamElement::Note(_)
148            | StreamElement::Chord(_)
149            | StreamElement::ChordSymbol(_)
150            | StreamElement::Unpitched(_)
151            | StreamElement::PercussionChord(_)
152            | StreamElement::Stream(_)
153    )
154}
155
156/// The timespans of a stream in time, each answer in music21's order: by
157/// where they start, then where they end, then as the stream holds them:
158/// music21's `TimespanTree`.
159#[derive(Clone, Debug)]
160pub struct TimespanTree<'a> {
161    source: &'a Stream,
162    timespans: Vec<ElementTimespan<'a>>,
163}
164
165/// Every element of a stream, nested ones included, as a timespan:
166/// music21's `asTimespans`. `filter` keeps only the elements it accepts, as
167/// music21's `classList` does; the streams are walked into either way.
168pub fn as_timespans<'a>(
169    stream: &'a Stream,
170    flatten: Flatten,
171    filter: Option<fn(&StreamElement) -> bool>,
172) -> TimespanTree<'a> {
173    let mut timespans = Vec::new();
174    let measure = (stream.kind() == StreamKind::Measure).then(|| stream.number());
175    walk(
176        stream,
177        0.0,
178        &mut vec![stream],
179        measure,
180        flatten,
181        filter,
182        &mut timespans,
183    );
184    timespans.sort_by(|a: &ElementTimespan<'_>, b: &ElementTimespan<'_>| {
185        a.offset
186            .total_cmp(&b.offset)
187            .then_with(|| a.end_time.total_cmp(&b.end_time))
188    });
189    TimespanTree {
190        source: stream,
191        timespans,
192    }
193}
194
195fn walk<'a>(
196    stream: &'a Stream,
197    initial: FloatType,
198    parentage: &mut Vec<&'a Stream>,
199    measure: Option<IntegerType>,
200    flatten: Flatten,
201    filter: Option<fn(&StreamElement) -> bool>,
202    out: &mut Vec<ElementTimespan<'a>>,
203) {
204    let parent_end_time = op_frac(initial + stream.end_offset());
205    let reversed: Vec<&'a Stream> = parentage.iter().rev().copied().collect();
206    for event in stream.events() {
207        let offset = op_frac(event.offset() + initial);
208        let element = event.element();
209        // A measure's own number is its measure number, as music21 reads it.
210        let mut own_measure = measure;
211        if let StreamElement::Stream(inner) = element {
212            parentage.push(inner);
213            let inner_measure = if inner.kind() == StreamKind::Measure {
214                Some(inner.number())
215            } else {
216                measure
217            };
218            walk(
219                inner,
220                offset,
221                parentage,
222                inner_measure,
223                flatten,
224                filter,
225                out,
226            );
227            parentage.pop();
228            own_measure = inner_measure;
229            if flatten == Flatten::Flat {
230                continue;
231            }
232        }
233        if filter.is_some_and(|accepts| !accepts(element)) {
234            continue;
235        }
236        out.push(ElementTimespan {
237            element,
238            offset,
239            end_time: op_frac(offset + element.quarter_length()),
240            parent_offset: initial,
241            parent_end_time,
242            parentage: reversed.clone(),
243            measure: own_measure,
244            pitched: is_pitched(element),
245        });
246    }
247}
248
249/// music21's `Pitch.__le__`: lower in pitch space, or the same pitch
250/// spelled the same.
251fn at_most(a: &Pitch, b: &Pitch) -> bool {
252    a.ps() < b.ps() || a == b
253}
254
255impl<'a> TimespanTree<'a> {
256    /// Every timespan, in order.
257    pub fn timespans(&self) -> &[ElementTimespan<'a>] {
258        &self.timespans
259    }
260
261    /// How many timespans there are.
262    pub fn len(&self) -> usize {
263        self.timespans.len()
264    }
265
266    /// Whether there are none.
267    pub fn is_empty(&self) -> bool {
268        self.timespans.is_empty()
269    }
270
271    /// Where the earliest timespan starts: music21's `lowestPosition`.
272    pub fn lowest_position(&self) -> Option<FloatType> {
273        self.timespans.first().map(|span| span.offset)
274    }
275
276    /// Where the latest starts: music21's `highestPosition`.
277    pub fn highest_position(&self) -> Option<FloatType> {
278        self.timespans.last().map(|span| span.offset)
279    }
280
281    /// Where the last to end ends: music21's `endTime`.
282    pub fn end_time(&self) -> Option<FloatType> {
283        self.timespans
284            .iter()
285            .map(|span| span.end_time)
286            .reduce(FloatType::max)
287    }
288
289    /// Each offset a timespan starts at, once, in order: music21's
290    /// `allOffsets`.
291    pub fn all_offsets(&self) -> Vec<FloatType> {
292        let mut offsets: Vec<FloatType> = self.timespans.iter().map(|span| span.offset).collect();
293        offsets.dedup();
294        offsets
295    }
296
297    /// Each offset a timespan starts or ends at, once, in order: music21's
298    /// `allTimePoints`.
299    pub fn all_time_points(&self) -> Vec<FloatType> {
300        let mut points: Vec<FloatType> = self
301            .timespans
302            .iter()
303            .flat_map(|span| [span.offset, span.end_time])
304            .collect();
305        points.sort_by(FloatType::total_cmp);
306        points.dedup();
307        points
308    }
309
310    /// The first offset after this one a timespan starts at: music21's
311    /// `getPositionAfter`.
312    pub fn position_after(&self, offset: FloatType) -> Option<FloatType> {
313        self.timespans
314            .iter()
315            .map(|span| span.offset)
316            .find(|start| *start > offset)
317    }
318
319    /// The last offset before this one a timespan starts at: music21's
320    /// `getPositionBefore`.
321    pub fn position_before(&self, offset: FloatType) -> Option<FloatType> {
322        self.timespans
323            .iter()
324            .rev()
325            .map(|span| span.offset)
326            .find(|start| *start < offset)
327    }
328
329    /// The timespans starting at an offset: music21's `elementsStartingAt`.
330    pub fn starting_at(&self, offset: FloatType) -> Vec<&ElementTimespan<'a>> {
331        self.timespans
332            .iter()
333            .filter(|span| span.offset == offset)
334            .collect()
335    }
336
337    /// The timespans ending at an offset: music21's `elementsStoppingAt`.
338    pub fn stopping_at(&self, offset: FloatType) -> Vec<&ElementTimespan<'a>> {
339        self.timespans
340            .iter()
341            .filter(|span| span.end_time == offset)
342            .collect()
343    }
344
345    /// The timespans sounding across an offset, started before it and
346    /// ending after: music21's `elementsOverlappingOffset`.
347    pub fn overlapping(&self, offset: FloatType) -> Vec<&ElementTimespan<'a>> {
348        self.timespans
349            .iter()
350            .filter(|span| span.offset < offset && offset < span.end_time)
351            .collect()
352    }
353
354    /// The offsets a timespan starts at, or with `include_stop_points` also
355    /// ends at, where another sounds across: music21's
356    /// `overlapTimePoints`.
357    pub fn overlap_time_points(&self, include_stop_points: bool) -> Vec<FloatType> {
358        let points = if include_stop_points {
359            self.all_time_points()
360        } else {
361            self.all_offsets()
362        };
363        points
364            .into_iter()
365            .filter(|point| !self.overlapping(*point).is_empty())
366            .collect()
367    }
368
369    /// What starts, stops and sounds across an offset: music21's
370    /// `getVerticalityAt`.
371    pub fn verticality_at(&self, offset: FloatType) -> Verticality<'_, 'a> {
372        Verticality {
373            tree: self,
374            offset,
375            start_timespans: self.starting_at(offset),
376            overlap_timespans: self.overlapping(offset),
377            stop_timespans: self.stopping_at(offset),
378        }
379    }
380
381    /// The verticality at an offset where something starts there, or the
382    /// one before: music21's `getVerticalityAtOrBefore`.
383    pub fn verticality_at_or_before(&self, offset: FloatType) -> Option<Verticality<'_, 'a>> {
384        let verticality = self.verticality_at(offset);
385        if verticality.start_timespans.is_empty() {
386            verticality.previous()
387        } else {
388            Some(verticality)
389        }
390    }
391
392    /// The verticality at each offset a timespan starts at, in order:
393    /// music21's `iterateVerticalities`.
394    pub fn verticalities(&self) -> Vec<Verticality<'_, 'a>> {
395        self.all_offsets()
396            .into_iter()
397            .map(|offset| self.verticality_at(offset))
398            .collect()
399    }
400
401    /// The most timespans starting at or sounding across any one offset a
402    /// timespan starts at, nothing for an empty tree: music21's
403    /// `maximumOverlap`.
404    pub fn maximum_overlap(&self) -> Option<usize> {
405        self.verticalities()
406            .iter()
407            .map(|verticality| {
408                verticality.start_timespans.len() + verticality.overlap_timespans.len()
409            })
410            .max()
411    }
412
413    /// The stream the tree was read from: music21's `source`.
414    pub fn source(&self) -> &'a Stream {
415        self.source
416    }
417
418    /// Takes out the timespan at a place in [`timespans`](Self::timespans)
419    /// and hands it back: music21's `removeTimespan`. Nothing is taken
420    /// out past the last.
421    pub fn remove_timespan(&mut self, index: usize) -> Option<ElementTimespan<'a>> {
422        (index < self.timespans.len()).then(|| self.timespans.remove(index))
423    }
424
425    /// Takes out the timespans at these places, each read as the tree
426    /// stood before any was taken out: music21's `removeTimespanList`.
427    pub fn remove_timespan_list(&mut self, indices: &[usize]) {
428        let mut index = 0;
429        self.timespans.retain(|_| {
430            let kept = !indices.contains(&index);
431            index += 1;
432            kept
433        });
434    }
435
436    /// The parts the timespans are in, each once: music21's `allParts`.
437    /// Those of the stream the tree was read from come first, in its
438    /// order, and any other after them by id, those with none last. A
439    /// timespan in no part is passed over.
440    pub fn all_parts(&self) -> Vec<&'a Stream> {
441        let mut parts: Vec<&'a Stream> = Vec::new();
442        for part in self.timespans.iter().filter_map(ElementTimespan::part) {
443            if !parts.iter().any(|known| std::ptr::eq(*known, part)) {
444                parts.push(part);
445            }
446        }
447        let order = self.source.parts();
448        parts.sort_by_key(|part| {
449            let place = order
450                .iter()
451                .position(|known| std::ptr::eq(*known, *part))
452                .unwrap_or(order.len());
453            (
454                place,
455                part.id().is_none(),
456                part.id().unwrap_or_default().to_string(),
457            )
458        });
459        parts
460    }
461
462    /// A tree for each part the timespans are in, holding that part's
463    /// timespans and read from it, in the order of
464    /// [`all_parts`](Self::all_parts): music21's `toPartwiseTimespanTrees`.
465    pub fn to_partwise_timespan_trees(&self) -> Vec<TimespanTree<'a>> {
466        self.all_parts()
467            .into_iter()
468            .map(|part| TimespanTree {
469                source: part,
470                timespans: self
471                    .timespans
472                    .iter()
473                    .filter(|span| span.part().is_some_and(|own| std::ptr::eq(own, part)))
474                    .cloned()
475                    .collect(),
476            })
477            .collect()
478    }
479
480    /// Cuts every timespan sounding across one of these offsets in two
481    /// there: music21's `splitAt`. The pieces come after what already
482    /// starts and ends where each does.
483    pub fn split_at(&mut self, offsets: &[FloatType]) {
484        for &offset in offsets {
485            let (across, mut kept): (Vec<ElementTimespan<'a>>, Vec<ElementTimespan<'a>>) =
486                std::mem::take(&mut self.timespans)
487                    .into_iter()
488                    .partition(|span| span.offset < offset && offset < span.end_time);
489            for span in across {
490                kept.push(span.spanning(span.offset, offset));
491                kept.push(span.spanning(offset, span.end_time));
492            }
493            kept.sort_by(|a, b| {
494                a.offset
495                    .total_cmp(&b.offset)
496                    .then_with(|| a.end_time.total_cmp(&b.end_time))
497            });
498            self.timespans = kept;
499        }
500    }
501
502    /// Runs of `n` verticalities, each starting one after the last, in
503    /// order or `reverse`d: music21's `iterateVerticalitiesNwise`. Where
504    /// there are fewer than `n`, or with `pad_end` at the end, a run is
505    /// filled out with an empty verticality at the tree's end.
506    ///
507    /// # Errors
508    ///
509    /// A run of no verticalities.
510    pub fn verticalities_nwise(
511        &self,
512        n: usize,
513        reverse: bool,
514        pad_end: bool,
515    ) -> Result<Vec<Vec<Verticality<'_, 'a>>>> {
516        if n == 0 {
517            return Err(Error::Tree(format!(
518                "The number of verticalities in the group must be at least one. Got {n}"
519            )));
520        }
521        let sentinel = Verticality {
522            tree: self,
523            offset: self.end_time().unwrap_or(FloatType::INFINITY),
524            start_timespans: Vec::new(),
525            overlap_timespans: Vec::new(),
526            stop_timespans: Vec::new(),
527        };
528        let mut sequence = self.verticalities();
529        if reverse {
530            sequence.reverse();
531        }
532        if pad_end {
533            sequence.extend(std::iter::repeat_n(sentinel.clone(), n - 1));
534        }
535        let mut windows: Vec<Vec<Verticality<'_, 'a>>> = if sequence.len() < n {
536            let mut window = sequence;
537            let missing = n - window.len();
538            window.extend(std::iter::repeat_n(sentinel, missing));
539            vec![window]
540        } else {
541            sequence.windows(n).map(<[_]>::to_vec).collect()
542        };
543        if reverse {
544            for window in &mut windows {
545                window.reverse();
546            }
547        }
548        Ok(windows)
549    }
550
551    /// Each run of verticalities from one whose chord is consonant to the
552    /// next that is, with at least one between: music21's
553    /// `iterateConsonanceBoundedVerticalities`.
554    ///
555    /// # Errors
556    ///
557    /// A verticality whose pitches make no chord.
558    pub fn consonance_bounded_verticalities(&self) -> Result<Vec<Vec<Verticality<'_, 'a>>>> {
559        let mut runs = Vec::new();
560        let mut buffer: Vec<Verticality<'_, 'a>> = Vec::new();
561        for verticality in self.verticalities() {
562            let consonant = verticality.to_chord()?.is_consonant();
563            if buffer.is_empty() {
564                if consonant {
565                    buffer.push(verticality);
566                }
567                continue;
568            }
569            buffer.push(verticality);
570            if consonant {
571                if buffer.len() > 2 {
572                    runs.push(buffer.clone());
573                }
574                let last = buffer.pop().expect("the verticality just pushed");
575                buffer = vec![last];
576            }
577        }
578        Ok(runs)
579    }
580
581    /// The next timespan after this one, starting at a later offset, in the
582    /// same part: music21's `findNextPitchedTimespanInSameStreamByClass`.
583    pub fn next_in_same_part(
584        &self,
585        timespan: &ElementTimespan<'a>,
586    ) -> Option<&ElementTimespan<'a>> {
587        let part = timespan.part();
588        let mut offset = timespan.offset;
589        while let Some(next) = self.position_after(offset) {
590            if let Some(found) = self
591                .starting_at(next)
592                .into_iter()
593                .find(|span| same_stream(span.part(), part))
594            {
595                return Some(found);
596            }
597            offset = next;
598        }
599        None
600    }
601
602    /// The timespan before this one, starting at an earlier offset, in the
603    /// same part: music21's `findPreviousPitchedTimespanInSameStreamByClass`.
604    pub fn previous_in_same_part(
605        &self,
606        timespan: &ElementTimespan<'a>,
607    ) -> Option<&ElementTimespan<'a>> {
608        let part = timespan.part();
609        let mut offset = timespan.offset;
610        while let Some(previous) = self.position_before(offset) {
611            if let Some(found) = self
612                .starting_at(previous)
613                .into_iter()
614                .find(|span| same_stream(span.part(), part))
615            {
616                return Some(found);
617            }
618            offset = previous;
619        }
620        None
621    }
622}
623
624/// Whether two parts are the same stream, or both are none.
625fn same_stream(a: Option<&Stream>, b: Option<&Stream>) -> bool {
626    match (a, b) {
627        (Some(a), Some(b)) => std::ptr::eq(a, b),
628        (None, None) => true,
629        _ => false,
630    }
631}
632
633/// What starts, stops and sounds across one offset of a [`TimespanTree`]:
634/// music21's `Verticality`.
635#[derive(Clone, Debug)]
636pub struct Verticality<'t, 'a> {
637    tree: &'t TimespanTree<'a>,
638    offset: FloatType,
639    start_timespans: Vec<&'t ElementTimespan<'a>>,
640    overlap_timespans: Vec<&'t ElementTimespan<'a>>,
641    stop_timespans: Vec<&'t ElementTimespan<'a>>,
642}
643
644impl<'t, 'a> Verticality<'t, 'a> {
645    /// The offset.
646    pub fn offset(&self) -> FloatType {
647        self.offset
648    }
649
650    /// The timespans starting here: music21's `startTimespans`.
651    pub fn start_timespans(&self) -> &[&'t ElementTimespan<'a>] {
652        &self.start_timespans
653    }
654
655    /// The timespans sounding across: music21's `overlapTimespans`.
656    pub fn overlap_timespans(&self) -> &[&'t ElementTimespan<'a>] {
657        &self.overlap_timespans
658    }
659
660    /// The timespans ending here: music21's `stopTimespans`.
661    pub fn stop_timespans(&self) -> &[&'t ElementTimespan<'a>] {
662        &self.stop_timespans
663    }
664
665    /// Those starting, then those sounding across: music21's
666    /// `startAndOverlapTimespans`.
667    pub fn start_and_overlap_timespans(&self) -> Vec<&'t ElementTimespan<'a>> {
668        self.start_timespans
669            .iter()
670            .chain(&self.overlap_timespans)
671            .copied()
672            .collect()
673    }
674
675    /// Each pitch sounding, each name and octave once, lowest first:
676    /// music21's `pitchSet`, ordered as its `toChord` orders it.
677    pub fn pitch_set(&self) -> Vec<Pitch> {
678        let mut seen: Vec<String> = Vec::new();
679        let mut pitches: Vec<Pitch> = Vec::new();
680        for span in self.start_and_overlap_timespans() {
681            for pitch in span.pitches() {
682                let name = pitch.name_with_octave();
683                if !seen.contains(&name) {
684                    seen.push(name);
685                    pitches.push(pitch);
686                }
687            }
688        }
689        pitches.sort_by(|a, b| a.ps().total_cmp(&b.ps()));
690        pitches
691    }
692
693    /// Each pitch class sounding, once, in order: music21's
694    /// `pitchClassSet`, by its classes.
695    pub fn pitch_class_set(&self) -> Vec<u8> {
696        let mut classes: Vec<u8> = self
697            .pitch_set()
698            .iter()
699            .map(|pitch| (pitch.ps().round_ties_even() as i64).rem_euclid(12) as u8)
700            .collect();
701        classes.sort_unstable();
702        classes.dedup();
703        classes
704    }
705
706    /// A chord of the pitches sounding, lowest first: music21's `toChord`.
707    ///
708    /// # Errors
709    ///
710    /// None in practice; a chord of no pitches is an empty chord.
711    pub fn to_chord(&self) -> Result<Chord> {
712        Chord::new(self.pitch_set().as_slice())
713    }
714
715    /// The timespan sounding the lowest pitch, the last of those sounding it
716    /// alike: music21's `bassTimespan`.
717    pub fn bass_timespan(&self) -> Option<&'t ElementTimespan<'a>> {
718        let mut lowest: Option<(Pitch, &'t ElementTimespan<'a>)> = None;
719        for span in self.start_and_overlap_timespans() {
720            let mut pitches = span.pitches();
721            if pitches.is_empty() {
722                continue;
723            }
724            pitches.sort_by(|a, b| a.ps().total_cmp(&b.ps()));
725            let pitch = pitches.swap_remove(0);
726            match &lowest {
727                None => lowest = Some((pitch, span)),
728                Some((overall, _)) if at_most(&pitch, overall) => lowest = Some((pitch, span)),
729                Some(_) => {}
730            }
731        }
732        lowest.map(|(_, span)| span)
733    }
734
735    /// The measure of the first timespan starting here: music21's
736    /// `measureNumber`.
737    pub fn measure_number(&self) -> Option<IntegerType> {
738        self.start_timespans.first().and_then(|span| span.measure)
739    }
740
741    /// Each pitched timespan starting here paired with the one before it in
742    /// its part, and, with `include_oblique`, each pitched one sounding
743    /// across paired with itself: music21's `getPairedMotion`. Without
744    /// `include_rests`, a pair is kept only where the earlier one stops
745    /// here; without `include_oblique`, a pair of the same pitches is not
746    /// kept.
747    pub fn paired_motion(
748        &self,
749        include_rests: bool,
750        include_oblique: bool,
751    ) -> Vec<(&'t ElementTimespan<'a>, &'t ElementTimespan<'a>)> {
752        let mut pairs = Vec::new();
753        for &starting in &self.start_timespans {
754            if !starting.pitched {
755                continue;
756            }
757            let Some(previous) = self.tree.previous_in_same_part(starting) else {
758                continue;
759            };
760            if !previous.pitched {
761                continue;
762            }
763            if !include_rests
764                && !self
765                    .stop_timespans
766                    .iter()
767                    .any(|stopping| std::ptr::eq(*stopping, previous))
768            {
769                continue;
770            }
771            if !include_oblique && starting.pitches() == previous.pitches() {
772                continue;
773            }
774            pairs.push((previous, starting));
775        }
776        if include_oblique {
777            for &overlap in &self.overlap_timespans {
778                if overlap.pitched {
779                    pairs.push((overlap, overlap));
780                }
781            }
782        }
783        pairs
784    }
785
786    /// Each two pairs of [`Self::paired_motion`], the earlier pair first:
787    /// music21's `getAllVoiceLeadingQuartets(returnObjects=False)`. Without
788    /// `include_no_motion`, two pairs neither of which moves are left out;
789    /// with `part_pairs`, only those whose two parts are one of the pairs of
790    /// the source's parts given, by their places among them.
791    ///
792    /// # Errors
793    ///
794    /// A part pair naming a part the source has not got.
795    pub fn voice_leading_timespans(
796        &self,
797        include_rests: bool,
798        include_oblique: bool,
799        include_no_motion: bool,
800        part_pairs: Option<&[(usize, usize)]>,
801    ) -> Result<Vec<[&'t ElementTimespan<'a>; 4]>> {
802        let pairs = self.paired_motion(include_rests, include_oblique);
803        let parts = self.tree.source.parts();
804        let mut quartets = Vec::new();
805        for (index, upper) in pairs.iter().enumerate() {
806            for lower in &pairs[index + 1..] {
807                if !include_no_motion
808                    && upper.0.pitches() == upper.1.pitches()
809                    && lower.0.pitches() == lower.1.pitches()
810                {
811                    continue;
812                }
813                if let Some(part_pairs) = part_pairs {
814                    let (top, bottom) = (upper.0.part(), lower.0.part());
815                    let is_either = |index: usize| -> Result<bool> {
816                        let part = parts
817                            .get(index)
818                            .copied()
819                            .ok_or_else(|| Error::Tree(format!("the score has no part {index}")))?;
820                        Ok(same_stream(Some(part), top) || same_stream(Some(part), bottom))
821                    };
822                    let mut appropriate = false;
823                    for (first, second) in part_pairs {
824                        if is_either(*first)? && is_either(*second)? {
825                            appropriate = true;
826                            break;
827                        }
828                    }
829                    if !appropriate {
830                        continue;
831                    }
832                }
833                quartets.push([upper.0, upper.1, lower.0, lower.1]);
834            }
835        }
836        Ok(quartets)
837    }
838
839    /// The same quartets as voice-leading quartets, where all four are
840    /// notes: music21's `getAllVoiceLeadingQuartets`.
841    ///
842    /// # Errors
843    ///
844    /// As [`Self::voice_leading_timespans`], or two pitches no interval can
845    /// be spelled between.
846    pub fn voice_leading_quartets(
847        &self,
848        include_rests: bool,
849        include_oblique: bool,
850        include_no_motion: bool,
851        part_pairs: Option<&[(usize, usize)]>,
852    ) -> Result<Vec<VoiceLeadingQuartet>> {
853        let mut quartets = Vec::new();
854        for spans in self.voice_leading_timespans(
855            include_rests,
856            include_oblique,
857            include_no_motion,
858            part_pairs,
859        )? {
860            let pitches: Vec<Pitch> = spans
861                .iter()
862                .filter_map(|span| match span.element {
863                    StreamElement::Note(note) => Some(note.pitch().clone()),
864                    _ => None,
865                })
866                .collect();
867            if let [v1n1, v1n2, v2n1, v2n2] = pitches.as_slice() {
868                quartets.push(VoiceLeadingQuartet::new(
869                    v1n1.clone(),
870                    v1n2.clone(),
871                    v2n1.clone(),
872                    v2n2.clone(),
873                )?);
874            }
875        }
876        Ok(quartets)
877    }
878
879    /// A chord of every pitch sounding here, lasting `length` or, without
880    /// one, until the next start -- a quarter where nothing follows -- or a
881    /// rest where nothing sounds: music21's `makeElement`. With
882    /// `add_ties`, a note begun before or going on after is tied; with
883    /// `remove_redundant_pitches`, a pitch two timespans sound is one note.
884    ///
885    /// # Errors
886    ///
887    /// A length no duration can have, or a chord symbol whose pitches
888    /// cannot be worked out.
889    pub fn make_element(
890        &self,
891        length: Option<FloatType>,
892        add_ties: bool,
893        remove_redundant_pitches: bool,
894    ) -> Result<StreamElement> {
895        let length = match length {
896            Some(length) => op_frac(length),
897            None => self.time_to_next_event().unwrap_or(1.0),
898        };
899        let spans: Vec<crate::stream::chordify::Span<'a>> = self
900            .start_and_overlap_timespans()
901            .into_iter()
902            .filter(|span| span.pitched)
903            .map(|span| crate::stream::chordify::Span {
904                start: span.offset,
905                end: span.end_time,
906                element: span.element,
907                part: 0,
908            })
909            .collect();
910        let options = crate::stream::ChordifyOptions {
911            add_ties,
912            remove_redundant_pitches,
913            to_sounding_pitch: false,
914        };
915        crate::stream::chordify::make_element(&spans, self.offset, length, &options)
916    }
917
918    /// The next offset a timespan starts at: music21's `nextStartOffset`.
919    pub fn next_start_offset(&self) -> Option<FloatType> {
920        self.tree.position_after(self.offset)
921    }
922
923    /// The verticality there: music21's `nextVerticality`.
924    pub fn next(&self) -> Option<Verticality<'t, 'a>> {
925        self.next_start_offset()
926            .map(|offset| self.tree.verticality_at(offset))
927    }
928
929    /// The verticality at the last offset before this one a timespan starts
930    /// at: music21's `previousVerticality`.
931    pub fn previous(&self) -> Option<Verticality<'t, 'a>> {
932        self.tree
933            .position_before(self.offset)
934            .map(|offset| self.tree.verticality_at(offset))
935    }
936
937    /// How long until the next start, or the end of the tree after the
938    /// last: music21's `timeToNextEvent`.
939    pub fn time_to_next_event(&self) -> Option<FloatType> {
940        let next = self.next_start_offset().or_else(|| self.tree.end_time())?;
941        Some(op_frac(next - self.offset))
942    }
943}
944
945/// Each part's timespans across a run of verticalities -- those sounding
946/// across or starting at the first, then those starting at the rest --
947/// part by part in the order first met: music21's
948/// `VerticalitySequence.unwrap`.
949pub fn unwrap<'t, 'a>(
950    verticalities: &[Verticality<'t, 'a>],
951) -> Vec<(Option<&'a Stream>, Horizontality<'t, 'a>)> {
952    let Some((first, rest)) = verticalities.split_first() else {
953        return Vec::new();
954    };
955    let mut parts: Vec<(Option<&'a Stream>, Vec<&'t ElementTimespan<'a>>)> = Vec::new();
956    let spans = first
957        .overlap_timespans
958        .iter()
959        .chain(&first.start_timespans)
960        .chain(
961            rest.iter()
962                .flat_map(|verticality| &verticality.start_timespans),
963        );
964    for &span in spans {
965        let part = span.part();
966        match parts
967            .iter_mut()
968            .find(|(known, _)| same_stream(*known, part))
969        {
970            Some((_, spans)) => spans.push(span),
971            None => parts.push((part, vec![span])),
972        }
973    }
974    parts
975        .into_iter()
976        .map(|(part, timespans)| (part, Horizontality { timespans }))
977        .collect()
978}
979
980/// One part's timespans one after another: music21's `Horizontality`.
981#[derive(Clone, Debug)]
982pub struct Horizontality<'t, 'a> {
983    timespans: Vec<&'t ElementTimespan<'a>>,
984}
985
986impl<'t, 'a> Horizontality<'t, 'a> {
987    /// The timespans, in order.
988    pub fn timespans(&self) -> &[&'t ElementTimespan<'a>] {
989        &self.timespans
990    }
991
992    /// The first pitch of each of the first three, where there are three
993    /// and every timespan has a pitch, as music21 asks.
994    fn first_three(&self) -> Option<[Pitch; 3]> {
995        if self.timespans.len() < 3 || self.timespans.iter().any(|span| span.pitches().is_empty()) {
996            return None;
997        }
998        let firsts: Vec<Pitch> = self
999            .timespans
1000            .iter()
1001            .take(3)
1002            .map(|span| span.pitches().into_iter().next())
1003            .collect::<Option<_>>()?;
1004        Some([firsts[0].clone(), firsts[1].clone(), firsts[2].clone()])
1005    }
1006
1007    /// Whether the first pitches of the first three rise all the way or
1008    /// fall all the way: music21's `hasPassingTone`.
1009    pub fn has_passing_tone(&self) -> bool {
1010        self.first_three().is_some_and(|[a, b, c]| {
1011            (a.ps() < b.ps() && b.ps() < c.ps()) || (a.ps() > b.ps() && b.ps() > c.ps())
1012        })
1013    }
1014
1015    /// Whether the first and third of the first three are the same pitch and
1016    /// the second is less than three semitones from them: music21's
1017    /// `hasNeighborTone`.
1018    pub fn has_neighbor_tone(&self) -> bool {
1019        self.first_three()
1020            .is_some_and(|[a, b, c]| a == c && (b.ps() - a.ps()).abs() < 3.0)
1021    }
1022
1023    /// Whether every timespan sounds the same pitches, written alike:
1024    /// music21's `hasNoMotion`. music21 gathers the pitches in a set, which
1025    /// tells apart pitches equal but for how their accidentals are shown or
1026    /// whether their spelling was worked out, so this does too.
1027    pub fn has_no_motion(&self) -> bool {
1028        let mut seen: Vec<Vec<String>> = Vec::new();
1029        for span in &self.timespans {
1030            let keys: Vec<String> = span.pitches().iter().map(set_key).collect();
1031            if !seen.contains(&keys) {
1032                seen.push(keys);
1033            }
1034        }
1035        seen.len() == 1
1036    }
1037}
1038
1039/// What tells two pitches apart in music21's sets of them: what its
1040/// `Pitch.__hash__` reads -- the accidental and how it is shown, the
1041/// fundamental, whether the spelling was worked out, the microtone, octave
1042/// and step.
1043fn set_key(pitch: &Pitch) -> String {
1044    pitch_set_key(pitch)
1045}
1046
1047/// What music21 hashes a pitch by, as text: a set of pitches holds two
1048/// pitches once only where these agree.
1049pub(crate) fn pitch_set_key(pitch: &Pitch) -> String {
1050    let accidental = pitch.written_accidental().map(|accidental| {
1051        format!(
1052            "{}|{:?}|{}|{}|{}|{}|{}|{}",
1053            accidental.alter(),
1054            accidental.display_status(),
1055            accidental.display_type(),
1056            accidental.modifier(),
1057            accidental.name(),
1058            accidental.display_location(),
1059            accidental.display_size(),
1060            accidental.display_style()
1061        )
1062    });
1063    format!(
1064        "{accidental:?}|{:?}|{}|{:?}|{:?}|{}",
1065        pitch.fundamental().map(pitch_set_key),
1066        pitch.spelling_is_inferred(),
1067        pitch.microtone().map(|microtone| microtone.cents()),
1068        pitch.octave(),
1069        pitch.name_with_octave()
1070    )
1071}
1072
1073#[cfg(test)]
1074mod tests {
1075    use super::*;
1076    use crate::tinynotation::from_tiny_notation;
1077
1078    #[test]
1079    fn a_line_is_read_as_timespans_and_verticalities() -> Result<()> {
1080        let line = from_tiny_notation("4/4 c2 e4 g")?;
1081        let tree = as_timespans(&line, Flatten::Flat, None);
1082        let notes: Vec<(FloatType, FloatType)> = tree
1083            .timespans()
1084            .iter()
1085            .filter(|span| matches!(span.element(), StreamElement::Note(_)))
1086            .map(|span| (span.offset(), span.end_time()))
1087            .collect();
1088        assert_eq!(notes, [(0.0, 2.0), (2.0, 3.0), (3.0, 4.0)]);
1089        let at_one = tree.verticality_at(1.0);
1090        assert!(at_one.start_timespans().is_empty());
1091        assert_eq!(at_one.overlap_timespans().len(), 1);
1092        assert_eq!(at_one.pitch_class_set(), [0]);
1093        assert_eq!(
1094            tree.verticality_at(2.0).next().map(|next| next.offset()),
1095            Some(3.0)
1096        );
1097        assert_eq!(tree.verticality_at(3.0).time_to_next_event(), Some(1.0));
1098        Ok(())
1099    }
1100
1101    /// A score of two parts read from tiny notation.
1102    fn two_parts() -> Result<Stream> {
1103        let mut score = Stream::with_kind(StreamKind::Score);
1104        for (id, line) in [("upper", "4/4 c'2 e'2"), ("lower", "4/4 c1")] {
1105            let mut part = from_tiny_notation(line)?;
1106            part.set_kind(StreamKind::Part);
1107            part.set_id(Some(id.to_string()));
1108            score.insert(0.0, part);
1109        }
1110        Ok(score)
1111    }
1112
1113    #[test]
1114    fn the_parts_come_in_the_score_order() -> Result<()> {
1115        let score = two_parts()?;
1116        let notes = as_timespans(
1117            &score,
1118            Flatten::Flat,
1119            Some(|element| matches!(element, StreamElement::Note(_))),
1120        );
1121        let ids: Vec<Option<&str>> = notes.all_parts().iter().map(|part| part.id()).collect();
1122        assert_eq!(ids, [Some("upper"), Some("lower")]);
1123
1124        let partwise = notes.to_partwise_timespan_trees();
1125        let counts: Vec<usize> = partwise.iter().map(TimespanTree::len).collect();
1126        assert_eq!(counts, [2, 1]);
1127        assert_eq!(partwise[1].source().id(), Some("lower"));
1128        assert_eq!(partwise[1].timespans()[0].end_time(), 4.0);
1129        Ok(())
1130    }
1131
1132    #[test]
1133    fn timespans_are_taken_out_by_place() -> Result<()> {
1134        let line = from_tiny_notation("4/4 c4 d e f")?;
1135        let mut tree = as_timespans(
1136            &line,
1137            Flatten::Flat,
1138            Some(|element| matches!(element, StreamElement::Note(_))),
1139        );
1140        let taken = tree.remove_timespan(1).map(|span| span.offset());
1141        assert_eq!(taken, Some(1.0));
1142        assert!(tree.remove_timespan(7).is_none());
1143        tree.remove_timespan_list(&[0, 2]);
1144        let left: Vec<FloatType> = tree
1145            .timespans()
1146            .iter()
1147            .map(ElementTimespan::offset)
1148            .collect();
1149        assert_eq!(left, [2.0]);
1150        Ok(())
1151    }
1152}