1use crate::common::numbertools::weighted_index;
25use crate::defaults::{FloatType, IntegerType};
26use crate::error::{Error, Result};
27use crate::interval::Interval;
28use crate::pitch::Pitch;
29use crate::scale::scaletype::{SCALE_STARTS, advance};
30use crate::scale::{DegreeComparison, ScaleType, Simplification};
31
32const EPSILON: FloatType = 0.00001;
34
35const MAX_ASCENDING_STEPS: usize = 100;
38
39const MAX_DESCENDING_STEPS: usize = 10_000;
42
43const OCTAVE: IntegerType = 12;
45
46const WEIGHTED_TRIES: usize = 40;
49
50const ILL_FORMED: &str = "Cannot realize these pitches; is your scale well-formed? \
52 (especially check if you're giving notes without octaves)";
53
54pub type Draw<'a> = dyn FnMut() -> FloatType + 'a;
57
58#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
60#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
61pub enum Terminus {
62 Low,
64 High,
67}
68
69#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
72#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
73pub enum NodeId {
74 Terminus(Terminus),
76 Index(usize),
78}
79
80impl NodeId {
81 pub const LOW: Self = Self::Terminus(Terminus::Low);
83 pub const HIGH: Self = Self::Terminus(Terminus::High);
85
86 #[must_use]
88 pub fn is_terminus(self) -> bool {
89 matches!(self, Self::Terminus(_))
90 }
91}
92
93#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
95#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
96pub enum Direction {
97 Bi,
99 Ascending,
101 Descending,
103}
104
105#[derive(Clone, Debug, PartialEq)]
111#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
112pub struct Node {
113 pub id: NodeId,
115 pub degree: IntegerType,
117 pub weight: FloatType,
119}
120
121impl Node {
122 #[must_use]
124 pub fn new(id: NodeId, degree: IntegerType) -> Self {
125 Self {
126 id,
127 degree,
128 weight: 1.0,
129 }
130 }
131}
132
133#[derive(Clone, Debug, PartialEq)]
136pub struct Edge {
137 pub interval: Interval,
139 pub direction: Direction,
141 pub weight: FloatType,
143 pub id: Option<usize>,
145 connections: Vec<(NodeId, NodeId)>,
146}
147
148impl Edge {
149 pub fn new(interval: Interval, id: Option<usize>) -> Self {
151 Self {
152 interval,
153 direction: Direction::Bi,
154 weight: 1.0,
155 id,
156 connections: Vec::new(),
157 }
158 }
159
160 pub fn connect(&mut self, from: NodeId, to: NodeId, direction: Direction) -> Result<()> {
168 self.connections.push((from, to));
169 if direction == Direction::Bi {
170 return Err(Error::Scale("must request a direction".to_string()));
171 }
172 self.direction = direction;
173 Ok(())
174 }
175
176 pub fn connect_both(&mut self, low: NodeId, high: NodeId) {
179 self.connections.push((low, high));
180 self.connections.push((high, low));
181 self.direction = Direction::Bi;
182 }
183
184 #[must_use]
186 pub fn connections(&self) -> &[(NodeId, NodeId)] {
187 &self.connections
188 }
189
190 pub fn connections_toward(&self, direction: Direction) -> Result<Vec<(NodeId, NodeId)>> {
196 if self.direction == direction {
197 return Ok(self.connections.clone());
198 }
199 if direction == Direction::Bi {
200 return Err(Error::Scale(
201 "cannot request a bi direction from a mono direction".to_string(),
202 ));
203 }
204 if self.direction != Direction::Bi {
205 return Ok(Vec::new());
206 }
207
208 let index = usize::from(direction == Direction::Descending);
210 Ok(self.connections.get(index).into_iter().copied().collect())
211 }
212}
213
214#[derive(Clone, Debug)]
217pub struct EdgeSpec {
218 pub interval: Interval,
220 pub connections: Vec<(NodeId, NodeId, Direction)>,
222}
223
224#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
227pub enum Octaves {
228 Duplicating,
230 Distinct,
232}
233
234#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
236pub enum Pathways {
237 Deterministic,
239 Weighted,
241}
242
243#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
245pub enum Termini {
246 Equate,
248 Distinct,
250}
251
252#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
254pub enum Moduli {
255 Permit,
257 Forbid,
259}
260
261#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
264pub enum Fill {
265 IfUnbounded,
267 Never,
269}
270
271#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
273pub enum First {
274 Include,
276 Exclude,
278}
279
280#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
282pub enum Order {
283 Ascending,
285 Descending,
287}
288
289#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
292pub enum Neighbor {
293 Above,
295 Below,
297 Never,
299}
300
301#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
303pub enum NodeName {
304 Degree(IntegerType),
307 Id(NodeId),
309}
310
311#[derive(Clone, Debug, Default)]
313pub struct PitchRange {
314 pub min: Option<Pitch>,
316 pub max: Option<Pitch>,
318}
319
320impl PitchRange {
321 #[must_use]
323 pub fn between(min: Pitch, max: Pitch) -> Self {
324 Self {
325 min: Some(min),
326 max: Some(max),
327 }
328 }
329
330 fn holds(&self, pitch: &Pitch) -> bool {
332 let above = self.min.as_ref().is_none_or(|min| at_least(pitch, min));
333 let below = self.max.as_ref().is_none_or(|max| at_most(pitch, max));
334 above && below
335 }
336
337 fn is_open(&self) -> bool {
338 self.min.is_none() && self.max.is_none()
339 }
340}
341
342#[derive(Clone, Debug, Default)]
344pub struct Realized {
345 pub pitches: Vec<Pitch>,
347 pub nodes: Vec<NodeId>,
349}
350
351impl Realized {
352 fn push(&mut self, pitch: Pitch, node: NodeId) {
353 self.pitches.push(pitch);
354 self.nodes.push(node);
355 }
356
357 fn reverse(&mut self) {
358 self.pitches.reverse();
359 self.nodes.reverse();
360 }
361}
362
363#[derive(Clone, Debug, Default, Eq, PartialEq)]
366pub struct Matched {
367 pub matched: Vec<usize>,
369 pub unmatched: Vec<usize>,
371}
372
373#[derive(Clone, Debug)]
375pub struct Found {
376 pub matches: usize,
378 pub tonic: Pitch,
380}
381
382fn at_least(pitch: &Pitch, bound: &Pitch) -> bool {
383 pitch.ps() > bound.ps() || (pitch.ps() - bound.ps()).abs() < EPSILON
384}
385
386fn at_most(pitch: &Pitch, bound: &Pitch) -> bool {
387 pitch.ps() < bound.ps() || (pitch.ps() - bound.ps()).abs() < EPSILON
388}
389
390fn shifted(pitch: &Pitch, semitones: IntegerType) -> Result<Pitch> {
393 pitch.transpose(&Interval::from_semitones(semitones)?)
394}
395
396fn same_pitch(a: &Pitch, b: &Pitch) -> bool {
398 a.name_with_octave() == b.name_with_octave() && a.ps() == b.ps()
399}
400
401fn with_octave(pitch: &Pitch) -> Pitch {
404 let mut copy = pitch.clone();
405 copy.set_octave_is_implicit(false);
406 copy
407}
408
409#[must_use]
413pub fn pitch_bounds(pitches: &[Pitch]) -> Option<(usize, usize)> {
414 let mut order: Vec<usize> = (0..pitches.len()).collect();
415 order.sort_by(|a, b| pitches[*a].ps().total_cmp(&pitches[*b].ps()));
416 Some((*order.first()?, *order.last()?))
417}
418
419#[derive(Clone, Debug, PartialEq)]
421pub struct IntervalNetwork {
422 edge_id_count: usize,
423 node_id_count: usize,
424 nodes: Vec<Node>,
425 edges: Vec<Edge>,
426 pub octaves: Octaves,
428 pub pathways: Pathways,
430 pub simplification: Simplification,
432}
433
434impl Default for IntervalNetwork {
435 fn default() -> Self {
436 Self {
437 edge_id_count: 0,
438 node_id_count: 0,
439 nodes: Vec::new(),
440 edges: Vec::new(),
441 octaves: Octaves::Distinct,
442 pathways: Pathways::Deterministic,
443 simplification: Simplification::MaxAccidental,
444 }
445 }
446}
447
448impl IntervalNetwork {
450 pub fn bidirected(steps: &[&str]) -> Result<Self> {
456 let steps = steps
457 .iter()
458 .map(Interval::from_name)
459 .collect::<Result<Vec<_>>>()?;
460 let mut network = Self::default();
461 network.fill_bidirected(&steps);
462 Ok(network)
463 }
464
465 #[must_use]
467 pub fn nodes(&self) -> &[Node] {
468 &self.nodes
469 }
470
471 #[must_use]
473 pub fn edges(&self) -> &[Edge] {
474 &self.edges
475 }
476
477 #[must_use]
479 pub fn edge_id_count(&self) -> usize {
480 self.edge_id_count
481 }
482
483 #[must_use]
486 pub fn node_id_count(&self) -> usize {
487 self.node_id_count
488 }
489
490 #[must_use]
492 pub fn node(&self, id: NodeId) -> Option<&Node> {
493 self.nodes.iter().find(|node| node.id == id)
494 }
495
496 fn node_or_err(&self, id: NodeId) -> Result<&Node> {
497 self.node(id)
498 .ok_or_else(|| Error::Scale(format!("the network has no node {id:?}")))
499 }
500
501 pub fn clear(&mut self) {
503 self.edge_id_count = 0;
504 self.node_id_count = 0;
505 self.nodes.clear();
506 self.edges.clear();
507 }
508
509 fn put_node(&mut self, node: Node) {
511 match self.nodes.iter_mut().find(|held| held.id == node.id) {
512 Some(held) => *held = node,
513 None => self.nodes.push(node),
514 }
515 }
516
517 fn chain_node(&mut self, step: usize, count: usize, degree: IntegerType) -> NodeId {
520 if step + 1 == count {
521 return NodeId::HIGH;
522 }
523 let id = NodeId::Index(self.node_id_count);
524 self.node_id_count += 1;
525 self.put_node(Node::new(id, degree));
526 id
527 }
528
529 fn push_edge(&mut self, edge: Edge) {
530 self.edges.push(edge);
531 self.edge_id_count += 1;
532 }
533
534 pub fn fill_bidirected(&mut self, steps: &[Interval]) {
537 self.clear();
538 self.put_node(Node::new(NodeId::LOW, 1));
539 let mut previous = NodeId::LOW;
540 for (index, step) in steps.iter().enumerate() {
541 let degree = index as IntegerType + 2;
542 let following = self.chain_node(index, steps.len(), degree);
543 if following == NodeId::HIGH {
544 self.put_node(Node::new(NodeId::HIGH, degree));
545 }
546 let mut edge = Edge::new(step.clone(), Some(self.edge_id_count));
547 edge.connect_both(previous, following);
548 self.push_edge(edge);
549 previous = following;
550 }
551 }
552
553 pub fn fill_directed(&mut self, ascending: &[Interval], descending: &[Interval]) -> Result<()> {
561 self.clear();
562 if ascending.len() != descending.len() {
563 return Err(Error::Scale(
564 "cannot manage unequal sized directed edges".to_string(),
565 ));
566 }
567 self.put_node(Node::new(NodeId::LOW, 1));
568
569 let mut previous = NodeId::LOW;
571 for (index, step) in ascending.iter().enumerate() {
572 let degree = index as IntegerType + 2;
573 let following = self.chain_node(index, ascending.len(), degree);
574 if following == NodeId::HIGH {
575 self.put_node(Node::new(NodeId::HIGH, degree));
576 }
577 let mut edge = Edge::new(step.clone(), Some(self.edge_id_count));
578 edge.connect(previous, following, Direction::Ascending)?;
579 self.push_edge(edge);
580 previous = following;
581 }
582
583 let mut previous = NodeId::LOW;
586 for (index, step) in descending.iter().enumerate() {
587 let degree = index as IntegerType + 2;
588 let following = self.chain_node(index, descending.len(), degree);
589 let mut edge = Edge::new(step.clone(), Some(self.edge_id_count));
590 edge.connect(following, previous, Direction::Descending)?;
591 self.push_edge(edge);
592 previous = following;
593 }
594 Ok(())
595 }
596
597 pub fn fill_arbitrary(&mut self, nodes: Vec<Node>, edges: Vec<EdgeSpec>) -> Result<()> {
605 self.clear();
606 for node in nodes {
607 self.put_node(node);
608 }
609 for (index, spec) in edges.into_iter().enumerate() {
610 let mut edge = Edge::new(spec.interval, Some(index));
611 for (from, to, direction) in spec.connections {
612 self.node_or_err(from)?;
613 self.node_or_err(to)?;
614 match direction {
615 Direction::Bi => edge.connect_both(from, to),
616 _ => edge.connect(from, to, direction)?,
617 }
618 }
619 self.edges.push(edge);
620 }
621 Ok(())
622 }
623
624 fn fill_table(&mut self, nodes: &[TableNode], edges: &[TableEdge]) -> Result<()> {
627 let nodes = nodes
628 .iter()
629 .map(|(id, degree)| Node::new(*id, *degree))
630 .collect();
631 let edges = edges
632 .iter()
633 .map(|(name, from, to, direction)| {
634 Ok(EdgeSpec {
635 interval: Interval::from_name(name)?,
636 connections: vec![(*from, *to, *direction)],
637 })
638 })
639 .collect::<Result<Vec<_>>>()?;
640 self.fill_arbitrary(nodes, edges)
641 }
642
643 pub fn fill_melodic_minor(&mut self) -> Result<()> {
651 self.fill_table(&MELODIC_MINOR_NODES, &MELODIC_MINOR_EDGES)?;
652 self.octaves = Octaves::Duplicating;
653 self.pathways = Pathways::Deterministic;
654 Ok(())
655 }
656}
657
658impl IntervalNetwork {
660 #[must_use]
662 pub fn degree_min(&self) -> Option<IntegerType> {
663 self.nodes.iter().map(|node| node.degree).min()
664 }
665
666 #[must_use]
668 pub fn degree_max(&self) -> Option<IntegerType> {
669 self.nodes.iter().map(|node| node.degree).max()
670 }
671
672 #[must_use]
675 pub fn degree_max_unique(&self) -> Option<IntegerType> {
676 self.nodes
677 .iter()
678 .filter(|node| node.id != NodeId::HIGH)
679 .map(|node| node.degree)
680 .max()
681 }
682
683 #[must_use]
686 pub fn node_degrees(&self, termini: Termini) -> Vec<(NodeId, IntegerType)> {
687 let low = self.node(NodeId::LOW).map(|node| node.degree);
688 self.nodes
689 .iter()
690 .map(|node| match (termini, node.id, low) {
691 (Termini::Equate, NodeId::HIGH, Some(low)) => (node.id, low),
692 _ => (node.id, node.degree),
693 })
694 .collect()
695 }
696
697 pub fn degree_of(&self, id: NodeId) -> Result<IntegerType> {
704 self.node_degrees(Termini::Equate)
705 .into_iter()
706 .find(|(node, _)| *node == id)
707 .map(|(_, degree)| degree)
708 .ok_or_else(|| Error::Scale(format!("the network has no node {id:?}")))
709 }
710
711 pub fn edge_directions(&self, id: NodeId) -> Result<Vec<Direction>> {
718 let found: Vec<Direction> = self
719 .edges
720 .iter()
721 .filter(|edge| {
722 edge.connections
723 .iter()
724 .any(|(from, to)| *from == id || *to == id)
725 })
726 .map(|edge| edge.direction)
727 .collect();
728 if found.is_empty() {
729 return Err(Error::Scale("failed to match any edges".to_string()));
730 }
731 Ok(found)
732 }
733
734 pub fn degree_modulus(&self, degree: IntegerType) -> Result<IntegerType> {
741 let (Some(min), Some(max)) = (self.degree_min(), self.degree_max()) else {
742 return Err(Error::Scale(
743 "Cannot compute degreeModulus on an empty network".to_string(),
744 ));
745 };
746 let span = max - min;
747 if span == 0 {
748 return Err(Error::Scale(
749 "Cannot compute degreeModulus on a network of one degree".to_string(),
750 ));
751 }
752 Ok((degree - 1).rem_euclid(span) + min)
753 }
754
755 pub fn nodes_named(
761 &self,
762 name: NodeName,
763 termini: Termini,
764 moduli: Moduli,
765 ) -> Result<Vec<NodeId>> {
766 let degree = match name {
767 NodeName::Id(id) => {
768 self.node_or_err(id)?;
769 return Ok(vec![id]);
770 }
771 NodeName::Degree(degree) => degree,
772 };
773 let degrees = self.node_degrees(termini);
774 let exact: Vec<NodeId> = degrees
775 .iter()
776 .filter(|(_, held)| *held == degree)
777 .map(|(id, _)| *id)
778 .collect();
779 if !exact.is_empty() || moduli == Moduli::Forbid || degrees.is_empty() {
780 return Ok(exact);
781 }
782
783 let folded = self.degree_modulus(degree)?;
785 Ok(degrees
786 .iter()
787 .filter(|(_, held)| *held == folded)
788 .map(|(id, _)| *id)
789 .collect())
790 }
791
792 fn start_of(&self, name: Option<NodeName>) -> Result<NodeId> {
795 let Some(name) = name else {
796 return Ok(self.node_or_err(NodeId::LOW)?.id);
797 };
798 self.nodes_named(name, Termini::Equate, Moduli::Permit)?
799 .first()
800 .copied()
801 .ok_or_else(|| Error::Scale(format!("no node is named {name:?}")))
802 }
803
804 pub fn next_steps(&self, from: NodeId, direction: Direction) -> Result<Vec<(usize, NodeId)>> {
812 let source = match (from, direction) {
813 (NodeId::LOW, Direction::Descending) => NodeId::HIGH,
814 (NodeId::HIGH, Direction::Ascending) => NodeId::LOW,
815 _ => from,
816 };
817 let mut found = Vec::new();
818 for (index, edge) in self.edges.iter().enumerate() {
819 for (start, end) in edge.connections_toward(direction)? {
820 if start == source {
821 found.push((index, end));
822 }
823 }
824 }
825 if found.is_empty() {
826 return Err(Error::Scale("could not find any edges".to_string()));
827 }
828 Ok(found)
829 }
830
831 fn choose(&self, steps: &[(usize, NodeId)], draw: &mut Draw<'_>) -> Result<(usize, NodeId)> {
834 if let [only] = steps {
835 return Ok(*only);
836 }
837 let weights = steps
838 .iter()
839 .map(|(_, node)| Ok(self.node_or_err(*node)?.weight))
840 .collect::<Result<Vec<_>>>()?;
841 let index = weighted_index(&weights, draw())?;
842 Ok(steps[index])
843 }
844
845 fn step_from(
848 &self,
849 from: NodeId,
850 direction: Direction,
851 draw: &mut Draw<'_>,
852 ) -> Result<(&Interval, NodeId)> {
853 let steps = self.next_steps(from, direction)?;
854 let (edge, node) = self.choose(&steps, draw)?;
855 Ok((&self.edges[edge].interval, node))
856 }
857}
858
859impl IntervalNetwork {
861 pub fn transpose_step(&self, interval: &Interval, pitch: &Pitch) -> Result<Pitch> {
871 let mut rule = self.simplification;
872 if rule == Simplification::Exact && interval.is_implicit_diatonic() {
873 rule = Simplification::MostCommon;
874 }
875 advance(pitch, interval, rule)
876 }
877
878 #[must_use]
882 pub fn search_span(&self) -> IntegerType {
883 let widest = self
884 .edges
885 .iter()
886 .map(|edge| edge.interval.semitones().abs())
887 .fold(0.0, FloatType::max);
888 OCTAVE.max(widest.ceil() as IntegerType)
889 }
890
891 fn terminus_name(&self, start: NodeId, reference: &Pitch) -> Option<String> {
895 if self.octaves == Octaves::Duplicating && start.is_terminus() {
896 return Some(reference.name());
897 }
898 None
899 }
900
901 pub fn spell_terminus(&self, pitch: Pitch, node: NodeId, name: Option<&str>) -> Result<Pitch> {
911 let Some(name) = name else {
912 return Ok(pitch);
913 };
914 if pitch.name() == name || !node.is_terminus() {
915 return Ok(pitch);
916 }
917 let mut respelled = Pitch::from_name(name)?;
918 let octave = pitch.implicit_octave();
919 respelled.set_octave(Some(octave));
920 let octaves = (pitch.ps() - respelled.ps()) / FloatType::from(OCTAVE);
921 if octaves != octaves.round() {
922 return Ok(pitch);
923 }
924 respelled.set_octave(Some(octave + octaves.round() as IntegerType));
925 Ok(respelled)
926 }
927}
928
929impl IntervalNetwork {
931 pub fn realize_ascending(
940 &self,
941 reference: &Pitch,
942 start: Option<NodeName>,
943 range: &PitchRange,
944 fill: Fill,
945 draw: &mut Draw<'_>,
946 ) -> Result<Realized> {
947 let mut pitch = with_octave(reference);
948 let start = self.start_of(start)?;
949 let range = match (fill, range.is_open()) {
950 (Fill::IfUnbounded, true) => self.min_max_range(&pitch, start, draw)?,
951 _ => range.clone(),
952 };
953 if self.octaves == Octaves::Duplicating
954 && let Some(min) = &range.min
955 {
956 pitch = pitch.transpose_below_target(min, true)?;
957 }
958
959 let name = self.terminus_name(start, &pitch);
960 let mut node = start;
961 let mut realized = Realized::default();
962 for _ in 0..MAX_ASCENDING_STEPS {
963 if range.holds(&pitch) {
964 realized.push(pitch.clone(), node);
965 }
966 if range.max.as_ref().is_some_and(|max| at_least(&pitch, max)) {
967 return Ok(realized);
968 }
969 if node == NodeId::HIGH {
970 if range.max.is_none() {
971 return Ok(realized);
972 }
973 node = NodeId::LOW;
974 }
975 let (interval, reached) = self.step_from(node, Direction::Ascending, draw)?;
976 node = reached;
977 pitch = self.transpose_step(interval, &pitch)?;
978 pitch = self.spell_terminus(pitch, node, name.as_deref())?;
979 }
980 Err(Error::Scale(ILL_FORMED.to_string()))
981 }
982
983 pub fn realize_descending(
991 &self,
992 reference: &Pitch,
993 start: Option<NodeName>,
994 range: &PitchRange,
995 walk: DescendingWalk,
996 draw: &mut Draw<'_>,
997 ) -> Result<Realized> {
998 let mut pitch = with_octave(reference);
999 let start = self.start_of(start)?;
1000 let range = match (walk.fill, range.is_open()) {
1001 (Fill::IfUnbounded, true) => self.min_max_range(&pitch, start, draw)?,
1002 _ => range.clone(),
1003 };
1004 if self.octaves == Octaves::Duplicating
1005 && let Some(max) = &range.max
1006 {
1007 pitch = pitch.transpose_above_target(max, true)?;
1008 }
1009
1010 let name = self.terminus_name(start, &pitch);
1011 let mut node = start;
1012 let mut realized = Realized::default();
1013 let mut first = true;
1014 for _ in 0..MAX_DESCENDING_STEPS {
1015 if range.holds(&pitch) && (!first || walk.first == First::Include) {
1016 realized.push(pitch.clone(), node);
1017 }
1018 first = false;
1019 if range.min.as_ref().is_some_and(|min| pitch.ps() <= min.ps()) {
1020 return Ok(Self::ordered(realized, walk.order));
1021 }
1022 if node == NodeId::LOW {
1023 if range.min.is_none() {
1024 return Ok(Self::ordered(realized, walk.order));
1025 }
1026 node = NodeId::HIGH;
1027 }
1028 let (interval, reached) = self.step_from(node, Direction::Descending, draw)?;
1029 node = reached;
1030 pitch = self.transpose_step(&interval.reversed()?, &pitch)?;
1031 pitch = self.spell_terminus(pitch, node, name.as_deref())?;
1032 }
1033 Err(Error::Scale(ILL_FORMED.to_string()))
1034 }
1035
1036 fn ordered(mut realized: Realized, order: Order) -> Realized {
1038 if order == Order::Ascending {
1039 realized.reverse();
1040 }
1041 realized
1042 }
1043
1044 pub fn realize(
1056 &self,
1057 reference: &Pitch,
1058 start: Option<NodeName>,
1059 range: &PitchRange,
1060 direction: Direction,
1061 order: Order,
1062 draw: &mut Draw<'_>,
1063 ) -> Result<Realized> {
1064 let reference = with_octave(reference);
1065 let mut realized = match self.octaves {
1066 Octaves::Duplicating => {
1067 self.realize_directed(&reference, start, range, direction, draw)?
1068 }
1069 Octaves::Distinct => {
1070 let above = self.realize_ascending(&reference, start, range, Fill::Never, draw)?;
1071 let walk = DescendingWalk::new(First::Exclude, Fill::Never);
1072 let mut realized = self.realize_descending(&reference, start, range, walk, draw)?;
1073 realized.pitches.extend(above.pitches);
1074 realized.nodes.extend(above.nodes);
1075 realized
1076 }
1077 };
1078 if order == Order::Descending {
1079 realized.reverse();
1080 }
1081 Ok(realized)
1082 }
1083
1084 fn realize_directed(
1086 &self,
1087 reference: &Pitch,
1088 start: Option<NodeName>,
1089 range: &PitchRange,
1090 direction: Direction,
1091 draw: &mut Draw<'_>,
1092 ) -> Result<Realized> {
1093 let below_min = |pitch: &Pitch| match &range.min {
1094 Some(min) => pitch.transpose_below_target(min, false),
1095 None => Ok(pitch.clone()),
1096 };
1097 let above_max = |pitch: &Pitch| match &range.max {
1098 Some(max) => pitch.transpose_above_target(max, false),
1099 None => Ok(pitch.clone()),
1100 };
1101 match direction {
1102 Direction::Ascending => {
1103 let low = below_min(reference)?;
1104 self.realize_ascending(&low, start, range, Fill::IfUnbounded, draw)
1105 }
1106 Direction::Descending => {
1107 let high = above_max(reference)?;
1108 let walk = DescendingWalk::new(First::Include, Fill::IfUnbounded);
1109 self.realize_descending(&high, start, range, walk, draw)
1110 }
1111 Direction::Bi => {
1112 let low = below_min(reference)?;
1113 let up = self.realize_ascending(&low, start, range, Fill::Never, draw)?;
1114 let high = above_max(reference)?;
1115 let walk = DescendingWalk::new(First::Include, Fill::Never);
1116 let down = self.realize_descending(&high, start, range, walk, draw)?;
1117 Ok(Self::interleaved(up, down))
1118 }
1119 }
1120 }
1121
1122 fn interleaved(up: Realized, down: Realized) -> Realized {
1124 let mut merged = Realized::default();
1125 let longest = up.pitches.len().max(down.pitches.len());
1126 for index in 0..longest {
1127 for side in [&up, &down] {
1128 let Some(pitch) = side.pitches.get(index) else {
1129 continue;
1130 };
1131 if merged.pitches.iter().any(|held| same_pitch(held, pitch)) {
1132 continue;
1133 }
1134 merged.push(pitch.clone(), side.nodes[index]);
1135 }
1136 }
1137 merged
1138 }
1139
1140 pub fn realize_pitches(
1148 &self,
1149 reference: &Pitch,
1150 start: Option<NodeName>,
1151 range: &PitchRange,
1152 ) -> Result<Vec<Pitch>> {
1153 let realized = self.realize(
1154 reference,
1155 start,
1156 range,
1157 Direction::Ascending,
1158 Order::Ascending,
1159 &mut || 0.0,
1160 )?;
1161 Ok(realized.pitches)
1162 }
1163
1164 pub fn realize_intervals(
1171 &self,
1172 start: Option<NodeName>,
1173 range: &PitchRange,
1174 direction: Direction,
1175 order: Order,
1176 draw: &mut Draw<'_>,
1177 ) -> Result<Vec<Interval>> {
1178 let reference = Pitch::from_name("C4")?;
1179 let realized = self.realize(&reference, start, range, direction, order, draw)?;
1180 realized
1181 .pitches
1182 .windows(2)
1183 .map(|pair| Interval::between_pitches(&pair[0], &pair[1]))
1184 .collect()
1185 }
1186
1187 pub fn realize_termini(
1194 &self,
1195 reference: &Pitch,
1196 start: Option<NodeName>,
1197 draw: &mut Draw<'_>,
1198 ) -> Result<(Pitch, Pitch)> {
1199 let start = Some(NodeName::Id(self.start_of(start)?));
1200 let open = PitchRange::default();
1201 let above = self.realize_ascending(reference, start, &open, Fill::Never, draw)?;
1202 let walk = DescendingWalk::new(First::Exclude, Fill::Never);
1203 let below = self.realize_descending(reference, start, &open, walk, draw)?;
1204 let low = below.pitches.first().or(above.pitches.first());
1205 let high = above.pitches.last().or(below.pitches.last());
1206 match (low, high) {
1207 (Some(low), Some(high)) => Ok((low.clone(), high.clone())),
1208 _ => Err(Error::Scale(ILL_FORMED.to_string())),
1209 }
1210 }
1211
1212 pub fn realize_min_max(
1219 &self,
1220 reference: &Pitch,
1221 start: Option<NodeName>,
1222 draw: &mut Draw<'_>,
1223 ) -> Result<(Pitch, Pitch)> {
1224 let start = self.start_of(start)?;
1225 let range = self.min_max_range(&with_octave(reference), start, draw)?;
1226 match (range.min, range.max) {
1227 (Some(min), Some(max)) => Ok((min, max)),
1228 _ => Err(Error::Scale(ILL_FORMED.to_string())),
1229 }
1230 }
1231
1232 fn min_max_range(
1233 &self,
1234 reference: &Pitch,
1235 start: NodeId,
1236 draw: &mut Draw<'_>,
1237 ) -> Result<PitchRange> {
1238 let name = Some(NodeName::Id(start));
1239 let (low, high) = self.realize_termini(reference, name, draw)?;
1240
1241 let wide = PitchRange::between(shifted(&low, -OCTAVE)?, shifted(&high, OCTAVE)?);
1244 let above = self.realize_ascending(reference, name, &wide, Fill::Never, draw)?;
1245 let walk = DescendingWalk {
1246 first: First::Include,
1247 fill: Fill::Never,
1248 order: Order::Ascending,
1249 };
1250 let below = self.realize_descending(reference, name, &wide, walk, draw)?;
1251
1252 let (Some(first), Some(last)) = (above.pitches.first(), above.pitches.last()) else {
1253 return Err(Error::Scale(ILL_FORMED.to_string()));
1254 };
1255 let mut min = last.clone();
1256 let mut max = first.clone();
1257 let spans = Self::terminus_span(&above).chain(Self::terminus_span(&below));
1258 for pitch in spans {
1259 if pitch.ps() < min.ps() {
1260 min = pitch.clone();
1261 }
1262 if pitch.ps() > max.ps() {
1263 max = pitch.clone();
1264 }
1265 }
1266 Ok(PitchRange::between(min, max))
1267 }
1268
1269 fn terminus_span(realized: &Realized) -> impl Iterator<Item = &Pitch> {
1272 let mut span = Vec::new();
1273 let mut collecting = false;
1274 for (index, (pitch, node)) in realized.pitches.iter().zip(&realized.nodes).enumerate() {
1275 if index == 0 && node.is_terminus() {
1276 continue;
1277 }
1278 if node.is_terminus() && collecting {
1279 span.push(pitch);
1280 break;
1281 }
1282 if node.is_terminus() {
1283 collecting = true;
1284 }
1285 if collecting {
1286 span.push(pitch);
1287 }
1288 }
1289 span.into_iter()
1290 }
1291
1292 pub fn pitches_by_degree(
1299 &self,
1300 reference: &Pitch,
1301 start: Option<NodeName>,
1302 degrees: &[IntegerType],
1303 range: &PitchRange,
1304 direction: Direction,
1305 draw: &mut Draw<'_>,
1306 ) -> Result<Vec<Pitch>> {
1307 let realized = self.realize(reference, start, range, direction, Order::Ascending, draw)?;
1308 let wanted = degrees
1309 .iter()
1310 .map(|degree| self.degree_modulus(*degree))
1311 .collect::<Result<Vec<_>>>()?;
1312 let mut found = Vec::new();
1313 for (pitch, node) in realized.pitches.into_iter().zip(realized.nodes) {
1314 let degree = self.node_or_err(node)?.degree;
1315 if wanted.contains(&self.degree_modulus(degree)?) {
1316 found.push(pitch);
1317 }
1318 }
1319 Ok(found)
1320 }
1321}
1322
1323#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1325pub struct DescendingWalk {
1326 pub first: First,
1328 pub fill: Fill,
1330 pub order: Order,
1332}
1333
1334impl DescendingWalk {
1335 #[must_use]
1337 pub fn new(first: First, fill: Fill) -> Self {
1338 Self {
1339 first,
1340 fill,
1341 order: Order::Ascending,
1342 }
1343 }
1344}
1345
1346impl IntervalNetwork {
1348 fn search_range(&self, pitch: &Pitch) -> Result<PitchRange> {
1350 let span = self.search_span();
1351 Ok(PitchRange::between(
1352 shifted(pitch, -span)?,
1353 shifted(pitch, span)?,
1354 ))
1355 }
1356
1357 pub fn relative_node_ids(
1365 &self,
1366 reference: &Pitch,
1367 start: Option<NodeName>,
1368 target: &Pitch,
1369 comparison: DegreeComparison,
1370 direction: Direction,
1371 draw: &mut Draw<'_>,
1372 ) -> Result<Vec<NodeId>> {
1373 let start = Some(NodeName::Id(self.start_of(start)?));
1374 let target = with_octave(target);
1375 let range = self.search_range(&target)?;
1376 let realized = self.realize(reference, start, &range, direction, Order::Ascending, draw)?;
1377 let wanted = comparison.key(&target);
1378 let mut found: Vec<NodeId> = Vec::new();
1379 for (pitch, node) in realized.pitches.iter().zip(realized.nodes) {
1380 if comparison.key(pitch) == wanted && !found.contains(&node) {
1381 found.push(node);
1382 }
1383 }
1384 let mut degrees = Vec::with_capacity(found.len());
1385 for node in &found {
1386 degrees.push(self.node_or_err(*node)?.degree);
1387 }
1388 let mut order: Vec<usize> = (0..found.len()).collect();
1389 order.sort_by_key(|index| degrees[*index]);
1390 Ok(order.into_iter().map(|index| found[index]).collect())
1391 }
1392
1393 pub fn relative_node_id(
1400 &self,
1401 reference: &Pitch,
1402 start: Option<NodeName>,
1403 target: &Pitch,
1404 comparison: DegreeComparison,
1405 direction: Direction,
1406 draw: &mut Draw<'_>,
1407 ) -> Result<Option<NodeId>> {
1408 let found =
1409 self.relative_node_ids(reference, start, target, comparison, direction, draw)?;
1410 self.weighted_node(&found, draw)
1411 }
1412
1413 fn weighted_node(&self, nodes: &[NodeId], draw: &mut Draw<'_>) -> Result<Option<NodeId>> {
1415 match nodes {
1416 [] => Ok(None),
1417 [only] => Ok(Some(*only)),
1418 _ => {
1419 let weights = nodes
1420 .iter()
1421 .map(|node| Ok(self.node_or_err(*node)?.weight))
1422 .collect::<Result<Vec<_>>>()?;
1423 Ok(Some(nodes[weighted_index(&weights, draw())?]))
1424 }
1425 }
1426 }
1427
1428 pub fn relative_degree(
1435 &self,
1436 reference: &Pitch,
1437 start: Option<NodeName>,
1438 target: &Pitch,
1439 comparison: DegreeComparison,
1440 direction: Direction,
1441 draw: &mut Draw<'_>,
1442 ) -> Result<Option<IntegerType>> {
1443 let node = self.relative_node_id(reference, start, target, comparison, direction, draw)?;
1444 node.map(|node| self.degree_of(node)).transpose()
1445 }
1446
1447 pub fn neighbor_node_ids(
1455 &self,
1456 reference: &Pitch,
1457 start: Option<NodeName>,
1458 target: &Pitch,
1459 direction: Direction,
1460 draw: &mut Draw<'_>,
1461 ) -> Result<Option<(Option<NodeId>, NodeId)>> {
1462 let start = Some(NodeName::Id(self.start_of(start)?));
1463 let target = with_octave(target);
1464 let range = self.search_range(&target)?;
1465 let realized = self.realize(reference, start, &range, direction, Order::Ascending, draw)?;
1466 let mut low = None;
1467 for (pitch, node) in realized.pitches.iter().zip(realized.nodes) {
1468 if target.ps() < pitch.ps() {
1469 return Ok(Some((low, node)));
1470 }
1471 low = Some(node);
1472 }
1473 Ok(None)
1474 }
1475
1476 #[allow(clippy::too_many_arguments)]
1487 pub fn pitch_of_degree(
1488 &self,
1489 reference: &Pitch,
1490 name: NodeName,
1491 target: NodeName,
1492 direction: Direction,
1493 range: &PitchRange,
1494 termini: Termini,
1495 draw: &mut Draw<'_>,
1496 ) -> Result<Option<Pitch>> {
1497 let Some(start) = self
1498 .nodes_named(name, Termini::Equate, Moduli::Permit)?
1499 .first()
1500 .copied()
1501 else {
1502 return Err(Error::Scale(format!("no node is named {name:?}")));
1503 };
1504 let wanted = self.target_node(target, direction, termini)?;
1505 let tries = match self.pathways {
1506 Pathways::Deterministic => 1,
1507 Pathways::Weighted => WEIGHTED_TRIES,
1508 };
1509 for _ in 0..tries {
1510 let realized = self.realize(
1511 reference,
1512 Some(NodeName::Id(start)),
1513 range,
1514 direction,
1515 Order::Ascending,
1516 draw,
1517 )?;
1518 for (pitch, node) in realized.pitches.iter().zip(&realized.nodes) {
1519 let both_termini = node.is_terminus() && wanted.is_terminus();
1520 if *node == wanted || (termini == Termini::Equate && both_termini) {
1521 return Ok(Some(pitch.clone()));
1522 }
1523 }
1524 }
1525 Ok(None)
1526 }
1527
1528 fn target_node(
1531 &self,
1532 target: NodeName,
1533 direction: Direction,
1534 termini: Termini,
1535 ) -> Result<NodeId> {
1536 let named = self.nodes_named(target, termini, Moduli::Permit)?;
1537 let Some(first) = named.first().copied() else {
1538 return Err(Error::Scale(format!("no node is named {target:?}")));
1539 };
1540 if named.len() == 1 || named == [NodeId::LOW, NodeId::HIGH] {
1541 return Ok(first);
1542 }
1543 for node in &named {
1544 if self.edge_directions(*node)?.contains(&direction) {
1545 return Ok(*node);
1546 }
1547 }
1548 Ok(first)
1549 }
1550
1551 pub fn match_pitches(
1558 &self,
1559 reference: &Pitch,
1560 start: Option<NodeName>,
1561 targets: &[Pitch],
1562 comparison: DegreeComparison,
1563 ) -> Result<Matched> {
1564 let start = Some(NodeName::Id(self.start_of(start)?));
1565 let Some((low, high)) = pitch_bounds(targets) else {
1566 return Err(Error::Value(
1567 "There must be at least one pitch given.".to_string(),
1568 ));
1569 };
1570 let range = PitchRange::between(targets[low].clone(), targets[high].clone());
1571 let realized = self.realize_pitches(reference, start, &range)?;
1572 let keys: Vec<String> = realized.iter().map(|pitch| comparison.key(pitch)).collect();
1573 let mut matched = Matched::default();
1574 for (index, target) in targets.iter().enumerate() {
1575 if keys.contains(&comparison.key(target)) {
1576 matched.matched.push(index);
1577 } else {
1578 matched.unmatched.push(index);
1579 }
1580 }
1581 Ok(matched)
1582 }
1583
1584 pub fn find_missing(
1591 &self,
1592 reference: &Pitch,
1593 start: Option<NodeName>,
1594 targets: &[Pitch],
1595 comparison: DegreeComparison,
1596 range: &PitchRange,
1597 ) -> Result<Vec<Pitch>> {
1598 let start = Some(NodeName::Id(self.start_of(start)?));
1599 let realized = self.realize_pitches(reference, start, range)?;
1600 if targets.is_empty() {
1601 return Err(Error::Value(
1602 "There must be at least one pitch given.".to_string(),
1603 ));
1604 }
1605 let keys: Vec<String> = targets.iter().map(|pitch| comparison.key(pitch)).collect();
1606 Ok(realized
1607 .into_iter()
1608 .filter(|pitch| !keys.contains(&comparison.key(pitch)))
1609 .collect())
1610 }
1611
1612 pub fn find(&self, targets: &[Pitch], comparison: DegreeComparison) -> Result<Vec<Found>> {
1620 let mut found = Vec::with_capacity(SCALE_STARTS.len());
1621 for name in SCALE_STARTS {
1622 let tonic = Pitch::from_name(name)?;
1623 let matched = self.match_pitches(&tonic, None, targets, comparison)?;
1624 found.push(Found {
1625 matches: matched.matched.len(),
1626 tonic,
1627 });
1628 }
1629
1630 found.sort_by(|a, b| {
1633 a.matches
1634 .cmp(&b.matches)
1635 .then(a.tonic.ps().total_cmp(&b.tonic.ps()))
1636 });
1637 found.reverse();
1638 Ok(found)
1639 }
1640
1641 #[allow(clippy::too_many_arguments)]
1649 pub fn next_pitch(
1650 &self,
1651 reference: &Pitch,
1652 name: NodeName,
1653 origin: &Pitch,
1654 direction: Direction,
1655 step_size: usize,
1656 neighbor: Neighbor,
1657 draw: &mut Draw<'_>,
1658 ) -> Result<Option<Pitch>> {
1659 let (mut node, mut pitch) =
1660 self.node_and_pitch_at(reference, name, origin, direction, neighbor, draw)?;
1661 let named = self.nodes_named(name, Termini::Equate, Moduli::Permit)?;
1662 let terminus = named
1663 .first()
1664 .and_then(|first| self.terminus_name(*first, reference));
1665 let mut next = None;
1666 for _ in 0..step_size {
1667 let (interval, reached) = self.step_from(node, direction, draw)?;
1668 node = reached;
1669 pitch = match direction {
1670 Direction::Ascending => self.transpose_step(interval, &pitch)?,
1671 _ => self.transpose_step(&interval.reversed()?, &pitch)?,
1672 };
1673 pitch = self.spell_terminus(pitch, node, terminus.as_deref())?;
1674 next = Some(pitch.clone());
1675 }
1676 Ok(next)
1677 }
1678
1679 fn node_and_pitch_at(
1683 &self,
1684 reference: &Pitch,
1685 name: NodeName,
1686 origin: &Pitch,
1687 direction: Direction,
1688 neighbor: Neighbor,
1689 draw: &mut Draw<'_>,
1690 ) -> Result<(NodeId, Pitch)> {
1691 let origin_ps = origin.ps();
1692 let span = FloatType::from(self.search_span());
1693 let range = PitchRange::between(
1694 Pitch::from_number(origin_ps - span)?,
1695 Pitch::from_number(origin_ps + span)?,
1696 );
1697 let realized = self.realize(
1698 reference,
1699 Some(name),
1700 &range,
1701 direction,
1702 Order::Ascending,
1703 draw,
1704 )?;
1705 let (node, at_or_below) =
1706 self.start_node(&realized, origin_ps, direction, neighbor, draw)?;
1707
1708 let mut best: Option<&Pitch> = None;
1711 for (pitch, held) in realized.pitches.iter().zip(&realized.nodes) {
1712 if Some(*held) != node {
1713 continue;
1714 }
1715 let ps = pitch.ps();
1716 let better = match (at_or_below, best) {
1717 (true, _) if ps > origin_ps => false,
1718 (false, _) if ps < origin_ps => false,
1719 (_, None) => true,
1720 (true, Some(held)) => ps > held.ps(),
1721 (false, Some(held)) => ps < held.ps(),
1722 };
1723 if better {
1724 best = Some(pitch);
1725 }
1726 }
1727 match (node, best) {
1728 (Some(node), Some(pitch)) => Ok((node, pitch.clone())),
1729 _ => Err(Error::Scale(
1730 "Could not find a pitch for the requested node degree".to_string(),
1731 )),
1732 }
1733 }
1734
1735 fn start_node(
1739 &self,
1740 realized: &Realized,
1741 origin_ps: FloatType,
1742 direction: Direction,
1743 neighbor: Neighbor,
1744 draw: &mut Draw<'_>,
1745 ) -> Result<(Option<NodeId>, bool)> {
1746 let mut matched: Vec<NodeId> = Vec::new();
1747 let mut low = None;
1748 let mut high = None;
1749 for (pitch, node) in realized.pitches.iter().zip(&realized.nodes) {
1750 let ps = pitch.ps();
1751 if ps == origin_ps {
1752 if !matched.contains(node) {
1753 matched.push(*node);
1754 }
1755 } else if high.is_none() {
1756 if ps < origin_ps {
1757 low = Some(*node);
1758 } else {
1759 high = Some(*node);
1760 }
1761 }
1762 }
1763
1764 let ascending = direction == Direction::Ascending;
1765 if !matched.is_empty() {
1766 let mut degrees = Vec::with_capacity(matched.len());
1767 for node in &matched {
1768 degrees.push((self.node_or_err(*node)?.degree, *node));
1769 }
1770 degrees.sort_by_key(|(degree, _)| *degree);
1771 let sorted: Vec<NodeId> = degrees.into_iter().map(|(_, node)| node).collect();
1772 return Ok((self.weighted_node(&sorted, draw)?, ascending));
1773 }
1774 Ok(match neighbor {
1775 Neighbor::Never => (None, false),
1776 Neighbor::Below => (low, true),
1777 Neighbor::Above => (high, false),
1778 })
1779 }
1780}
1781
1782impl ScaleType {
1783 pub fn network(self) -> Result<IntervalNetwork> {
1791 let mut network = IntervalNetwork::default();
1792 match self {
1793 Self::MelodicMinor => network.fill_melodic_minor()?,
1794 Self::RagAsawari => network.fill_table(&RAG_ASAWARI_NODES, &RAG_ASAWARI_EDGES)?,
1795 Self::RagMarwa => network.fill_table(&RAG_MARWA_NODES, &RAG_MARWA_EDGES)?,
1796 _ => {
1797 let steps = self
1798 .realization_steps()
1799 .into_iter()
1800 .map(Interval::from_name)
1801 .collect::<Result<Vec<_>>>()?;
1802 network.fill_bidirected(&steps);
1803 }
1804 }
1805 network.octaves = Octaves::Duplicating;
1806 network.simplification = self.simplification();
1807 Ok(network)
1808 }
1809}
1810
1811const OCTAVE_DIVISORS: [IntegerType; 6] = [1, 2, 3, 4, 6, 12];
1814
1815const OCTAVE_SEMITONES: FloatType = 12.0;
1817
1818pub fn close_on_tonic(steps: &[Interval]) -> Result<Vec<Interval>> {
1826 let Some((last, before)) = steps.split_last() else {
1827 return Ok(Vec::new());
1828 };
1829 let tonic = Pitch::from_name("C4")?;
1830 let mut reached = tonic.clone();
1831 for step in before {
1832 reached = step.transpose_pitch_with_options(&reached, false, Some(1))?;
1833 }
1834 let octave = Interval::from_name("P8")?.transpose_pitch(&tonic)?;
1835 if last.transpose_pitch(&reached)?.name_with_octave() == octave.name_with_octave() {
1836 return Ok(steps.to_vec());
1837 }
1838 let mut closed = before.to_vec();
1839 closed.push(Interval::between_pitches(&reached, &octave)?);
1840 Ok(closed)
1841}
1842
1843pub fn cyclical(steps: &[Interval]) -> Result<IntervalNetwork> {
1851 let span: FloatType = steps.iter().map(Interval::semitones).sum();
1852 let whole = steps.iter().all(|step| step.semitones().fract() == 0.0);
1853 let divides = whole
1854 && OCTAVE_DIVISORS
1855 .iter()
1856 .any(|divisor| (span - FloatType::from(*divisor)).abs() < FloatType::EPSILON);
1857
1858 let mut network = IntervalNetwork::default();
1859 if !divides {
1860 network.fill_bidirected(steps);
1861 return Ok(network);
1862 }
1863 let repeats = (OCTAVE_SEMITONES / span) as usize;
1864 let filled: Vec<Interval> = steps
1865 .iter()
1866 .cycle()
1867 .take(steps.len() * repeats)
1868 .cloned()
1869 .collect();
1870 network.fill_bidirected(&close_on_tonic(&filled)?);
1871 network.octaves = Octaves::Duplicating;
1872 Ok(network)
1873}
1874
1875pub fn octave_repeating(steps: &[Interval]) -> Result<(Vec<Interval>, IntervalNetwork)> {
1884 let total = Interval::sum(steps)?;
1885 let mut span = total.semitones();
1886 let mut completed = steps.to_vec();
1887 if span == OCTAVE_SEMITONES && total.short_name() != "P8" {
1888 completed = close_on_tonic(steps)?;
1889 } else if span != OCTAVE_SEMITONES {
1890 let rest = total.complement()?;
1891 if rest.semitones() != 0.0 {
1892 span += rest.semitones();
1893 completed.push(rest);
1894 }
1895 }
1896
1897 let mut network = IntervalNetwork::default();
1898 network.fill_bidirected(&completed);
1899 if span == OCTAVE_SEMITONES {
1900 network.octaves = Octaves::Duplicating;
1901 }
1902 Ok((completed, network))
1903}
1904
1905pub fn weighted_hexatonic_blues() -> Result<IntervalNetwork> {
1913 let mut network = IntervalNetwork::default();
1914 network.fill_table(&BLUES_NODES, &BLUES_EDGES)?;
1915 network.octaves = Octaves::Duplicating;
1916 network.pathways = Pathways::Weighted;
1917 Ok(network)
1918}
1919
1920type TableNode = (NodeId, IntegerType);
1922
1923type TableEdge = (&'static str, NodeId, NodeId, Direction);
1926
1927const UP: Direction = Direction::Ascending;
1928const DOWN: Direction = Direction::Descending;
1929const BOTH: Direction = Direction::Bi;
1930const LOW: NodeId = NodeId::LOW;
1931const HIGH: NodeId = NodeId::HIGH;
1932
1933const fn at(index: usize) -> NodeId {
1934 NodeId::Index(index)
1935}
1936
1937const MELODIC_MINOR_NODES: [TableNode; 10] = [
1940 (LOW, 1),
1941 (at(0), 2),
1942 (at(1), 3),
1943 (at(2), 4),
1944 (at(3), 5),
1945 (at(4), 6),
1946 (at(5), 6),
1947 (at(6), 7),
1948 (at(7), 7),
1949 (HIGH, 8),
1950];
1951
1952const MELODIC_MINOR_EDGES: [TableEdge; 10] = [
1953 ("M2", LOW, at(0), BOTH),
1954 ("m2", at(0), at(1), BOTH),
1955 ("M2", at(1), at(2), BOTH),
1956 ("M2", at(2), at(3), BOTH),
1957 ("M2", at(3), at(4), UP),
1958 ("M2", at(4), at(6), UP),
1959 ("m2", at(6), HIGH, UP),
1960 ("M2", HIGH, at(7), DOWN),
1961 ("M2", at(7), at(5), DOWN),
1962 ("m2", at(5), at(3), DOWN),
1963];
1964
1965const RAG_ASAWARI_NODES: [TableNode; 12] = [
1968 (LOW, 1),
1969 (at(0), 2),
1970 (at(1), 4),
1971 (at(2), 5),
1972 (at(3), 6),
1973 (HIGH, 8),
1974 (at(4), 7),
1975 (at(5), 6),
1976 (at(6), 5),
1977 (at(7), 4),
1978 (at(8), 3),
1979 (at(9), 2),
1980];
1981
1982const RAG_ASAWARI_EDGES: [TableEdge; 12] = [
1983 ("M2", LOW, at(0), UP),
1984 ("m3", at(0), at(1), UP),
1985 ("M2", at(1), at(2), UP),
1986 ("m2", at(2), at(3), UP),
1987 ("M3", at(3), HIGH, UP),
1988 ("M2", HIGH, at(4), DOWN),
1989 ("M2", at(4), at(5), DOWN),
1990 ("m2", at(5), at(6), DOWN),
1991 ("M2", at(6), at(7), DOWN),
1992 ("M2", at(7), at(8), DOWN),
1993 ("m2", at(8), at(9), DOWN),
1994 ("M2", at(9), LOW, DOWN),
1995];
1996
1997const RAG_MARWA_NODES: [TableNode; 14] = [
2000 (LOW, 1),
2001 (at(0), 2),
2002 (at(1), 3),
2003 (at(2), 4),
2004 (at(3), 5),
2005 (at(4), 6),
2006 (at(5), 7),
2007 (HIGH, 8),
2008 (at(6), 7),
2009 (at(7), 6),
2010 (at(8), 5),
2011 (at(9), 4),
2012 (at(10), 3),
2013 (at(11), 2),
2014];
2015
2016const RAG_MARWA_EDGES: [TableEdge; 14] = [
2017 ("m2", LOW, at(0), UP),
2018 ("A2", at(0), at(1), UP),
2019 ("M2", at(1), at(2), UP),
2020 ("m3", at(2), at(3), UP),
2021 ("M2", at(3), at(4), UP),
2022 ("-M2", at(4), at(5), UP),
2023 ("m3", at(5), HIGH, UP),
2024 ("-m2", HIGH, at(6), DOWN),
2025 ("d3", at(6), at(7), DOWN),
2026 ("M2", at(7), at(8), DOWN),
2027 ("m3", at(8), at(9), DOWN),
2028 ("M2", at(9), at(10), DOWN),
2029 ("A2", at(10), at(11), DOWN),
2030 ("m2", at(11), LOW, DOWN),
2031];
2032
2033const BLUES_NODES: [TableNode; 7] = [
2035 (LOW, 1),
2036 (at(0), 2),
2037 (at(1), 3),
2038 (at(2), 4),
2039 (at(3), 5),
2040 (at(4), 6),
2041 (HIGH, 7),
2042];
2043
2044const BLUES_EDGES: [TableEdge; 7] = [
2046 ("m3", LOW, at(0), BOTH),
2047 ("M2", at(0), at(1), BOTH),
2048 ("M2", at(1), at(3), BOTH),
2049 ("a1", at(1), at(2), BOTH),
2050 ("m2", at(2), at(3), BOTH),
2051 ("m3", at(3), at(4), BOTH),
2052 ("M2", at(4), HIGH, BOTH),
2053];
2054
2055#[cfg(test)]
2056mod tests {
2057 use super::*;
2058
2059 fn pitch(name: &str) -> Pitch {
2060 Pitch::from_name(name).unwrap()
2061 }
2062
2063 fn names(pitches: &[Pitch]) -> Vec<String> {
2064 pitches.iter().map(Pitch::name_with_octave).collect()
2065 }
2066
2067 fn major() -> IntervalNetwork {
2068 IntervalNetwork::bidirected(&["M2", "M2", "m2", "M2", "M2", "M2", "m2"]).unwrap()
2069 }
2070
2071 fn melodic_minor() -> IntervalNetwork {
2072 let mut network = IntervalNetwork::default();
2073 network.fill_melodic_minor().unwrap();
2074 network
2075 }
2076
2077 fn no_draw() -> FloatType {
2078 0.0
2079 }
2080
2081 #[test]
2082 fn a_major_scale_is_realized_on_any_degree() {
2083 let network = major();
2084 let realized = network
2085 .realize_pitches(
2086 &pitch("C#"),
2087 Some(NodeName::Degree(7)),
2088 &PitchRange::default(),
2089 )
2090 .unwrap();
2091 assert_eq!(
2092 names(&realized),
2093 ["D3", "E3", "F#3", "G3", "A3", "B3", "C#4", "D4"]
2094 );
2095 let ranged = network
2096 .realize_pitches(
2097 &pitch("F4"),
2098 Some(NodeName::Degree(1)),
2099 &PitchRange::between(pitch("C3"), pitch("C4")),
2100 )
2101 .unwrap();
2102 assert_eq!(
2103 names(&ranged),
2104 ["C3", "D3", "E3", "F3", "G3", "A3", "Bb3", "C4"]
2105 );
2106 }
2107
2108 #[test]
2109 fn a_fifth_cycle_need_not_repeat_at_the_octave() {
2110 let network = IntervalNetwork::bidirected(&["P5", "P5", "P5"]).unwrap();
2111 let realized = network
2112 .realize_pitches(
2113 &pitch("C4"),
2114 Some(NodeName::Degree(1)),
2115 &PitchRange::between(pitch("C4"), pitch("C11")),
2116 )
2117 .unwrap();
2118 assert_eq!(realized.len(), 13);
2119 assert_eq!(realized[12].name_with_octave(), "B#10");
2120 }
2121
2122 #[test]
2123 fn a_melodic_minor_comes_down_by_other_steps() {
2124 let network = melodic_minor();
2125 let mut draw = no_draw;
2126 let down = network
2127 .realize(
2128 &pitch("G4"),
2129 Some(NodeName::Id(NodeId::HIGH)),
2130 &PitchRange::default(),
2131 Direction::Descending,
2132 Order::Ascending,
2133 &mut draw,
2134 )
2135 .unwrap();
2136 assert_eq!(
2137 names(&down.pitches),
2138 ["G3", "A3", "Bb3", "C4", "D4", "Eb4", "F4", "G4"]
2139 );
2140 let sixth = network
2141 .pitch_of_degree(
2142 &pitch("C4"),
2143 NodeName::Degree(1),
2144 NodeName::Degree(6),
2145 Direction::Descending,
2146 &PitchRange::default(),
2147 Termini::Equate,
2148 &mut draw,
2149 )
2150 .unwrap()
2151 .unwrap();
2152 assert_eq!(sixth.name_with_octave(), "Ab4");
2153 }
2154
2155 #[test]
2156 fn the_next_pitch_steps_from_a_neighbor() {
2157 let network = melodic_minor();
2158 let mut draw = no_draw;
2159 let next = network
2160 .next_pitch(
2161 &pitch("C4"),
2162 NodeName::Degree(1),
2163 &pitch("C#4"),
2164 Direction::Ascending,
2165 1,
2166 Neighbor::Below,
2167 &mut draw,
2168 )
2169 .unwrap()
2170 .unwrap();
2171 assert_eq!(next.name_with_octave(), "D4");
2172 let neighbors = network
2173 .neighbor_node_ids(
2174 &pitch("C4"),
2175 Some(NodeName::Degree(1)),
2176 &pitch("C#"),
2177 Direction::Ascending,
2178 &mut draw,
2179 )
2180 .unwrap();
2181 assert_eq!(neighbors, Some((Some(NodeId::HIGH), NodeId::Index(0))));
2182 }
2183
2184 #[test]
2185 fn find_ranks_the_tonics_by_matches() {
2186 let targets: Vec<Pitch> = ["g", "a", "b", "d", "f#"].map(pitch).to_vec();
2187 let found = major()
2188 .find(&targets, DegreeComparison::PitchClass)
2189 .unwrap();
2190 let top: Vec<(usize, String)> = found[..4]
2191 .iter()
2192 .map(|found| (found.matches, found.tonic.name()))
2193 .collect();
2194 assert_eq!(
2195 top,
2196 [
2197 (5, "G".to_string()),
2198 (5, "D".to_string()),
2199 (4, "A".to_string()),
2200 (4, "C".to_string())
2201 ]
2202 );
2203 }
2204
2205 fn steps(names: &[&str]) -> Vec<Interval> {
2206 names
2207 .iter()
2208 .map(|name| Interval::from_name(name).unwrap())
2209 .collect()
2210 }
2211
2212 fn named(steps: &[Interval]) -> Vec<String> {
2213 steps.iter().map(Interval::short_name).collect()
2214 }
2215
2216 #[test]
2217 fn closing_on_the_tonic_respells_the_last_step() {
2218 assert_eq!(
2219 named(&close_on_tonic(&steps(&["M3", "M3", "M3"])).unwrap()),
2220 ["M3", "M3", "d4"]
2221 );
2222 assert_eq!(
2223 named(&close_on_tonic(&steps(&["m3", "M3", "P4"])).unwrap()),
2224 ["m3", "M3", "P4"]
2225 );
2226 }
2227
2228 #[test]
2229 fn a_cycle_dividing_the_octave_repeats_at_it() {
2230 let thirds = cyclical(&steps(&["M3"])).unwrap();
2231 assert_eq!(thirds.octaves, Octaves::Duplicating);
2232 assert_eq!(thirds.degree_max_unique(), Some(3));
2233 assert_eq!(
2234 cyclical(&steps(&["P5"])).unwrap().octaves,
2235 Octaves::Distinct
2236 );
2237 }
2238
2239 #[test]
2240 fn octave_repeating_steps_are_completed_to_the_octave() {
2241 let (completed, network) = octave_repeating(&steps(&["M3", "m3"])).unwrap();
2242 assert_eq!(named(&completed), ["M3", "m3", "P4"]);
2243 assert_eq!(network.octaves, Octaves::Duplicating);
2244 let (completed, _) = octave_repeating(&steps(&["P8"])).unwrap();
2245 assert_eq!(named(&completed), ["P8"]);
2246 }
2247
2248 #[test]
2249 fn the_blues_network_branches_at_f() {
2250 let network = weighted_hexatonic_blues().unwrap();
2251 assert_eq!(network.pathways, Pathways::Weighted);
2252 let from_f = network.next_steps(at(1), Direction::Ascending).unwrap();
2253 let mut reached: Vec<NodeId> = from_f.into_iter().map(|(_, node)| node).collect();
2254 reached.sort_by_key(|node| network.node(*node).unwrap().degree);
2255 assert_eq!(reached, [at(2), at(3)]);
2256 }
2257
2258 #[test]
2259 fn rag_marwa_sounds_one_note_on_two_degrees() {
2260 let network = ScaleType::RagMarwa.network().unwrap();
2261 let mut draw = no_draw;
2262 let mut degrees = |target: &str, direction| {
2263 let nodes = network
2264 .relative_node_ids(
2265 &pitch("C4"),
2266 Some(NodeName::Degree(1)),
2267 &pitch(target),
2268 DegreeComparison::Ps,
2269 direction,
2270 &mut draw,
2271 )
2272 .unwrap();
2273 nodes
2274 .into_iter()
2275 .map(|node| network.node(node).unwrap().degree)
2276 .collect::<Vec<_>>()
2277 };
2278 assert_eq!(degrees("A4", Direction::Ascending), [5, 7]);
2279 assert_eq!(degrees("D-3", Direction::Descending), [2, 7]);
2280 }
2281
2282 #[test]
2283 fn a_degree_past_the_ends_folds_back() {
2284 let network = major();
2285 assert_eq!(network.degree_modulus(0).unwrap(), 7);
2286 assert_eq!(network.degree_modulus(9).unwrap(), 2);
2287 assert_eq!(
2288 network
2289 .nodes_named(NodeName::Degree(-1), Termini::Equate, Moduli::Permit)
2290 .unwrap(),
2291 [NodeId::Index(4)]
2292 );
2293 }
2294
2295 #[test]
2296 fn a_one_way_edge_has_no_both_ways() {
2297 let mut edge = Edge::new(Interval::from_name("M3").unwrap(), Some(0));
2298 edge.connect(NodeId::Index(0), NodeId::Index(1), Direction::Ascending)
2299 .unwrap();
2300 assert!(edge.connections_toward(Direction::Bi).is_err());
2301 assert!(
2302 edge.connections_toward(Direction::Descending)
2303 .unwrap()
2304 .is_empty()
2305 );
2306 }
2307
2308 #[test]
2309 fn weights_choose_between_branches() {
2310 let mut network = IntervalNetwork::default();
2311 let mut heavy = Node::new(NodeId::Index(0), 2);
2312 heavy.weight = 3.0;
2313 let nodes = vec![
2314 Node::new(NodeId::LOW, 1),
2315 heavy,
2316 Node::new(NodeId::Index(1), 2),
2317 Node::new(NodeId::HIGH, 3),
2318 ];
2319 let edge = |name: &str, from, to| EdgeSpec {
2320 interval: Interval::from_name(name).unwrap(),
2321 connections: vec![(from, to, Direction::Ascending)],
2322 };
2323 let edges = vec![
2324 edge("M2", NodeId::LOW, NodeId::Index(0)),
2325 edge("m2", NodeId::LOW, NodeId::Index(1)),
2326 edge("P4", NodeId::Index(0), NodeId::HIGH),
2327 edge("A4", NodeId::Index(1), NodeId::HIGH),
2328 ];
2329 network.fill_arbitrary(nodes, edges).unwrap();
2330 let open = PitchRange::default();
2331 let mut low_draw = || 0.1;
2332 let heavy_way = network
2333 .realize_ascending(&pitch("C4"), None, &open, Fill::Never, &mut low_draw)
2334 .unwrap();
2335 assert_eq!(names(&heavy_way.pitches), ["C4", "D4", "G4"]);
2336 let mut high_draw = || 0.9;
2337 let light_way = network
2338 .realize_ascending(&pitch("C4"), None, &open, Fill::Never, &mut high_draw)
2339 .unwrap();
2340 assert_eq!(names(&light_way.pitches), ["C4", "Db4", "G4"]);
2341 }
2342}