1#[derive(Debug, Clone)]
12pub struct PlotSeries<'a> {
13 pub label: &'a str,
14 pub x: &'a [f64],
15 pub y: &'a [f64],
16}
17
18#[derive(Debug, Clone)]
20pub struct PlotOptions {
21 pub width: usize,
23 pub height: usize,
25 pub title: Option<String>,
26 pub x_label: Option<String>,
27 pub y_label: Option<String>,
28 pub color: bool,
30 pub scatter: bool,
32 pub x_range: Option<(f64, f64)>,
34 pub y_range: Option<(f64, f64)>,
36}
37
38impl Default for PlotOptions {
39 fn default() -> Self {
40 PlotOptions { width: 60, height: 16, title: None, x_label: None, y_label: None, color: false, scatter: false, x_range: None, y_range: None }
41 }
42}
43
44const GUTTER: usize = 10;
45const BRAILLE_BASE: u32 = 0x2800;
46const DOT_BITS: [[u8; 4]; 2] = [[0x01, 0x02, 0x04, 0x40], [0x08, 0x10, 0x20, 0x80]];
48const COLORS: [&str; 6] = ["\x1b[36m", "\x1b[33m", "\x1b[32m", "\x1b[35m", "\x1b[31m", "\x1b[34m"];
49
50fn format_tick(v: f64) -> String {
51 let a = v.abs();
52 let s = if a != 0.0 && !(1e-3..1e5).contains(&a) { format!("{v:.2e}") } else { format!("{v:.4}") };
53 if s.contains('e') || !s.contains('.') { s } else { s.trim_end_matches('0').trim_end_matches('.').to_string() }
55}
56
57fn extent(values: impl Iterator<Item = f64>) -> (f64, f64) {
58 let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY);
59 for v in values.filter(|v| v.is_finite()) {
60 lo = lo.min(v);
61 hi = hi.max(v);
62 }
63 if lo > hi {
64 (-1.0, 1.0)
65 } else if lo == hi {
66 (lo - 1.0, hi + 1.0)
67 } else {
68 (lo, hi)
69 }
70}
71
72pub fn render_terminal_plot(series: &[PlotSeries], opts: &PlotOptions) -> String {
74 let (w, h) = (opts.width.max(4), opts.height.max(2));
75 let (xmin, xmax) = opts.x_range.filter(|r| r.1 > r.0).unwrap_or_else(|| extent(series.iter().flat_map(|s| s.x.iter().copied())));
76 let (ymin, ymax) = opts.y_range.filter(|r| r.1 > r.0).unwrap_or_else(|| extent(series.iter().flat_map(|s| s.y.iter().copied())));
77 let (dw, dh) = (w * 2, h * 4);
78 let mut cells = vec![(0u8, 0usize); w * h];
80 let to_dot = |x: f64, y: f64| -> (i64, i64) {
81 let px = ((x - xmin) / (xmax - xmin) * (dw - 1) as f64).round() as i64;
82 let py = ((ymax - y) / (ymax - ymin) * (dh - 1) as f64).round() as i64;
83 (px, py)
84 };
85 let mut plot_dot = |px: i64, py: i64, s: usize| {
86 if px >= 0 && py >= 0 && (px as usize) < dw && (py as usize) < dh {
87 let (cx, cy) = (px as usize / 2, py as usize / 4);
88 let cell = &mut cells[cy * w + cx];
89 cell.0 |= DOT_BITS[px as usize % 2][py as usize % 4];
90 cell.1 = s;
91 }
92 };
93 for (si, s) in series.iter().enumerate() {
94 let mut prev: Option<(i64, i64)> = None;
95 for (&x, &y) in s.x.iter().zip(s.y) {
96 if !x.is_finite() || !y.is_finite() {
97 prev = None;
98 continue;
99 }
100 let p = to_dot(x, y);
101 match (prev, opts.scatter) {
102 (Some(q), false) => {
103 let (mut x0, mut y0) = q;
105 let (dx, dy) = ((p.0 - x0).abs(), -(p.1 - y0).abs());
106 let (sx, sy) = (if x0 < p.0 { 1 } else { -1 }, if y0 < p.1 { 1 } else { -1 });
107 let mut err = dx + dy;
108 loop {
109 plot_dot(x0, y0, si);
110 if (x0, y0) == p {
111 break;
112 }
113 let e2 = 2 * err;
114 if e2 >= dy {
115 err += dy;
116 x0 += sx;
117 }
118 if e2 <= dx {
119 err += dx;
120 y0 += sy;
121 }
122 }
123 }
124 _ => plot_dot(p.0, p.1, si),
125 }
126 prev = Some(p);
127 }
128 }
129
130 let mut out: Vec<String> = Vec::new();
131 if let Some(t) = &opts.title {
132 out.push(format!("{:^width$}", t, width = GUTTER + w + 1));
133 }
134 if let Some(l) = &opts.y_label {
135 out.push(l.clone());
136 }
137 for row in 0..h {
138 let tick = if row == 0 {
139 format_tick(ymax)
140 } else if row == h - 1 {
141 format_tick(ymin)
142 } else if row == h / 2 {
143 format_tick(0.5 * (ymin + ymax))
144 } else {
145 String::new()
146 };
147 let mut line = format!("{tick:>width$} │", width = GUTTER - 1);
148 for col in 0..w {
149 let (bits, owner) = cells[row * w + col];
150 let ch = char::from_u32(BRAILLE_BASE + bits as u32).expect("valid braille");
151 if opts.color && bits != 0 {
152 line.push_str(COLORS[owner % COLORS.len()]);
153 line.push(ch);
154 line.push_str("\x1b[0m");
155 } else {
156 line.push(if bits == 0 { ' ' } else { ch });
157 }
158 }
159 out.push(line);
160 }
161 out.push(format!("{:>width$} └{}", "", "─".repeat(w), width = GUTTER - 1));
162 let (lo, mid, hi) = (format_tick(xmin), format_tick(0.5 * (xmin + xmax)), format_tick(xmax));
163 let mut axis = vec![' '; w];
164 let mut put = |text: &str, start: usize| {
165 for (i, c) in text.chars().enumerate() {
166 if start + i < w {
167 axis[start + i] = c;
168 }
169 }
170 };
171 put(&lo, 0);
172 put(&mid, (w.saturating_sub(mid.chars().count())) / 2);
173 put(&hi, w.saturating_sub(hi.chars().count()));
174 out.push(format!("{:>width$} {}", "", axis.iter().collect::<String>(), width = GUTTER - 1));
175 if let Some(l) = &opts.x_label {
176 out.push(format!("{:^width$}", l, width = GUTTER + w + 1));
177 }
178 if series.len() > 1 || series.first().is_some_and(|s| !s.label.is_empty()) {
179 for (i, s) in series.iter().enumerate() {
180 let mark = if opts.color { format!("{}━\x1b[0m", COLORS[i % COLORS.len()]) } else { format!("{}", i + 1) };
181 out.push(format!("{:>width$} {mark} {}", "", s.label, width = GUTTER - 1));
182 }
183 }
184 out.join("\n")
185}
186
187pub fn generate_terminal_plot(x: &[f64], y: &[f64], width: usize, height: usize) -> String {
189 let series = [PlotSeries { label: "", x, y }];
190 render_terminal_plot(&series, &PlotOptions { width, height, ..Default::default() })
191}
192
193#[derive(Debug, Clone)]
196pub struct PolarSeries<'a> {
197 pub label: &'a str,
198 pub angles: &'a [f64],
199 pub values_db: &'a [f64],
200}
201
202pub fn render_polar_plot(series: &[PolarSeries], floor_db: f64, ring_step_db: f64, width: usize, title: Option<&str>, color: bool) -> String {
208 let peak = series.iter().flat_map(|s| s.values_db.iter().copied()).filter(|v| v.is_finite()).fold(f64::NEG_INFINITY, f64::max);
209 let peak = if peak.is_finite() { peak } else { floor_db + 1.0 };
210 let r_max = (peak - floor_db).max(1e-9);
211 let mut owned: Vec<(String, Vec<f64>, Vec<f64>)> = series
212 .iter()
213 .map(|s| {
214 let (x, y): (Vec<f64>, Vec<f64>) = s.angles.iter().zip(s.values_db).map(|(&a, &v)| {
215 let r = (v - floor_db).max(0.0);
216 (r * a.cos(), r * a.sin())
217 }).unzip();
218 (s.label.to_string(), x, y)
219 })
220 .collect();
221 let mut level = peak;
223 while ring_step_db > 0.0 && level > floor_db + 1e-9 {
224 let r = level - floor_db;
225 let (x, y): (Vec<f64>, Vec<f64>) = (0..120).map(|k| {
226 let a = std::f64::consts::TAU * k as f64 / 120.0;
227 (r * a.cos(), r * a.sin())
228 }).unzip();
229 owned.push((format!("{:+.0} dB ring", level - peak), x, y));
230 level -= ring_step_db;
231 }
232 let curves: Vec<PlotSeries> = owned[..series.len()].iter().map(|(l, x, y)| PlotSeries { label: l, x, y }).collect();
233 let rings: Vec<PlotSeries> = owned[series.len()..].iter().map(|(l, x, y)| PlotSeries { label: l, x, y }).collect();
234 let width = width.max(8);
235 let opts = PlotOptions {
236 width,
237 height: (width / 2).max(4),
238 title: title.map(str::to_string),
239 color,
240 x_range: Some((-r_max, r_max)),
241 y_range: Some((-r_max, r_max)),
242 ..Default::default()
243 };
244 let mut all: Vec<PlotSeries> = rings;
246 all.extend(curves);
247 render_terminal_plot(&all, &opts)
248}
249
250#[cfg(test)]
251mod tests {
252 use super::*;
253
254 fn sine() -> (Vec<f64>, Vec<f64>) {
255 let x: Vec<f64> = (0..200).map(|i| i as f64 * 0.05).collect();
256 (x.clone(), x.iter().map(|v| v.sin()).collect())
257 }
258
259 #[test]
260 fn layout_and_labels() {
261 let (x, y) = sine();
262 let text = generate_terminal_plot(&x, &y, 50, 12);
263 let lines: Vec<&str> = text.lines().collect();
264 assert_eq!(lines.len(), 12 + 2); assert!(lines[0].trim_start().starts_with('1'), "{}", lines[0]);
266 assert!(lines[11].trim_start().starts_with('-'));
267 assert!(lines[13].contains('0') && lines[13].contains("9.95"));
268 assert!(text.chars().any(|c| ('\u{2801}'..='\u{28FF}').contains(&c)));
269 }
270
271 #[test]
272 fn curve_occupies_expected_rows() {
273 let x: Vec<f64> = (0..=40).map(|i| i as f64).collect();
274 let y: Vec<f64> = x.to_vec();
275 let text = generate_terminal_plot(&x, &y, 20, 8);
276 let lines: Vec<&str> = text.lines().collect();
277 let plot_part = |l: &str| l.split('│').nth(1).unwrap().to_string();
279 assert_ne!(plot_part(lines[7]).chars().next().unwrap(), ' ');
280 assert_ne!(plot_part(lines[0]).chars().last().unwrap(), ' ');
281 assert_eq!(plot_part(lines[0]).chars().next().unwrap(), ' ');
282 }
283
284 #[test]
285 fn degenerate_data_title_legend_and_colour() {
286 let flat = [2.0; 5];
287 let x = [0.0, 1.0, 2.0, 3.0, 4.0];
288 let a = PlotSeries { label: "flat", x: &x, y: &flat };
289 let b = PlotSeries { label: "ramp", x: &x, y: &x };
290 let opts = PlotOptions { title: Some("T".into()), x_label: Some("time".into()), color: true, ..Default::default() };
291 let text = render_terminal_plot(&[a, b], &opts);
292 assert!(text.contains("flat") && text.contains("ramp") && text.contains("time"));
293 assert!(text.contains("\x1b[36m") && text.contains("\x1b[33m"));
294 assert!(text.lines().next().unwrap().contains('T'));
295 let nan = [f64::NAN, f64::INFINITY];
297 assert!(!generate_terminal_plot(&nan, &nan, 10, 4).is_empty());
298 assert!(!generate_terminal_plot(&[], &[], 10, 4).is_empty());
299 }
300
301 #[test]
302 fn scatter_draws_isolated_points() {
303 let opts = PlotOptions { width: 10, height: 4, scatter: true, ..Default::default() };
304 let s = PlotSeries { label: "", x: &[0.0, 10.0], y: &[0.0, 10.0] };
305 let text = render_terminal_plot(&[s], &opts);
306 let dots: usize = text.chars().filter(|c| ('\u{2801}'..='\u{28FF}').contains(c)).count();
307 assert_eq!(dots, 2);
308 }
309
310 #[test]
311 fn fixed_ranges_and_polar_plots() {
312 let x = [0.0, 1.0];
313 let y = [0.0, 1.0];
314 let opts = PlotOptions { width: 20, height: 6, x_range: Some((-1.0, 3.0)), y_range: Some((0.0, 2.0)), ..Default::default() };
315 let text = render_terminal_plot(&[PlotSeries { label: "", x: &x, y: &y }], &opts);
316 assert!(text.contains("-1") && text.lines().next().unwrap().trim_start().starts_with('2'));
317 let angles: Vec<f64> = (0..360).map(|k| (k as f64).to_radians()).collect();
319 let db: Vec<f64> = angles.iter().map(|a| 20.0 * ((1.0 + a.cos()) / 2.0).max(1e-3).log10()).collect();
320 let p = render_polar_plot(&[PolarSeries { label: "pattern", angles: &angles, values_db: &db }], -20.0, 10.0, 40, Some("cut"), false);
321 assert!(p.contains("cut") && p.contains("pattern") && p.contains("-10 dB ring"));
322 assert_eq!(p.lines().filter(|l| l.contains('│')).count(), 20); }
324}