Skip to main content

music21/graph/
axis.rs

1//! The ticks and labels of a graph's axes: the numbers behind music21's
2//! `graph.axis` classes.
3//!
4//! An axis of music21's reads its values from a stream and then says
5//! where its ticks go and what each says. The reading is the wheel's,
6//! over whatever stream it is given; what the ticks are, given what was
7//! read, is here.
8
9use crate::defaults::FloatType;
10use crate::dynamics::SHORT_NAMES;
11use crate::error::{Error, Result};
12use crate::pitch::Pitch;
13
14use super::py_range;
15use super::utilities::accidental_label_to_unicode;
16
17/// The barlines a measure tick is never left out at: music21's
18/// `bar.strongBarlineTypes`.
19pub const STRONG_BARLINES: [&str; 5] = ["heavy", "double", "final", "heavy-light", "heavy-heavy"];
20
21/// Whether a barline type is a strong one.
22///
23/// ```
24/// use music21::graph::axis::is_strong_barline;
25///
26/// assert!(is_strong_barline("final"));
27/// assert!(!is_strong_barline("regular"));
28/// ```
29pub fn is_strong_barline(kind: &str) -> bool {
30    STRONG_BARLINES.contains(&kind)
31}
32
33/// The lowest an axis's ticks start from when no minimum is set.
34const DEFAULT_MIN: FloatType = 0.0;
35
36/// The highest an axis's ticks reach when no maximum is set.
37const DEFAULT_MAX: FloatType = 10.0;
38
39/// Python's `int()` of a float: toward nought.
40fn truncate(value: FloatType) -> i64 {
41    value.trunc() as i64
42}
43
44/// About ten ticks at a power of ten apart, covering `min` to `max`:
45/// music21's `Axis.ticks`. A missing bound is 0 or 10.
46///
47/// ```
48/// use music21::graph::axis::numeric_ticks;
49///
50/// assert_eq!(numeric_ticks(Some(1.0), Some(9.0))?, (0..=10).collect::<Vec<_>>());
51/// assert_eq!(numeric_ticks(Some(7.0), Some(80.0))?[..3], [0, 10, 20]);
52/// assert_eq!(numeric_ticks(Some(712.0), Some(2213.0))?[0], 600);
53/// # Ok::<(), music21::Error>(())
54/// ```
55///
56/// # Errors
57///
58/// A maximum below the minimum, or a span under a tenth, which have no
59/// whole step to count with.
60pub fn numeric_ticks(min: Option<FloatType>, max: Option<FloatType>) -> Result<Vec<i64>> {
61    let min = min.unwrap_or(DEFAULT_MIN);
62    let max = max.unwrap_or(DEFAULT_MAX);
63    let difference = max - min;
64    if difference < 0.0 {
65        return Err(Error::Value("math domain error".to_string()));
66    }
67
68    // The power of ten just under the span, a tenth of it for spans of
69    // two such powers or less, so there are at least three steps.
70    let power = if difference == 0.0 {
71        0
72    } else {
73        truncate(difference.log10())
74    };
75    if power < 0 {
76        return Err(Error::Value(
77            "'float' object cannot be interpreted as an integer".to_string(),
78        ));
79    }
80    let mut step = 10_i64.pow(power as u32);
81    if step > 1 && difference / step as FloatType <= 2.0 {
82        step /= 10;
83    }
84
85    let mut start = (truncate(min / step as FloatType) - 1) * step;
86    if start < 0 && min >= 0.0 {
87        start = 0;
88    }
89    let stop = (truncate(max / step as FloatType) + 2) * step;
90    Ok(py_range(start, stop, step))
91}
92
93/// How a pitch axis writes octaves: music21's `showOctaves`, which is
94/// `False`, `'few'` or `True`.
95#[derive(Clone, Copy, Debug, PartialEq, Eq)]
96pub enum Octaves {
97    /// No octave numbers.
98    Hidden,
99    /// Only on the first label of each octave.
100    First,
101    /// On every label.
102    All,
103}
104
105/// How a pitch axis labels its ticks: music21's `PitchAxis` attributes.
106#[derive(Clone, Copy, Debug, PartialEq, Eq)]
107pub struct PitchLabels {
108    /// music21's `showOctaves`.
109    pub octaves: Octaves,
110    /// Whether a tick names every spelling found of it, or only the most
111    /// used: music21's `showEnharmonic`.
112    pub show_enharmonic: bool,
113    /// Whether a tick no pitch found is left unlabelled, rather than
114    /// named: music21's `blankLabelUnused`.
115    pub blank_label_unused: bool,
116    /// Whether a tick no pitch found is left out: music21's `hideUnused`.
117    pub hide_unused: bool,
118}
119
120/// A name with `A` sorted after `G`, as music21 sorts enharmonics.
121fn sort_name(name: &str) -> String {
122    match name.strip_prefix('A') {
123        Some(rest) => format!("H{rest}"),
124        None => name.to_string(),
125    }
126}
127
128/// The digits taken out of a label.
129fn without_digits(label: &str) -> String {
130    label.chars().filter(|c| !c.is_ascii_digit()).collect()
131}
132
133/// A pitch axis's ticks from `min` to `max`, one a whole number:
134/// music21's `PitchAxis._pitchTickHelper`.
135///
136/// `counts` is how often each name was found, in the order found;
137/// `value_of` says where a name stands on the axis, and `unused_label`
138/// names a tick no name stands at, where one is wanted.
139///
140/// ```
141/// use music21::graph::axis::{Octaves, PitchLabels, pitch_ticks};
142///
143/// let labels = PitchLabels {
144///     octaves: Octaves::Hidden,
145///     show_enharmonic: true,
146///     blank_label_unused: true,
147///     hide_unused: false,
148/// };
149/// let counts = [("G#".to_string(), 1), ("A-".to_string(), 2)];
150/// let ticks = pitch_ticks(labels, 7, 8, &counts, |_| Ok(8.0), |_| Ok(String::new()))?;
151/// assert_eq!(ticks, vec![(7, String::new()), (8, "G\u{266f}/A\u{266d}".to_string())]);
152/// # Ok::<(), music21::Error>(())
153/// ```
154///
155/// # Errors
156///
157/// What `value_of` or `unused_label` returns.
158pub fn pitch_ticks(
159    labels: PitchLabels,
160    min: i64,
161    max: i64,
162    counts: &[(String, usize)],
163    value_of: impl Fn(&str) -> Result<FloatType>,
164    unused_label: impl Fn(i64) -> Result<String>,
165) -> Result<Vec<(i64, String)>> {
166    let mut values = Vec::with_capacity(counts.len());
167    for (name, _) in counts {
168        values.push(value_of(name)?);
169    }
170
171    let mut ticks = Vec::new();
172    let mut octaves_seen: Vec<char> = Vec::new();
173    for tick in min..=max {
174        // The names found at this tick, ordered as music21 orders them.
175        let mut weights: Vec<(usize, &str)> = counts
176            .iter()
177            .zip(&values)
178            .filter(|(_, value)| **value == tick as FloatType)
179            .map(|((name, count), _)| (*count, name.as_str()))
180            .collect();
181        if labels.show_enharmonic {
182            weights.sort_by_key(|(count, name)| (*count as i64, sort_name(name)));
183        } else {
184            weights.sort_by_key(|(count, name)| (-(*count as i64), sort_name(name)));
185        }
186
187        let mut label = if weights.is_empty() {
188            if labels.hide_unused {
189                continue;
190            }
191            if labels.blank_label_unused {
192                String::new()
193            } else {
194                unused_label(tick)?
195            }
196        } else if !labels.show_enharmonic {
197            weights[0].1.to_string()
198        } else {
199            let names: Vec<String> = weights
200                .iter()
201                .map(|(_, name)| accidental_label_to_unicode(name))
202                .collect();
203            names.join("/")
204        };
205
206        // Octave numbers as asked.
207        match labels.octaves {
208            Octaves::Hidden => label = without_digits(&label),
209            Octaves::First => {
210                if let Some(digit) = label.chars().find(char::is_ascii_digit) {
211                    if octaves_seen.contains(&digit) {
212                        label = without_digits(&label);
213                    } else {
214                        octaves_seen.push(digit);
215                    }
216                }
217            }
218            Octaves::All => {}
219        }
220        ticks.push((tick, accidental_label_to_unicode(&label)));
221    }
222    Ok(ticks)
223}
224
225/// A tick at each octave of `start` from `min` to `max`: music21's
226/// `PitchSpaceOctaveAxis.ticks`.
227///
228/// ```
229/// use music21::graph::axis::octave_ticks;
230///
231/// let ticks = octave_ticks("A2", 36.0, 100.0)?;
232/// assert_eq!(ticks[0], (45, "A2".to_string()));
233/// assert_eq!(ticks.len(), 5);
234/// # Ok::<(), music21::Error>(())
235/// ```
236///
237/// # Errors
238///
239/// A start that names no pitch.
240pub fn octave_ticks(start: &str, min: FloatType, max: FloatType) -> Result<Vec<(i64, String)>> {
241    let mut pitch = Pitch::from_name(start)?;
242    let mut ticks = Vec::new();
243    while pitch.ps() <= max {
244        if pitch.ps() >= min {
245            let label = accidental_label_to_unicode(&pitch.name_with_octave());
246            ticks.push((truncate(pitch.ps()), label));
247        }
248        let Some(octave) = pitch.octave() else {
249            return Err(Error::Value(format!("{start} names no octave")));
250        };
251        pitch.set_octave(Some(octave + 1));
252    }
253    Ok(ticks)
254}
255
256/// Ticks every `step` from `min` to `max`, rounded outward: music21's
257/// `OffsetAxis.ticks` where there are no measures.
258///
259/// ```
260/// use music21::graph::axis::offset_ticks;
261///
262/// assert_eq!(offset_ticks(0.0, 20.0, 10), vec![0, 10, 20]);
263/// assert_eq!(offset_ticks(0.5, 4.5, 2), vec![0, 2, 4]);
264/// ```
265pub fn offset_ticks(min: FloatType, max: FloatType, step: i64) -> Vec<i64> {
266    py_range(min.floor() as i64, max.ceil() as i64 + 1, step)
267}
268
269/// A measure an offset axis can tick: where it starts, its number, and
270/// whether it ends in a strong barline.
271#[derive(Clone, Debug, PartialEq)]
272pub struct MeasureMark {
273    /// Where the measure starts.
274    pub offset: FloatType,
275    /// Its number as it is written.
276    pub number: String,
277    /// Whether its right barline is heavy, double or final.
278    pub strong: bool,
279}
280
281/// Which of the measures an offset axis ticks: music21's
282/// `minMaxMeasureOnly`.
283#[derive(Clone, Copy, Debug, PartialEq, Eq)]
284pub enum MeasureSpan {
285    /// The first and the last only.
286    Ends,
287    /// The first, the last, every strong barline, and others evenly, to
288    /// about this many in all: music21's `mostMeasureTicksToShow`.
289    Spaced(i64),
290}
291
292/// The measure ticks of an offset axis, of the measures starting from
293/// `min` to `max`: music21's `OffsetAxis._measureTicks`.
294///
295/// ```
296/// use music21::graph::axis::{MeasureMark, MeasureSpan, measure_ticks};
297///
298/// let marks: Vec<MeasureMark> = (0..9)
299///     .map(|n| MeasureMark { offset: f64::from(n) * 4.0, number: n.to_string(), strong: false })
300///     .collect();
301/// let ticks = measure_ticks(&marks, 0.0, 32.0, MeasureSpan::Ends)?;
302/// assert_eq!(ticks, vec![(0.0, "0".to_string()), (32.0, "8".to_string())]);
303/// # Ok::<(), music21::Error>(())
304/// ```
305///
306/// # Errors
307///
308/// No measure starting in the range, or a span that leaves no room for
309/// any more ticks.
310pub fn measure_ticks(
311    marks: &[MeasureMark],
312    min: FloatType,
313    max: FloatType,
314    span: MeasureSpan,
315) -> Result<Vec<(FloatType, String)>> {
316    let used: Vec<&MeasureMark> = marks
317        .iter()
318        .filter(|mark| min <= mark.offset && mark.offset <= max)
319        .collect();
320    if used.is_empty() {
321        return Err(Error::Value("list index out of range".to_string()));
322    }
323    let tick_of = |index: usize| (used[index].offset, used[index].number.clone());
324
325    let most = match span {
326        MeasureSpan::Ends => {
327            let mut ticks = vec![tick_of(0)];
328            let last = tick_of(used.len() - 1);
329            if !ticks.contains(&last) {
330                ticks.push(last);
331            }
332            return Ok(ticks);
333        }
334        MeasureSpan::Spaced(most) => most,
335    };
336
337    // The first, the last, and every strong barline between.
338    let mut chosen: Vec<usize> = Vec::new();
339    let choose = |index: usize, chosen: &mut Vec<usize>| {
340        if !chosen.contains(&index) {
341            chosen.push(index);
342        }
343    };
344    choose(0, &mut chosen);
345    choose(used.len() - 1, &mut chosen);
346    for (index, mark) in used.iter().enumerate().take(used.len() - 1).skip(1) {
347        if mark.strong {
348            choose(index, &mut chosen);
349        }
350    }
351
352    // Then evenly, up to about `most`.
353    let more = (most - chosen.len() as i64 + 1).min(used.len() as i64);
354    if more == 0 {
355        return Err(Error::Value(
356            "integer division or modulo by zero".to_string(),
357        ));
358    }
359    let step = ((used.len() as FloatType / more as FloatType).floor() as i64).max(1) as usize;
360    let mut index = step;
361    while index < used.len() - 1 {
362        choose(index, &mut chosen);
363        index += step;
364    }
365
366    let mut ticks: Vec<(FloatType, String)> = chosen.into_iter().map(tick_of).collect();
367    ticks.sort_by(|a, b| a.0.total_cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
368    Ok(ticks)
369}
370
371/// A tick for each dynamic from `min` to `max`, by its index in
372/// `dynamics.shortNames`, written in TeX italics: music21's
373/// `DynamicsAxis.ticks`.
374///
375/// ```
376/// use music21::graph::axis::dynamics_ticks;
377///
378/// let ticks = dynamics_ticks(3, 4)?;
379/// assert_eq!(ticks, vec![(3, "$ppp$".to_string()), (4, "$pp$".to_string())]);
380/// # Ok::<(), music21::Error>(())
381/// ```
382///
383/// # Errors
384///
385/// An index past the last dynamic.
386pub fn dynamics_ticks(min: i64, max: i64) -> Result<Vec<(i64, String)>> {
387    let mut ticks = Vec::new();
388    for index in min..=max {
389        let at = if index < 0 {
390            index + SHORT_NAMES.len() as i64
391        } else {
392            index
393        };
394        let Some(name) = usize::try_from(at).ok().and_then(|at| SHORT_NAMES.get(at)) else {
395            return Err(Error::Value("list index out of range".to_string()));
396        };
397        ticks.push((index, format!("${name}$")));
398    }
399    Ok(ticks)
400}
401
402/// The index of the last dynamic: the most a dynamics axis reaches.
403pub fn dynamics_max() -> i64 {
404    SHORT_NAMES.len() as i64 - 1
405}
406
407/// Whether a quarter-length axis is scaled: music21's `useLogScale`.
408#[derive(Clone, Copy, Debug, PartialEq, Eq)]
409pub enum Scale {
410    /// As the lengths are.
411    Linear,
412    /// By their logarithm, base two.
413    Log2,
414}
415
416/// Where a quarter length stands on a quarter-length axis: music21's
417/// `dataFromQL`. A grace note, of no length, stands at `grace`.
418///
419/// ```
420/// use music21::graph::axis::{Scale, quarter_length_value};
421///
422/// assert_eq!(quarter_length_value(0.5, Scale::Log2, 0.0625)?, -1.0);
423/// assert_eq!(quarter_length_value(0.0, Scale::Log2, 0.0625)?, -4.0);
424/// assert_eq!(quarter_length_value(0.0, Scale::Linear, 0.0625)?, 0.0625);
425/// # Ok::<(), music21::Error>(())
426/// ```
427///
428/// # Errors
429///
430/// A negative length on a logarithmic axis.
431pub fn quarter_length_value(ql: FloatType, scale: Scale, grace: FloatType) -> Result<FloatType> {
432    match scale {
433        Scale::Log2 => {
434            let length = if ql == 0.0 { grace } else { ql };
435            if length < 0.0 {
436                return Err(Error::Graph(format!(
437                    "cannot take log of x value: {length}"
438                )));
439            }
440            Ok(length.log2())
441        }
442        Scale::Linear if ql > 0.0 => Ok(ql),
443        Scale::Linear => Ok(grace),
444    }
445}
446
447/// What a quarter-length axis's label gains for its scale: music21's
448/// `labelLogTag`, given the base written, or none for a linear axis.
449///
450/// ```
451/// use music21::graph::axis::log_label_tag;
452///
453/// assert_eq!(log_label_tag(Some(2)), " ($log_2$)");
454/// assert_eq!(log_label_tag(None), "");
455/// ```
456pub fn log_label_tag(base: Option<i64>) -> String {
457    match base {
458        Some(base) => format!(" ($log_{base}$)"),
459        None => String::new(),
460    }
461}
462
463/// Whether a note carries a tie on to the next.
464#[derive(Clone, Copy, Debug, PartialEq, Eq)]
465pub enum Tied {
466    /// It does.
467    Onward,
468    /// It does not.
469    Not,
470}
471
472/// Where a note's bar starts and how long it is drawn, a little short of
473/// its length so untied notes stand apart: music21's
474/// `OffsetEndAxis.extractOneElement`.
475///
476/// ```
477/// use music21::graph::axis::{Tied, offset_end};
478///
479/// assert_eq!(offset_end(1.0, 0.5, 0.0625, Tied::Not), (1.0, 0.4375));
480/// assert_eq!(offset_end(1.0, 0.5, 0.0625, Tied::Onward), (1.0, 0.5));
481/// ```
482pub fn offset_end(
483    offset: FloatType,
484    length: FloatType,
485    spacing: FloatType,
486    tied: Tied,
487) -> (FloatType, FloatType) {
488    if length < spacing {
489        return (offset, spacing);
490    }
491    if length > spacing * 2.0 && tied == Tied::Not {
492        return (offset, length - spacing);
493    }
494    (offset, length)
495}
496
497#[cfg(test)]
498mod tests {
499    use super::*;
500
501    #[test]
502    fn measure_ticks_space_out_and_keep_strong_bars() {
503        let offsets = [0.0, 1.0, 5.0, 9.0, 13.0, 17.0, 21.0, 25.0, 29.0];
504        let mut marks: Vec<MeasureMark> = offsets
505            .iter()
506            .enumerate()
507            .map(|(number, offset)| MeasureMark {
508                offset: *offset,
509                number: number.to_string(),
510                strong: false,
511            })
512            .collect();
513        let numbers = |ticks: Vec<(FloatType, String)>| -> Vec<String> {
514            ticks.into_iter().map(|(_, label)| label).collect()
515        };
516        let ticks = measure_ticks(&marks, 0.0, 33.0, MeasureSpan::Spaced(4)).unwrap();
517        assert_eq!(numbers(ticks), ["0", "3", "6", "8"]);
518        marks[5].strong = true;
519        let ticks = measure_ticks(&marks, 0.0, 33.0, MeasureSpan::Spaced(4)).unwrap();
520        assert_eq!(numbers(ticks), ["0", "4", "5", "8"]);
521        let ticks = measure_ticks(&marks, 8.0, 12.0, MeasureSpan::Spaced(20)).unwrap();
522        assert_eq!(numbers(ticks), ["3"]);
523    }
524
525    #[test]
526    fn pitch_ticks_write_octaves_once() {
527        let labels = PitchLabels {
528            octaves: Octaves::First,
529            show_enharmonic: true,
530            blank_label_unused: false,
531            hide_unused: false,
532        };
533        let names = ["G#0", "A0", "B-0", "B0", "C1"];
534        let ticks = pitch_ticks(
535            labels,
536            20,
537            24,
538            &[],
539            |_| Ok(0.0),
540            |tick| Ok(names[(tick - 20) as usize].to_string()),
541        )
542        .unwrap();
543        let written: Vec<&str> = ticks.iter().map(|(_, label)| label.as_str()).collect();
544        assert_eq!(written, ["G\u{266f}0", "A", "B\u{266d}", "B", "C1"]);
545    }
546}