1pub 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
37pub enum Flatten {
38 #[default]
40 Flat,
41 SemiFlat,
44}
45
46#[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 pub fn element(&self) -> &'a StreamElement {
64 self.element
65 }
66
67 pub fn offset(&self) -> FloatType {
69 self.offset
70 }
71
72 pub fn end_time(&self) -> FloatType {
74 self.end_time
75 }
76
77 pub fn quarter_length(&self) -> FloatType {
79 self.end_time - self.offset
80 }
81
82 pub fn parent_offset(&self) -> FloatType {
84 self.parent_offset
85 }
86
87 pub fn parent_end_time(&self) -> FloatType {
89 self.parent_end_time
90 }
91
92 pub fn parentage(&self) -> &[&'a Stream] {
95 &self.parentage
96 }
97
98 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 pub fn measure_number(&self) -> Option<IntegerType> {
109 self.measure
110 }
111
112 pub fn is_pitched(&self) -> bool {
115 self.pitched
116 }
117
118 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 fn spanning(&self, offset: FloatType, end_time: FloatType) -> Self {
134 Self {
135 offset,
136 end_time,
137 ..self.clone()
138 }
139 }
140}
141
142fn 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#[derive(Clone, Debug)]
160pub struct TimespanTree<'a> {
161 source: &'a Stream,
162 timespans: Vec<ElementTimespan<'a>>,
163}
164
165pub 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 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
249fn at_most(a: &Pitch, b: &Pitch) -> bool {
252 a.ps() < b.ps() || a == b
253}
254
255impl<'a> TimespanTree<'a> {
256 pub fn timespans(&self) -> &[ElementTimespan<'a>] {
258 &self.timespans
259 }
260
261 pub fn len(&self) -> usize {
263 self.timespans.len()
264 }
265
266 pub fn is_empty(&self) -> bool {
268 self.timespans.is_empty()
269 }
270
271 pub fn lowest_position(&self) -> Option<FloatType> {
273 self.timespans.first().map(|span| span.offset)
274 }
275
276 pub fn highest_position(&self) -> Option<FloatType> {
278 self.timespans.last().map(|span| span.offset)
279 }
280
281 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 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 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 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 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 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 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 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 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 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 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 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 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 pub fn source(&self) -> &'a Stream {
415 self.source
416 }
417
418 pub fn remove_timespan(&mut self, index: usize) -> Option<ElementTimespan<'a>> {
422 (index < self.timespans.len()).then(|| self.timespans.remove(index))
423 }
424
425 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 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 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 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 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 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 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 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
624fn 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#[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 pub fn offset(&self) -> FloatType {
647 self.offset
648 }
649
650 pub fn start_timespans(&self) -> &[&'t ElementTimespan<'a>] {
652 &self.start_timespans
653 }
654
655 pub fn overlap_timespans(&self) -> &[&'t ElementTimespan<'a>] {
657 &self.overlap_timespans
658 }
659
660 pub fn stop_timespans(&self) -> &[&'t ElementTimespan<'a>] {
662 &self.stop_timespans
663 }
664
665 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 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 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 pub fn to_chord(&self) -> Result<Chord> {
712 Chord::new(self.pitch_set().as_slice())
713 }
714
715 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 pub fn measure_number(&self) -> Option<IntegerType> {
738 self.start_timespans.first().and_then(|span| span.measure)
739 }
740
741 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 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 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 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 pub fn next_start_offset(&self) -> Option<FloatType> {
920 self.tree.position_after(self.offset)
921 }
922
923 pub fn next(&self) -> Option<Verticality<'t, 'a>> {
925 self.next_start_offset()
926 .map(|offset| self.tree.verticality_at(offset))
927 }
928
929 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 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
945pub 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#[derive(Clone, Debug)]
982pub struct Horizontality<'t, 'a> {
983 timespans: Vec<&'t ElementTimespan<'a>>,
984}
985
986impl<'t, 'a> Horizontality<'t, 'a> {
987 pub fn timespans(&self) -> &[&'t ElementTimespan<'a>] {
989 &self.timespans
990 }
991
992 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 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 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 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
1039fn set_key(pitch: &Pitch) -> String {
1044 pitch_set_key(pitch)
1045}
1046
1047pub(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 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}