Skip to main content

music21/scale/
intervalnetwork.rs

1//! music21's `IntervalNetwork`: a scale or a chord as a graph whose nodes
2//! are pitches not yet realized and whose edges are intervals.
3//!
4//! A network has two ends, its low and high termini, which are the same
5//! pitch class an octave or more apart; walking off one end comes back in
6//! at the other, so a scale can be realized over any range. Edges are
7//! walked ascending, descending or both ways, which is how a melodic minor
8//! goes up by one set of steps and down by another. Where two edges leave
9//! a node the same way, the node weights choose between them, from a draw
10//! the caller supplies: nothing here reaches for a random number generator
11//! of its own.
12//!
13//! ```
14//! use music21::Pitch;
15//! use music21::scale::intervalnetwork::{IntervalNetwork, PitchRange};
16//!
17//! let major = IntervalNetwork::bidirected(&["M2", "M2", "m2", "M2", "M2", "M2", "m2"])?;
18//! let realized = major.realize_pitches(&Pitch::from_name("G4")?, None, &PitchRange::default())?;
19//! let names: Vec<String> = realized.iter().map(Pitch::name_with_octave).collect();
20//! assert_eq!(names, ["G4", "A4", "B4", "C5", "D5", "E5", "F#5", "G5"]);
21//! # Ok::<(), music21::Error>(())
22//! ```
23
24use 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
32/// How close two pitch-space values must be to count as the same.
33const EPSILON: FloatType = 0.00001;
34
35/// The most steps an ascending walk takes before giving up on reaching
36/// its target: music21's `maxAttempts`.
37const MAX_ASCENDING_STEPS: usize = 100;
38
39/// The most steps a descending walk takes. music21 sets no limit; one is
40/// set here so that a network that never descends fails instead of hanging.
41const MAX_DESCENDING_STEPS: usize = 10_000;
42
43/// How many semitones either side of a pitch a search realizes at least.
44const OCTAVE: IntegerType = 12;
45
46/// How many times a weighted network is realized looking for a degree it
47/// may skip: 40 tries miss a node that is there once in a trillion.
48const WEIGHTED_TRIES: usize = 40;
49
50/// The complaint music21 makes about a walk that does not reach its target.
51const ILL_FORMED: &str = "Cannot realize these pitches; is your scale well-formed? \
52                          (especially check if you're giving notes without octaves)";
53
54/// A source of draws from `0.0` (inclusive) to `1.0` (exclusive), used to
55/// choose between branches by weight.
56pub type Draw<'a> = dyn FnMut() -> FloatType + 'a;
57
58/// Either end of a network: music21's `Terminus`.
59#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
60#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
61pub enum Terminus {
62    /// The bottom: the pitch a realization starts from.
63    Low,
64    /// The top: the same pitch class, where the walk comes back in at the
65    /// bottom.
66    High,
67}
68
69/// Which node an edge connects: a terminus, or a node between them,
70/// numbered as it was added.
71#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
72#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
73pub enum NodeId {
74    /// One of the two ends.
75    Terminus(Terminus),
76    /// A node between them.
77    Index(usize),
78}
79
80impl NodeId {
81    /// The low terminus.
82    pub const LOW: Self = Self::Terminus(Terminus::Low);
83    /// The high terminus.
84    pub const HIGH: Self = Self::Terminus(Terminus::High);
85
86    /// Whether this is either end of the network.
87    #[must_use]
88    pub fn is_terminus(self) -> bool {
89        matches!(self, Self::Terminus(_))
90    }
91}
92
93/// The way an edge is walked: music21's `Direction`.
94#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
95#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
96pub enum Direction {
97    /// Both ways.
98    Bi,
99    /// Up only.
100    Ascending,
101    /// Down only.
102    Descending,
103}
104
105/// A pitch the network does not hold yet: music21's `Node`.
106///
107/// The `degree` is what a scale calls the node, counted from one at the low
108/// terminus; two nodes may share one, as the raised and natural sixths of a
109/// melodic minor do. The `weight` decides between nodes that both answer.
110#[derive(Clone, Debug, PartialEq)]
111#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
112pub struct Node {
113    /// Which node this is.
114    pub id: NodeId,
115    /// The scale degree it stands for.
116    pub degree: IntegerType,
117    /// How likely it is to be chosen where several could be.
118    pub weight: FloatType,
119}
120
121impl Node {
122    /// A node of weight one.
123    #[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/// An interval between two nodes, and the way it is walked: music21's
134/// `Edge`.
135#[derive(Clone, Debug, PartialEq)]
136pub struct Edge {
137    /// The step.
138    pub interval: Interval,
139    /// The way it is walked, set as connections are added.
140    pub direction: Direction,
141    /// Carried for music21's sake; nothing reads it.
142    pub weight: FloatType,
143    /// Its key in the network, if it has been put in one.
144    pub id: Option<usize>,
145    connections: Vec<(NodeId, NodeId)>,
146}
147
148impl Edge {
149    /// An edge connecting nothing yet.
150    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    /// Connects `from` to `to`, walked `direction`: music21's
161    /// `addDirectedConnection`.
162    ///
163    /// # Errors
164    ///
165    /// [`Direction::Bi`], which is not one way. The connection is kept all
166    /// the same, as music21 keeps it.
167    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    /// Connects `low` to `high` going up and back going down: music21's
177    /// `addBiDirectedConnections`.
178    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    /// Every pair of nodes this edge connects, the way up first.
185    #[must_use]
186    pub fn connections(&self) -> &[(NodeId, NodeId)] {
187        &self.connections
188    }
189
190    /// The connections walked `direction`: music21's `getConnections`.
191    ///
192    /// # Errors
193    ///
194    /// Asking a one-way edge for both ways.
195    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        // A two-way edge holds its way up first and its way down second.
209        let index = usize::from(direction == Direction::Descending);
210        Ok(self.connections.get(index).into_iter().copied().collect())
211    }
212}
213
214/// An edge of [`IntervalNetwork::fill_arbitrary`]: its step and the nodes
215/// it connects, each pair with the way it is walked.
216#[derive(Clone, Debug)]
217pub struct EdgeSpec {
218    /// The step.
219    pub interval: Interval,
220    /// Pairs of node ids and the way each is walked.
221    pub connections: Vec<(NodeId, NodeId, Direction)>,
222}
223
224/// Whether a network's pitches repeat at the octave, which lets a walk
225/// start an octave from where it was asked to.
226#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
227pub enum Octaves {
228    /// They repeat.
229    Duplicating,
230    /// They need not.
231    Distinct,
232}
233
234/// Whether every walk through a network takes the same way.
235#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
236pub enum Pathways {
237    /// No node has two ways on in one direction.
238    Deterministic,
239    /// Some node has, and its weights choose.
240    Weighted,
241}
242
243/// Whether the two termini count as one degree.
244#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
245pub enum Termini {
246    /// The high terminus has the low one's degree.
247    Equate,
248    /// Each has its own.
249    Distinct,
250}
251
252/// Whether a degree past either end is folded back into the network.
253#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
254pub enum Moduli {
255    /// Degree 9 of a seven-note scale is its degree 2.
256    Permit,
257    /// It is no degree.
258    Forbid,
259}
260
261/// Whether a realization starting at the low terminus first works out a
262/// range when none is given.
263#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
264pub enum Fill {
265    /// Realize a terminus to terminus span either side of the reference.
266    IfUnbounded,
267    /// Stop at the terminus.
268    Never,
269}
270
271/// Whether a descending walk keeps the pitch it starts from.
272#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
273pub enum First {
274    /// Keep it.
275    Include,
276    /// Start below it.
277    Exclude,
278}
279
280/// The order a realization comes back in.
281#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
282pub enum Order {
283    /// Lowest first, as music21 gives a realization by default.
284    Ascending,
285    /// Highest first.
286    Descending,
287}
288
289/// Which node `next_pitch` starts from when the pitch it is given is on
290/// none: music21's `getNeighbor`.
291#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
292pub enum Neighbor {
293    /// The node above it.
294    Above,
295    /// The node below it.
296    Below,
297    /// None; there is no next pitch.
298    Never,
299}
300
301/// How a node is named when asking for it: by scale degree, or as itself.
302#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
303pub enum NodeName {
304    /// Every node of this degree, folded into the network if
305    /// [`Moduli::Permit`].
306    Degree(IntegerType),
307    /// That node.
308    Id(NodeId),
309}
310
311/// The range a realization keeps; either bound may be open.
312#[derive(Clone, Debug, Default)]
313pub struct PitchRange {
314    /// The lowest pitch kept.
315    pub min: Option<Pitch>,
316    /// The highest pitch kept.
317    pub max: Option<Pitch>,
318}
319
320impl PitchRange {
321    /// A range closed at both ends.
322    #[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    /// Whether `pitch` lies within the range, to within [`EPSILON`].
331    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/// A realization: its pitches, and the node each stands on.
343#[derive(Clone, Debug, Default)]
344pub struct Realized {
345    /// The pitches.
346    pub pitches: Vec<Pitch>,
347    /// The node each pitch stands on.
348    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/// Which of a list of pitches a realization holds and which it does not,
364/// each as an index into the list.
365#[derive(Clone, Debug, Default, Eq, PartialEq)]
366pub struct Matched {
367    /// The indices of the pitches found.
368    pub matched: Vec<usize>,
369    /// The indices of the pitches not found.
370    pub unmatched: Vec<usize>,
371}
372
373/// A tonic [`IntervalNetwork::find`] tried, and how many pitches it found.
374#[derive(Clone, Debug)]
375pub struct Found {
376    /// How many of the pitches the network holds on this tonic.
377    pub matches: usize,
378    /// The pitch on the low terminus.
379    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
390/// The pitch moved by whole semitones, as music21's `Pitch.transpose`
391/// moves it by a number.
392fn shifted(pitch: &Pitch, semitones: IntegerType) -> Result<Pitch> {
393    pitch.transpose(&Interval::from_semitones(semitones)?)
394}
395
396/// music21's `Pitch.__eq__`: the same note in the same octave.
397fn same_pitch(a: &Pitch, b: &Pitch) -> bool {
398    a.name_with_octave() == b.name_with_octave() && a.ps() == b.ps()
399}
400
401/// The pitch with an octave of its own: music21 sets `octaveIsImplicit`
402/// to false on a reference before walking from it.
403fn with_octave(pitch: &Pitch) -> Pitch {
404    let mut copy = pitch.clone();
405    copy.set_octave_is_implicit(false);
406    copy
407}
408
409/// The indices of the lowest and highest of `pitches`, the earlier of two
410/// equal lows and the later of two equal highs: music21's
411/// `filterPitchList`, which sorts on pitch space and then on index.
412#[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/// A scale or chord as a graph of intervals: music21's `IntervalNetwork`.
420#[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    /// Whether the pitches repeat at the octave.
427    pub octaves: Octaves,
428    /// Whether any node branches.
429    pub pathways: Pathways,
430    /// How pitches are respelled as the network is walked.
431    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
448// Building.
449impl IntervalNetwork {
450    /// A network of these steps walked both ways, from interval names.
451    ///
452    /// # Errors
453    ///
454    /// A name that is not an interval.
455    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    /// The nodes, in the order they were added.
466    #[must_use]
467    pub fn nodes(&self) -> &[Node] {
468        &self.nodes
469    }
470
471    /// The edges, each at the index that is its key.
472    #[must_use]
473    pub fn edges(&self) -> &[Edge] {
474        &self.edges
475    }
476
477    /// The next key a filling method gives an edge: music21's `edgeIdCount`.
478    #[must_use]
479    pub fn edge_id_count(&self) -> usize {
480        self.edge_id_count
481    }
482
483    /// The next number a filling method gives a node: music21's
484    /// `nodeIdCount`.
485    #[must_use]
486    pub fn node_id_count(&self) -> usize {
487        self.node_id_count
488    }
489
490    /// The node with this id.
491    #[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    /// Removes every node and edge: music21's `clear`.
502    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    /// Adds a node, or replaces the one with its id where it already stands.
510    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    /// The next node of a chain of `count` steps: a numbered one, or the
518    /// high terminus after the last step.
519    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    /// Replaces the network with a chain of `steps` walked both ways:
535    /// music21's `fillBiDirectedEdges`.
536    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    /// Replaces the network with one chain of steps walked up and another,
554    /// given as rising steps, walked down between the same termini:
555    /// music21's `fillDirectedEdges`.
556    ///
557    /// # Errors
558    ///
559    /// Chains of different lengths, whose degrees cannot be matched up.
560    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        // The way up, ending on a new high terminus.
570        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        // The way down, through nodes of its own to the same high terminus,
584        // each edge connected from its upper node.
585        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    /// Replaces the network with these nodes and edges: music21's
598    /// `fillArbitrary`. Edges are keyed by their place in the list; the
599    /// id counters are left at nought, as music21 leaves them.
600    ///
601    /// # Errors
602    ///
603    /// A connection to a node not in `nodes`.
604    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    /// Replaces the network with nodes and one-connection edges written
625    /// as tables.
626    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    /// Replaces the network with a melodic minor, which raises its sixth
644    /// and seventh going up and not coming down: music21's
645    /// `fillMelodicMinor`.
646    ///
647    /// # Errors
648    ///
649    /// None in practice; the intervals are fixed.
650    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
658// Degrees and nodes.
659impl IntervalNetwork {
660    /// The lowest degree: music21's `degreeMin`.
661    #[must_use]
662    pub fn degree_min(&self) -> Option<IntegerType> {
663        self.nodes.iter().map(|node| node.degree).min()
664    }
665
666    /// The highest degree: music21's `degreeMax`.
667    #[must_use]
668    pub fn degree_max(&self) -> Option<IntegerType> {
669        self.nodes.iter().map(|node| node.degree).max()
670    }
671
672    /// The highest degree but the high terminus's, which repeats the low
673    /// one: music21's `degreeMaxUnique`.
674    #[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    /// Each node's id and degree, in order: music21's
684    /// `getNodeDegreeDictionary`.
685    #[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    /// The degree of a node, the high terminus taking the low one's:
698    /// music21's `nodeIdToDegree`.
699    ///
700    /// # Errors
701    ///
702    /// A node not in the network.
703    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    /// The direction of every edge meeting a node: music21's
712    /// `nodeIdToEdgeDirections`.
713    ///
714    /// # Errors
715    ///
716    /// A node no edge meets.
717    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    /// The degree folded into the network's span, so that degree 8 of a
735    /// seven-note scale is 1: music21's `degreeModulus`.
736    ///
737    /// # Errors
738    ///
739    /// An empty network, or one whose nodes all share a degree.
740    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    /// The nodes a name stands for: music21's `nodeNameToNodes`.
756    ///
757    /// # Errors
758    ///
759    /// A node id the network does not hold.
760    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        // Past either end: the degree folded back into the network.
784        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    /// The node a walk named this way starts from: the low terminus for
793    /// none, else the first node the name stands for.
794    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    /// Every edge leaving a node walked `direction`, each as its index and
805    /// the node it reaches: music21's `getNext`. Leaving the high terminus
806    /// upward is leaving the low one, and the other way round.
807    ///
808    /// # Errors
809    ///
810    /// No edge leaving the node that way.
811    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    /// One of several ways on, chosen by the weight of the node each
832    /// reaches: music21's `weightedSelection`.
833    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    /// One step on from `from`, chosen by weight where it branches: the
846    /// interval walked and the node reached.
847    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
859// Spelling.
860impl IntervalNetwork {
861    /// The pitch moved by one step and respelled as the network's
862    /// simplification says: music21's
863    /// `transposePitchAndApplySimplification`. A network told to spell
864    /// exactly takes the most common spelling of a step given only in
865    /// semitones, which has no spelling of its own.
866    ///
867    /// # Errors
868    ///
869    /// A pitch moved past the octaves an integer counts.
870    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    /// How many semitones either side of a pitch a search realizes: an
879    /// octave, or the widest edge where that is wider. music21's
880    /// `_searchSpan`.
881    #[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    /// The name every terminus takes on a walk from `reference` standing on
892    /// `start`, where the network repeats at the octave and `start` is a
893    /// terminus.
894    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    /// The pitch spelled as `name` where it lands on a terminus and the two
902    /// are the same note an octave or more apart: music21's
903    /// `_spellTerminus`. Respelling accidentals along a walk can change its
904    /// letters, so a walk can reach the octave as C## where it set out from
905    /// D.
906    ///
907    /// # Errors
908    ///
909    /// A name that is not a pitch.
910    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
929// Realizing.
930impl IntervalNetwork {
931    /// The pitches from `reference` on `start` upward: music21's
932    /// `realizeAscending`. With no range the walk stops at the high
933    /// terminus; with `Fill::IfUnbounded` it first works one out.
934    ///
935    /// # Errors
936    ///
937    /// A start the network does not hold, or a walk that never reaches the
938    /// top of its range.
939    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    /// The pitches from `reference` on `start` downward: music21's
984    /// `realizeDescending`. With no lower bound the walk stops at the low
985    /// terminus.
986    ///
987    /// # Errors
988    ///
989    /// A start the network does not hold, or a walk that never descends.
990    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    /// A descending walk's pitches lowest first, or as walked.
1037    fn ordered(mut realized: Realized, order: Order) -> Realized {
1038        if order == Order::Ascending {
1039            realized.reverse();
1040        }
1041        realized
1042    }
1043
1044    /// The network realized from `reference` standing on `start`: music21's
1045    /// `realize`.
1046    ///
1047    /// A network that repeats at the octave is walked `direction` over the
1048    /// range, the whole span between the termini where there is none; one
1049    /// that does not is walked up and down from the reference whatever the
1050    /// direction.
1051    ///
1052    /// # Errors
1053    ///
1054    /// A start the network does not hold, or a walk that fails.
1055    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    /// [`Self::realize`] for a network that repeats at the octave.
1085    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    /// Two realizations taken a pitch from each in turn, each pitch once.
1123    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    /// The pitches of [`Self::realize`] walked upward, lowest first:
1141    /// music21's `realizePitch` with its defaults. A weighted network
1142    /// branches on a fixed draw.
1143    ///
1144    /// # Errors
1145    ///
1146    /// As [`Self::realize`].
1147    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    /// The steps between successive pitches of a realization from C4:
1165    /// music21's `realizeIntervals`.
1166    ///
1167    /// # Errors
1168    ///
1169    /// As [`Self::realize`].
1170    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    /// The pitches on the termini of a realization from `reference`:
1188    /// music21's `realizeTermini`.
1189    ///
1190    /// # Errors
1191    ///
1192    /// As [`Self::realize`], or a realization with no pitches.
1193    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    /// The lowest and highest pitches of one span from terminus to terminus
1213    /// either side of `reference`: music21's `realizeMinMax`.
1214    ///
1215    /// # Errors
1216    ///
1217    /// As [`Self::realize`].
1218    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        // An octave past each terminus, so that a span starting anywhere
1242        // fits.
1243        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    /// The pitches from the first terminus a realization reaches after its
1270    /// start to the next one, both included.
1271    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    /// The realized pitches on any of `degrees`, each folded into the
1293    /// network: music21's `realizePitchByDegree`.
1294    ///
1295    /// # Errors
1296    ///
1297    /// As [`Self::realize`].
1298    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/// How a descending realization is walked.
1324#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1325pub struct DescendingWalk {
1326    /// Whether the starting pitch is kept.
1327    pub first: First,
1328    /// Whether a range is worked out when none is given.
1329    pub fill: Fill,
1330    /// The order the pitches come back in.
1331    pub order: Order,
1332}
1333
1334impl DescendingWalk {
1335    /// A walk returned lowest first, as music21 returns one by default.
1336    #[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
1346// Finding pitches.
1347impl IntervalNetwork {
1348    /// The range a search around `pitch` realizes.
1349    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    /// Every node that sounds `target` on a realization from `reference`
1358    /// standing on `start`, in any octave, by degree: music21's
1359    /// `getRelativeNodeIds`.
1360    ///
1361    /// # Errors
1362    ///
1363    /// As [`Self::realize`].
1364    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    /// One node of [`Self::relative_node_ids`], chosen by weight where
1394    /// several sound the target: music21's `getRelativeNodeId`.
1395    ///
1396    /// # Errors
1397    ///
1398    /// As [`Self::realize`].
1399    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    /// One of `nodes` chosen by weight, or none of none.
1414    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    /// The degree of the node sounding `target`: music21's
1429    /// `getRelativeNodeDegree`.
1430    ///
1431    /// # Errors
1432    ///
1433    /// As [`Self::realize`].
1434    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    /// The nodes either side of `target` on a realization, where it lies
1448    /// below some realized pitch: music21's `getNeighborNodeIds`. The lower
1449    /// one is none where nothing realized lies below.
1450    ///
1451    /// # Errors
1452    ///
1453    /// As [`Self::realize`].
1454    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    /// The pitch of the node of degree `target` on a realization from
1477    /// `reference` standing on `name`: music21's `getPitchFromNodeDegree`.
1478    ///
1479    /// Where two nodes have the degree, the one walked `direction` is
1480    /// taken; a weighted network that may skip it is realized up to forty
1481    /// times.
1482    ///
1483    /// # Errors
1484    ///
1485    /// No node named `name` or `target`, or a realization that fails.
1486    #[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    /// The node a degree names for a walk `direction`: the only one, the
1529    /// low terminus of the two, or the first with an edge walked that way.
1530    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    /// Which of `targets` a realization from `reference` standing on `start`
1552    /// over their range holds: music21's `match`.
1553    ///
1554    /// # Errors
1555    ///
1556    /// No targets, or a realization that fails.
1557    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    /// The realized pitches none of `targets` matches: music21's
1585    /// `findMissing`.
1586    ///
1587    /// # Errors
1588    ///
1589    /// No targets, or a realization that fails.
1590    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    /// How many of `targets` the network holds standing on each of fifteen
1613    /// tonics, most first: music21's `find`. Ties keep the higher tonic
1614    /// first, and the later-tried of two enharmonic ones.
1615    ///
1616    /// # Errors
1617    ///
1618    /// No targets, or a realization that fails.
1619    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        // music21 sorts (count, pitch) pairs and reverses them; equal pitches
1631        // keep the order they were tried in before the reversal.
1632        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    /// The pitch `step_size` steps on from `origin` walking `direction` on a
1642    /// realization from `reference` standing on `name`: music21's
1643    /// `nextPitch`. An origin on no node steps from its `neighbor`.
1644    ///
1645    /// # Errors
1646    ///
1647    /// No node named `name`, or an origin with no node to step from.
1648    #[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    /// The node `next_pitch` steps from and its pitch nearest `origin`: at
1680    /// or below it when stepping up from a match or down from a lower
1681    /// neighbor, else at or above it.
1682    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        // The pitch of that node nearest the origin on the side wanted, the
1709        // first of equals.
1710        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    /// The node sounding `origin_ps`, chosen by weight among several, or
1736    /// its neighbor; and whether its pitch is sought at or below the
1737    /// origin.
1738    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    /// The network music21 realizes this scale through: its steps walked
1784    /// both ways, or, for the scales that come down by other steps, music21's
1785    /// own nodes and edges.
1786    ///
1787    /// # Errors
1788    ///
1789    /// None in practice; the steps are fixed.
1790    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
1811/// The semitone spans that divide the octave evenly, over which a cycle
1812/// of whole semitones repeats at the octave.
1813const OCTAVE_DIVISORS: [IntegerType; 6] = [1, 2, 3, 4, 6, 12];
1814
1815/// Semitones in an octave.
1816const OCTAVE_SEMITONES: FloatType = 12.0;
1817
1818/// The steps with the last one respelled so that they climb from C4 to
1819/// exactly C5: music21's `_closeOnTonic`. Steps that already do are
1820/// returned as they are, and so are steps spanning anything but an octave.
1821///
1822/// # Errors
1823///
1824/// A step that cannot move a pitch.
1825pub 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
1843/// music21's `AbstractCyclicalScale` network: the steps walked both ways.
1844/// Whole semitones adding up to a divisor of the octave repeat to fill it,
1845/// closed on the tonic, and the network then repeats at the octave.
1846///
1847/// # Errors
1848///
1849/// A step that cannot move a pitch.
1850pub 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
1875/// music21's `AbstractOctaveRepeatingScale` steps and network: the steps
1876/// completed to an octave by the interval left over, or respelled to
1877/// close on the tonic where they already span twelve semitones. Steps
1878/// past the octave make a network that does not repeat at it.
1879///
1880/// # Errors
1881///
1882/// No steps, or a step that cannot move a pitch.
1883pub 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
1905/// music21's `AbstractWeightedHexatonicBlues`: the minor pentatonic with
1906/// the blue note between its fourth and fifth degrees as a second way from
1907/// F to G, which a weighted walk takes or passes by.
1908///
1909/// # Errors
1910///
1911/// None in practice; the steps are fixed.
1912pub 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
1920/// A node of a network written as a table: its id and degree.
1921type TableNode = (NodeId, IntegerType);
1922
1923/// An edge of a network written as a table: its step, the nodes it
1924/// connects, and the way it is walked.
1925type 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
1937/// music21's `fillMelodicMinor`: A B C D E, then F# G# going up and G F
1938/// coming down.
1939const 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
1965/// music21's `AbstractRagAsawari`: C D F G A- going up, the natural minor
1966/// coming down.
1967const 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
1997/// music21's `AbstractRagMarwa`: going up it dips from B back to A before
1998/// the octave, and coming down it starts from the D- above the octave.
1999const 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
2033/// The blues network's nodes: C E- F F# G B- and the octave.
2034const 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
2044/// Every edge both ways; F goes on to G directly or through F#.
2045const 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}