Skip to main content

music21/graph/
find.rs

1//! Which plot a format and some quantities ask for: music21's
2//! `graph.findPlot`.
3//!
4//! The plots and axes chosen among are described by the caller, each by
5//! its graph type and the quantities its axes plot, so that a plot class
6//! of the caller's own is chosen as music21 would choose it.
7
8use crate::error::{Error, Result};
9
10/// Each format and the other names a user may give it, the format first.
11pub const FORMAT_SYNONYMS: [&[&str]; 7] = [
12    &["horizontalbar", "bar", "horizontal", "pianoroll", "piano"],
13    &["histogram", "histo", "count"],
14    &["scatter", "point"],
15    &["scatterweighted", "weightedscatter", "weighted"],
16    &["3dbars", "3d"],
17    &["colorgrid", "grid", "window", "windowed"],
18    &["horizontalbarweighted", "barweighted", "weightedbar"],
19];
20
21/// Names that ask for one plot class outright, and the class each names.
22pub const PLOT_SHORTCUTS: [(&str, &str); 5] = [
23    ("ambitus", "WindowedAmbitus"),
24    ("dolan", "Dolan"),
25    ("instruments", "Dolan"),
26    ("key", "WindowedKey"),
27    ("pianoroll", "HorizontalBarPitchSpaceOffset"),
28];
29
30/// The format asked for when nothing is.
31const DEFAULT_FORMAT: &str = "pianoroll";
32
33/// The axis letters, in order.
34const AXIS_LETTERS: [char; 3] = ['x', 'y', 'z'];
35
36/// A format as its first name: music21's `userFormatsToFormat`. An unknown
37/// format is lowercased with its spaces taken out.
38///
39/// ```
40/// use music21::graph::find::user_format;
41///
42/// assert_eq!(user_format("Weighted Scatter"), "scatterweighted");
43/// assert_eq!(user_format("3D"), "3dbars");
44/// assert_eq!(user_format("4D super chart"), "4dsuperchart");
45/// ```
46pub fn user_format(format: &str) -> String {
47    let format = format.to_lowercase().replace(' ', "");
48    for names in FORMAT_SYNONYMS {
49        if names.contains(&format.as_str()) {
50            return names[0].to_string();
51        }
52    }
53    format
54}
55
56/// A plot class chosen among: its graph type and the quantities each of
57/// its axes plots, by axis letter.
58#[derive(Clone, Debug, PartialEq)]
59pub struct PlotCandidate {
60    /// music21's `graphType`.
61    pub graph_type: String,
62    /// Each axis's letter and its class's `quantities`.
63    pub axes: Vec<(char, Vec<String>)>,
64}
65
66impl PlotCandidate {
67    fn axis(&self, letter: char) -> Option<&[String]> {
68        self.axes
69            .iter()
70            .find(|(found, _)| *found == letter)
71            .map(|(_, quantities)| quantities.as_slice())
72    }
73}
74
75/// Whether a value names one of an axis's quantities, ignoring case:
76/// music21's `axisMatchesValue`.
77///
78/// ```
79/// use music21::graph::find::axis_matches;
80///
81/// let quantities = ["count".to_string(), "counting".to_string()];
82/// assert!(axis_matches(&quantities, "Counting"));
83/// assert!(!axis_matches(&quantities, "offset"));
84/// ```
85pub fn axis_matches(quantities: &[String], value: &str) -> bool {
86    let value = value.to_lowercase();
87    quantities
88        .iter()
89        .any(|quantity| quantity.to_lowercase() == value)
90}
91
92/// The plots of a format among `plots`, by index: music21's
93/// `getPlotClassesFromFormat`.
94pub fn plots_of_format(format: &str, plots: &[PlotCandidate], among: &[usize]) -> Vec<usize> {
95    let format = user_format(format).to_lowercase();
96    among
97        .iter()
98        .copied()
99        .filter(|index| plots[*index].graph_type.to_lowercase() == format)
100        .collect()
101}
102
103/// What `plots_to_make` chose.
104#[derive(Clone, Debug, PartialEq)]
105pub enum PlotChoice {
106    /// Plot classes that plot what was asked, by index.
107    Plots(Vec<usize>),
108    /// The plot class nearest what was asked, and the axis class, by index
109    /// in the axes given, to put on each of its axes.
110    WithAxes {
111        /// The plot class.
112        plot: usize,
113        /// Each axis letter and its axis class.
114        axes: Vec<(char, usize)>,
115    },
116}
117
118/// The plots to make for a format and up to three quantities: music21's
119/// `getPlotsToMake`.
120///
121/// `plots` is every plot class, `shortcut` the index among them of the
122/// class a shortcut format names, where it is one, and `axes` the
123/// quantities of every axis class. Where no plot plots the quantities
124/// asked, the nearest plot is chosen with an axis class for each.
125///
126/// ```
127/// use music21::graph::find::{PlotCandidate, PlotChoice, plots_to_make};
128///
129/// let quantities = |names: &[&str]| names.iter().map(|n| n.to_string()).collect::<Vec<_>>();
130/// let plots = [PlotCandidate {
131///     graph_type: "histogram".to_string(),
132///     axes: vec![('x', quantities(&["pitchSpace", "pitch"])), ('y', quantities(&["count"]))],
133/// }];
134/// let choice = plots_to_make(Some("pitch"), [None, None, None], None, &plots, &[])?;
135/// assert_eq!(choice, PlotChoice::Plots(vec![0]));
136/// # Ok::<(), music21::Error>(())
137/// ```
138///
139/// # Errors
140///
141/// Quantities given with no format, or no plot classes to choose from.
142pub fn plots_to_make(
143    format: Option<&str>,
144    values: [Option<&str>; 3],
145    shortcut: Option<usize>,
146    plots: &[PlotCandidate],
147    axes: &[Vec<String>],
148) -> Result<PlotChoice> {
149    let mut format = format.map(str::to_string);
150    let mut values = values.map(|value| value.map(str::to_string));
151    if format.is_none() && values.iter().all(Option::is_none) {
152        format = Some(DEFAULT_FORMAT.to_string());
153    }
154    let all: Vec<usize> = (0..plots.len()).collect();
155
156    // The classes the format names; where none, the format is taken as
157    // the first quantity and every class is a candidate.
158    let mut classes = match (&format, shortcut) {
159        (Some(_), Some(index)) => vec![index],
160        (Some(named), None) => plots_of_format(named, plots, &all),
161        (None, _) => {
162            return Err(Error::Value(
163                "'NoneType' object has no attribute 'lower'".to_string(),
164            ));
165        }
166    };
167    if classes.is_empty() {
168        values = [format.take(), values[0].take(), values[1].take()];
169        classes = all;
170    }
171    let format_given = format.is_some();
172    let counted = values.iter().filter(|value| value.is_some()).count();
173    let best = |among: Vec<usize>| -> Vec<usize> {
174        let format = match counted {
175            3 => "scatterweighted",
176            2 => "scatter",
177            1 => "histogram",
178            _ => "",
179        };
180        let inner = plots_of_format(format, plots, &among);
181        if inner.is_empty() { among } else { inner }
182    };
183    let finish = |kept: Vec<usize>| -> Option<PlotChoice> {
184        if kept.is_empty() {
185            return None;
186        }
187        if format_given || kept.len() == 1 {
188            return Some(PlotChoice::Plots(kept));
189        }
190        Some(PlotChoice::Plots(best(kept)))
191    };
192
193    // Classes whose axis of each letter plots that letter's quantity.
194    let kept: Vec<usize> = classes
195        .iter()
196        .copied()
197        .filter(|index| {
198            AXIS_LETTERS.iter().zip(&values).all(|(letter, value)| {
199                let Some(value) = value else {
200                    return true;
201                };
202                plots[*index]
203                    .axis(*letter)
204                    .is_some_and(|quantities| axis_matches(quantities, value))
205            })
206        })
207        .collect();
208    if let Some(choice) = finish(kept) {
209        return Ok(choice);
210    }
211
212    // Then classes with some axis plotting each quantity.
213    let kept: Vec<usize> = classes
214        .iter()
215        .copied()
216        .filter(|index| {
217            values.iter().flatten().all(|value| {
218                plots[*index]
219                    .axes
220                    .iter()
221                    .any(|(_, quantities)| axis_matches(quantities, value))
222            })
223        })
224        .collect();
225    if let Some(choice) = finish(kept) {
226        return Ok(choice);
227    }
228
229    // Else the nearest class, with an axis class for each quantity.
230    let mut chosen_axes = Vec::new();
231    for (letter, value) in AXIS_LETTERS.iter().zip(&values) {
232        let Some(value) = value else {
233            continue;
234        };
235        if let Some(axis) = axes
236            .iter()
237            .position(|quantities| axis_matches(quantities, value))
238        {
239            chosen_axes.push((*letter, axis));
240        }
241    }
242    let Some(first) = classes.first().copied() else {
243        return Err(Error::Value("list index out of range".to_string()));
244    };
245    let plot = if classes.len() == 1 {
246        first
247    } else {
248        best(classes).first().copied().unwrap_or(first)
249    };
250    Ok(PlotChoice::WithAxes {
251        plot,
252        axes: chosen_axes,
253    })
254}
255
256#[cfg(test)]
257mod tests {
258    use super::*;
259
260    fn quantities(names: &[&str]) -> Vec<String> {
261        names.iter().map(|name| name.to_string()).collect()
262    }
263
264    fn scatter(y: &[&str]) -> PlotCandidate {
265        PlotCandidate {
266            graph_type: "scatter".to_string(),
267            axes: vec![('x', quantities(&["offset"])), ('y', quantities(y))],
268        }
269    }
270
271    #[test]
272    fn quantities_in_the_wrong_order_still_find_a_plot() {
273        let plots = [scatter(&["pitchClass", "pc"]), scatter(&["dynamic"])];
274        let choice = plots_to_make(
275            Some("scatter"),
276            [Some("pc"), Some("offset"), None],
277            None,
278            &plots,
279            &[],
280        )
281        .unwrap();
282        assert_eq!(choice, PlotChoice::Plots(vec![0]));
283    }
284
285    #[test]
286    fn an_unknown_pairing_gets_axes_of_its_own() {
287        let plots = [scatter(&["pitchClass"])];
288        let axes = [quantities(&["offset"]), quantities(&["count"])];
289        let choice = plots_to_make(
290            Some("scatter"),
291            [Some("offset"), Some("count"), None],
292            None,
293            &plots,
294            &axes,
295        )
296        .unwrap();
297        assert_eq!(
298            choice,
299            PlotChoice::WithAxes {
300                plot: 0,
301                axes: vec![('x', 0), ('y', 1)]
302            }
303        );
304    }
305}