Skip to main content

music21/graph/
primitives.rs

1//! The layout numbers music21's graph primitives draw with: where the
2//! ticks of a count go, how big a weighted point is, and where a bar of a
3//! horizontal bar graph sits in its channel.
4
5use crate::defaults::FloatType;
6
7use super::py_range;
8
9/// The step a count's ticks take at the least.
10const MIN_COUNT_STEP: i64 = 2;
11
12/// The bar-graph ticks run about a tenth of the span apart.
13const BAR_TICK_DIVISIONS: FloatType = 10.0;
14
15/// How far right of its point a weighted point's count is written, in
16/// units of the axis.
17const LABEL_SHIFT_X: FloatType = 0.05;
18
19/// How far above its point a weighted point's count is written.
20const LABEL_SHIFT_Y: FloatType = 0.10;
21
22/// Ticks for a count from nought to the most of `data`, about `steps`
23/// apart: music21's `Graph.setIntegerTicksFromData`.
24///
25/// ```
26/// use music21::graph::primitives::integer_ticks;
27///
28/// assert_eq!(integer_ticks(&[10.0, 5.0, 3.0, 8.0, 20.0, 11.0], 4), vec![0, 5, 10, 15, 20]);
29/// ```
30pub fn integer_ticks(data: &[FloatType], steps: i64) -> Vec<i64> {
31    let most = data
32        .iter()
33        .copied()
34        .fold(FloatType::NEG_INFINITY, FloatType::max) as i64;
35    let mut step = (most as FloatType / steps as FloatType).round_ties_even() as i64;
36    if step <= 1 {
37        step = MIN_COUNT_STEP;
38    }
39    py_range(0, most + 1, step)
40}
41
42/// The x ticks a horizontal bar graph makes for itself when it is given
43/// none: music21's `GraphHorizontalBar.renderSubplot`.
44///
45/// ```
46/// use music21::graph::primitives::bar_x_ticks;
47///
48/// assert_eq!(bar_x_ticks(0.0, 20.0), vec![0, 2, 4, 6, 8, 10, 12, 14, 16, 18]);
49/// ```
50pub fn bar_x_ticks(min: FloatType, max: FloatType) -> Vec<i64> {
51    let span = max - min;
52    let mut step = (min + (span / BAR_TICK_DIVISIONS).round_ties_even()).trunc() as i64;
53    if step == 0 {
54        step = 1;
55    }
56    py_range(
57        min.floor() as i64,
58        max.ceil().round_ties_even() as i64,
59        step,
60    )
61}
62
63/// A weighted point as drawn: an ellipse, and where its count is written
64/// where it is written at all.
65#[derive(Clone, Copy, Debug, PartialEq)]
66pub struct WeightedPoint {
67    /// The ellipse's width, in units of the x axis.
68    pub width: FloatType,
69    /// Its height, in units of the y axis.
70    pub height: FloatType,
71    /// Where the count is written, for a count over one.
72    pub label_at: Option<(FloatType, FloatType)>,
73}
74
75/// Each point of a weighted scatter graph, sized by its count between the
76/// two diameters and stretched so it draws round on unequal axes: music21's
77/// `GraphScatterWeighted.renderSubplot`.
78///
79/// ```
80/// use music21::graph::primitives::weighted_points;
81///
82/// let drawn = weighted_points(&[(0.0, 0.0, 1.0), (10.0, 10.0, 3.0)], 0.25, 1.25);
83/// assert_eq!(drawn[0].width, 0.25);
84/// assert_eq!(drawn[1].width, 1.25);
85/// assert!(drawn[0].label_at.is_none());
86/// ```
87pub fn weighted_points(
88    points: &[(FloatType, FloatType, FloatType)],
89    min_diameter: FloatType,
90    max_diameter: FloatType,
91) -> Vec<WeightedPoint> {
92    let span = |values: Vec<FloatType>| -> (FloatType, FloatType) {
93        let low = values
94            .iter()
95            .copied()
96            .fold(FloatType::INFINITY, FloatType::min);
97        let high = values
98            .iter()
99            .copied()
100            .fold(FloatType::NEG_INFINITY, FloatType::max);
101        (low, high - low)
102    };
103    let (_, x_range) = span(points.iter().map(|p| p.0).collect());
104    let (_, y_range) = span(points.iter().map(|p| p.1).collect());
105    let (z_min, z_range) = span(points.iter().map(|p| p.2).collect());
106
107    // A circle on axes of unequal span is drawn narrower along the longer.
108    let mut x_distort = 1.0;
109    let mut y_distort = 1.0;
110    if x_range > y_range {
111        y_distort = y_range / x_range;
112    } else if y_range > x_range {
113        x_distort = x_range / y_range;
114    }
115
116    let range_diameter = max_diameter - min_diameter;
117    points
118        .iter()
119        .map(|&(x, y, z)| {
120            let diameter = if z == 0.0 {
121                0.0
122            } else if z_range != 0.0 {
123                min_diameter + range_diameter * (z - z_min) / z_range
124            } else {
125                min_diameter + range_diameter * 0.5
126            };
127            let width = diameter * x_distort;
128            let height = diameter * y_distort;
129            let label = (
130                x + (width * 0.5 + LABEL_SHIFT_X * x_distort),
131                y + LABEL_SHIFT_Y,
132            );
133            let label_at = (z > 1.0).then_some(label);
134            WeightedPoint {
135                width,
136                height,
137                label_at,
138            }
139        })
140        .collect()
141}
142
143/// A weighted horizontal bar's channel and how it sits in it.
144#[derive(Clone, Copy, Debug, PartialEq)]
145pub struct Channel {
146    /// Where the channel starts.
147    pub start: FloatType,
148    /// The space above and below its bars.
149    pub margin: FloatType,
150    /// The height of a full bar.
151    pub bar_height: FloatType,
152}
153
154/// Where a bar of a weighted horizontal bar graph starts and how tall it
155/// is, `scale` of a full bar, shifted up or down by `shift` from -1 to 1:
156/// music21's `GraphHorizontalBarWeighted.renderSubplot`.
157///
158/// ```
159/// use music21::graph::primitives::{Channel, weighted_bar};
160///
161/// let channel = Channel { start: 0.0, margin: 0.25, bar_height: 7.5 };
162/// assert_eq!(weighted_bar(channel, 1.0, 0.0), (0.25, 7.5));
163/// assert_eq!(weighted_bar(channel, 0.5, 0.0), (2.125, 3.75));
164/// ```
165pub fn weighted_bar(
166    channel: Channel,
167    scale: FloatType,
168    shift: FloatType,
169) -> (FloatType, FloatType) {
170    let height = channel.bar_height * scale;
171    let centring = (channel.bar_height - height) * 0.5;
172    let shift_unit = channel.bar_height * (1.0 - scale) * 0.5;
173    let start = channel.start + channel.margin + centring + shift_unit * shift;
174    (start, height)
175}