1use crate::error::{Error, Result};
9
10pub 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
21pub const PLOT_SHORTCUTS: [(&str, &str); 5] = [
23 ("ambitus", "WindowedAmbitus"),
24 ("dolan", "Dolan"),
25 ("instruments", "Dolan"),
26 ("key", "WindowedKey"),
27 ("pianoroll", "HorizontalBarPitchSpaceOffset"),
28];
29
30const DEFAULT_FORMAT: &str = "pianoroll";
32
33const AXIS_LETTERS: [char; 3] = ['x', 'y', 'z'];
35
36pub 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#[derive(Clone, Debug, PartialEq)]
59pub struct PlotCandidate {
60 pub graph_type: String,
62 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
75pub 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
92pub 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#[derive(Clone, Debug, PartialEq)]
105pub enum PlotChoice {
106 Plots(Vec<usize>),
108 WithAxes {
111 plot: usize,
113 axes: Vec<(char, usize)>,
115 },
116}
117
118pub 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 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 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 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 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}