Render a diagnostic plot gallery in Rust
Current source-owned tutorial. API availability differs by language.
Start the walkthrough · Jump to complete source
Compose nine diagnostic panels into one retained oa::plot::Figure, render it on the GPU compositor, and replay the same figure to a PNG file or an interactive oa::Viewer window.
Run
cargo run -p sdk --release --example tu_plot_gallery -- --headless --output artifact/plot
--headless skips the window and only writes PNG artifacts. Without it the program additionally opens the dark gallery in an oa::Viewer window. --output DIR chooses where the files land.
Expected output:
OA Plot walkthrough artifacts:
artifact/plot/oa-plot-intro-dark.png
artifact/plot/oa-plot-gallery-dark.png
artifact/plot/oa-plot-gallery-light.png
artifact/plot/oa-plot-evaluation-dark.png
artifact/plot/oa-plot-diagnostics-dark.png
artifact/plot/oa-plot-landscapes-dark.png
1. A figure is a grid of axes
Figure::new takes a FigureConfig describing the grid, canvas size, spacing, and theme. fig.ax(row, col) returns a mutable Axes handle for each cell.
1let mut fig = oa::plot::Figure::new(FigureConfig {2 title: "oa::plot intro".to_owned(),3 rows: 1,4 cols: 2,5 width: 1280,6 height: 560,7 h_spacing: 36,8 padding: 34,9 theme: Theme::Dark,10 ..Default::default()11});12fig.title("One retained figure, Rust and C++ parity");1314let curves = fig.ax(0, 0);15curves.title("training curves");16curves.x_label("optimizer step");17curves.y_label("cross entropy");18curves.limits(0.0, 7.0, 0.0, 1.1);19
The figure is retained: drawing calls only record a description. Nothing renders until save_to or show replays it.
2. Artists share one Axes
Every panel uses the same call shape: pass data slices plus a style record.
ax.plot(&y, LineStyle)andax.plot_xy(&x, &y, LineStyle)draw lines.ax.scatter(&x, &y, ScatterStyle)draws points.ax.histogram(&values, bins, BarStyle)bins samples.ax.bar(&values, BarStyle)draws bars.ax.heatmap(&values, rows, cols, HeatmapStyle)draws a matrix.
1ax.plot_xy(&rate, &fusion, line(success(), "fusion AUC 0.93", 1.35, 4));2ax.histogram(&scores, 20, bars(accent(), "validation scores", 0.20));3ax.heatmap(&confusion, 5, 5, HeatmapStyle {4 colormap: 1,5 auto_scale: true,6 show_grid: true,7 ..Default::default()8});9
Legends come from the label field on each style. ax.legend(false) and ax.grid(false) turn the defaults off per axes.
3. Wireframes are explicit-X projections
The two landscape panels are 2D projections of scalar fields, not a 3D scene API. Each mesh line is a row or column sweep evaluated through a height function and projected into axes space, then drawn with plot_xy. Color interpolates between a near and far color along the sweep.
1for row in 0..LINES {2 let v = -1.0 + 2.0 * row as f32 / (LINES - 1) as f32;3 // sample height_fn along the row, project into the axes plane4 let t = row as f32 / (LINES - 1) as f32;5 ax.plot_xy(&px, &py, line(gradient(far, near, t), "", 1.15, 8));6}7
4. One figure, two output sinks
gallery(theme) fills a 3×3 Figure by calling each panel builder on a cell:
1fn gallery(theme: Theme) -> oa::plot::Figure {2 let mut fig = oa::plot::Figure::new(FigureConfig {3 rows: 3, cols: 3, width: 1600, height: 1050, theme,4 ..Default::default()5 });6 training_plot(fig.ax(0, 0));7 roc_plot(fig.ax(0, 1));8 // ...9 fig10}11
fig.save_to(path) renders to PNG through the compute-only runtime. fig.show() needs a presentation runtime, so main builds the runtime to match the mode:
1let runtime = if show {2 let window = oa::SdlWindow::new("OA Plot presentation probe", 1, 1)?;3 let extensions = window.required_instance_extensions()?;4 Runtime::builder()5 .requirements(oa::RuntimeRequirements::default().presentation())6 .instance_extensions(extensions)7 .build()?8} else {9 Runtime::current()?10};11Runtime::set_default(runtime.clone());12
In --headless mode Runtime::current() resolves the thread default compute runtime. In show mode the builder adds the presentation requirement and the instance extensions the SDL window needs, and set_default installs it for the figure and texture calls.
What you built
A retained Figure records every panel once and replays it to PNG or to oa::Viewer with the same rendering path. The full source is sdk/rs/tutorials/plot/tu_plot_gallery/tu_plot_gallery.rs; the Python version is at walkthrough-python.
Example
1// OA Plot walkthrough: nine deterministic diagnostic plots, two themes, one2// GPU compositor, and the same retained Figure replay for PNG and oa::Viewer.3//4// usage:5// tu_plot_gallery [--output DIR] [--headless]6//7// The two wireframe panels are deliberate 2D projections of scalar fields.8// They demonstrate explicit-X multi-series composition without claiming a9// general 3D scene, camera, depth, or surface-plot API.10//11// Donor reference: tuPlotGallery.cpp1213use std::f32::consts::PI;1415use oa::plot::{Axes, BarStyle, FigureConfig, HeatmapStyle, LineStyle, ScatterStyle, Theme};16use oa::{Color, Runtime};1718// ── Style helpers ─────────────────────────────────────────────────────────────1920fn line(color: Color, label: &str, width: f32, antialias_samples: u32) -> LineStyle {21 LineStyle {22 color,23 label: label.to_owned(),24 width,25 antialias_samples,26 ..Default::default()27 }28}2930fn points(color: Color, label: &str, radius: f32) -> ScatterStyle {31 ScatterStyle {32 color,33 label: label.to_owned(),34 radius,35 ..Default::default()36 }37}3839fn bars(color: Color, label: &str, gap: f32) -> BarStyle {40 BarStyle {41 color,42 label: label.to_owned(),43 gap,44 ..Default::default()45 }46}4748fn gradient(a: Color, b: Color, t: f32) -> Color {49 let t = t.clamp(0.0, 1.0);50 Color::new(51 a.r + (b.r - a.r) * t,52 a.g + (b.g - a.g) * t,53 a.b + (b.b - a.b) * t,54 a.a + (b.a - a.a) * t,55 )56}5758// ── Named colors matching the donor palette ───────────────────────────────────5960fn accent() -> Color {61 Color::new(0.24, 0.65, 1.00, 1.0)62}63fn success() -> Color {64 Color::new(0.35, 0.82, 0.54, 1.0)65}66fn purple() -> Color {67 Color::new(0.75, 0.45, 1.00, 1.0)68}69fn cyan() -> Color {70 Color::new(0.30, 0.87, 0.89, 1.0)71}72fn warning() -> Color {73 Color::new(1.00, 0.80, 0.22, 1.0)74}75fn pink() -> Color {76 Color::new(1.00, 0.55, 0.75, 1.0)77}78fn gray() -> Color {79 Color::new(0.565, 0.565, 0.565, 1.0)80}8182// ── Individual axes builders ──────────────────────────────────────────────────8384// [oa-plot-intro-begin]85fn intro_figure() -> oa::plot::Figure {86 let mut fig = oa::plot::Figure::new(FigureConfig {87 title: "oa::plot intro".to_owned(),88 rows: 1,89 cols: 2,90 width: 1280,91 height: 560,92 h_spacing: 36,93 padding: 34,94 theme: Theme::Dark,95 ..Default::default()96 });97 fig.title("One retained figure, Rust and C++ parity");9899 let steps = [0.0f32, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0];100 let train = [1.00f32, 0.78, 0.61, 0.48, 0.37, 0.29, 0.23, 0.19];101 let validation = [1.04f32, 0.83, 0.66, 0.53, 0.43, 0.35, 0.30, 0.27];102 let ideal = [0.0f32, 0.25, 0.50, 0.75, 1.0];103 let confidence = [0.10f32, 0.30, 0.50, 0.70, 0.90];104 let accuracy = [0.08f32, 0.34, 0.47, 0.74, 0.88];105106 let curves = fig.ax(0, 0);107 curves.title("training curves");108 curves.x_label("optimizer step");109 curves.y_label("cross entropy");110 curves.limits(0.0, 7.0, 0.0, 1.1);111 curves.plot_xy(&steps, &train, line(accent(), "train", 1.6, 4));112 curves.plot_xy(&steps, &validation, line(success(), "validation", 1.6, 4));113114 let quality = fig.ax(0, 1);115 quality.title("Calibration");116 quality.x_label("confidence");117 quality.y_label("observed accuracy");118 quality.limits(0.0, 1.0, 0.0, 1.0);119 quality.plot_xy(&ideal, &ideal, line(gray(), "ideal", 1.35, 4));120 quality.scatter(&confidence, &accuracy, points(cyan(), "model", 3.5));121 fig122}123// [oa-plot-intro-end]124125fn training_plot(ax: &mut Axes) {126 let n = 72usize;127 let train: Vec<f32> = (0..n)128 .map(|i| {129 let step = i as f32;130 1.55 * (-step / 18.0).exp() + 0.035 * (step * 0.52).sin() + 0.11131 })132 .collect();133 let validation: Vec<f32> = (0..n)134 .map(|i| {135 let step = i as f32;136 1.45 * (-step / 21.0).exp() + 0.045 * (step * 0.39 + 0.8).sin() + 0.17137 })138 .collect();139 ax.title("training curves");140 ax.x_label("optimizer step");141 ax.y_label("cross entropy");142 ax.plot(&train, line(accent(), "train", 1.35, 4));143 ax.plot(&validation, line(success(), "validation", 1.35, 4));144}145146fn roc_plot(ax: &mut Axes) {147 let n = 33usize;148 let rate: Vec<f32> = (0..n).map(|i| i as f32 / (n - 1) as f32).collect();149 let vision: Vec<f32> = rate150 .iter()151 .map(|&x| (1.0 - (-4.3 * x).exp()).clamp(0.0, 1.0))152 .collect();153 let fusion: Vec<f32> = rate154 .iter()155 .map(|&x| (1.0 - (-6.7 * x).exp()).clamp(0.0, 1.0))156 .collect();157 ax.title("ROC threshold sweep");158 ax.x_label("false positive rate");159 ax.y_label("true positive rate");160 ax.limits(0.0, 1.0, 0.0, 1.0);161 ax.plot_xy(&rate, &vision, line(cyan(), "vision AUC 0.88", 1.35, 4));162 ax.plot_xy(&rate, &fusion, line(success(), "fusion AUC 0.93", 1.35, 4));163 ax.plot_xy(&rate, &rate, line(gray(), "chance", 1.35, 4));164}165166fn precision_recall_plot(ax: &mut Axes) {167 let n = 33usize;168 let recall: Vec<f32> = (0..n).map(|i| i as f32 / (n - 1) as f32).collect();169 let vision: Vec<f32> = recall170 .iter()171 .map(|&x| (0.98 - 0.40 * x.powf(1.6) - 0.025 * (x * 5.0 * PI).sin()).clamp(0.0, 1.0))172 .collect();173 let fusion: Vec<f32> = recall174 .iter()175 .map(|&x| (0.995 - 0.27 * x.powf(2.1) - 0.015 * (x * 4.0 * PI).sin()).clamp(0.0, 1.0))176 .collect();177 ax.title("Precision-recall");178 ax.x_label("recall");179 ax.y_label("precision");180 ax.limits(0.0, 1.0, 0.0, 1.0);181 ax.plot_xy(&recall, &vision, line(purple(), "vision AP 0.84", 1.35, 4));182 ax.plot_xy(&recall, &fusion, line(pink(), "fusion AP 0.91", 1.35, 4));183}184185fn score_histogram(ax: &mut Axes) {186 let scores: Vec<f32> = (0..192usize)187 .map(|i| {188 let phase = i as f32;189 let cluster = if i % 3 == 0 { 0.28 } else { 0.74 };190 (cluster + 0.12 * (phase * 1.73).sin() + 0.045 * (phase * 0.37).cos()).clamp(0.0, 1.0)191 })192 .collect();193 ax.title("confidence distribution");194 ax.x_label("model score");195 ax.y_label("samples");196 ax.histogram(&scores, 20, bars(accent(), "validation scores", 0.20));197}198199fn calibration_scatter(ax: &mut Axes) {200 let n = 24usize;201 let confidence: Vec<f32> = (0..n).map(|i| (i as f32 + 0.5) / n as f32).collect();202 let accuracy: Vec<f32> = confidence203 .iter()204 .map(|&x| (x + 0.055 * (8.0 * PI * x).sin() - 0.025).clamp(0.0, 1.0))205 .collect();206 let ideal: Vec<f32> = confidence.clone();207 ax.title("Calibration");208 ax.x_label("confidence");209 ax.y_label("observed accuracy");210 ax.limits(0.0, 1.0, 0.0, 1.0);211 ax.plot_xy(&confidence, &ideal, line(gray(), "ideal", 1.35, 4));212 ax.scatter(&confidence, &accuracy, points(cyan(), "model", 3.5));213}214215fn throughput_bars(ax: &mut Axes) {216 let throughput = [0.42f32, 0.58, 0.71, 0.86, 0.79, 0.94];217 ax.title("normalized throughput");218 ax.x_label("kernel route");219 ax.y_label("relative peak");220 ax.limits(-0.5, 5.5, 0.0, 1.0);221 ax.bar(&throughput, bars(warning(), "device routes", 0.24));222}223224fn confusion_heatmap(ax: &mut Axes) {225 let confusion = [226 42.0f32, 2.0, 0.0, 1.0, 0.0, 3.0, 37.0, 2.0, 0.0, 1.0, 0.0, 2.0, 40.0, 3.0, 0.0, 1.0, 0.0, 2.0,227 38.0, 2.0, 0.0, 1.0, 0.0, 2.0, 43.0,228 ];229 ax.title("confusion matrix");230 ax.x_label("predicted class");231 ax.y_label("reference class");232 ax.heatmap(233 &confusion,234 5,235 5,236 HeatmapStyle {237 colormap: 1,238 auto_scale: true,239 show_grid: true,240 ..Default::default()241 },242 );243 ax.grid(false);244}245246fn wireframe(247 ax: &mut Axes,248 title: &str,249 height_fn: impl Fn(f32, f32) -> f32,250 near: Color,251 far: Color,252) {253 const LINES: i32 = 13;254 const SAMPLES: i32 = 29;255 // Row sweeps.256 for row in 0..LINES {257 let v = -1.0 + 2.0 * row as f32 / (LINES - 1) as f32;258 let mut px = vec![0.0f32; SAMPLES as usize];259 let mut py = vec![0.0f32; SAMPLES as usize];260 for col in 0..SAMPLES {261 let u = -1.0 + 2.0 * col as f32 / (SAMPLES - 1) as f32;262 let z = height_fn(u, v);263 px[col as usize] = 0.50 + 0.34 * (u - v);264 py[col as usize] = 0.58 - 0.16 * (u + v) - 0.23 * z;265 }266 let t = row as f32 / (LINES - 1) as f32;267 ax.plot_xy(&px, &py, line(gradient(far, near, t), "", 1.15, 8));268 }269 // Column sweeps.270 for col in 0..LINES {271 let u = -1.0 + 2.0 * col as f32 / (LINES - 1) as f32;272 let mut px = vec![0.0f32; SAMPLES as usize];273 let mut py = vec![0.0f32; SAMPLES as usize];274 for row in 0..SAMPLES {275 let v = -1.0 + 2.0 * row as f32 / (SAMPLES - 1) as f32;276 let z = height_fn(u, v);277 px[row as usize] = 0.50 + 0.34 * (u - v);278 py[row as usize] = 0.58 - 0.16 * (u + v) - 0.23 * z;279 }280 let t = col as f32 / (LINES - 1) as f32;281 let mut col_style = line(gradient(far, near, t), "", 1.15, 8);282 col_style.color.a = 0.78;283 ax.plot_xy(&px, &py, col_style);284 }285 ax.title(title);286 ax.limits(-0.20, 1.20, 0.02, 1.08);287 ax.grid(false);288 ax.legend(false);289}290291fn loss_landscape(ax: &mut Axes) {292 wireframe(293 ax,294 "projected loss landscape",295 |x, y| {296 let bowl = 0.42 * (x * x + 0.75 * y * y);297 bowl + 0.18 * (2.7 * x).sin() * (3.1 * y).cos()298 },299 cyan(),300 purple(),301 );302}303304fn gradient_basin(ax: &mut Axes) {305 wireframe(306 ax,307 "projected optimizer basin",308 |x, y| {309 let radius = (x * x + y * y).sqrt();310 0.34 * radius + 0.17 * (9.0 * radius).cos() * (-1.8 * radius).exp()311 },312 success(),313 warning(),314 );315}316317fn gallery(theme: Theme) -> oa::plot::Figure {318 let mut fig = oa::plot::Figure::new(FigureConfig {319 title: "OA Plot gallery".to_owned(),320 rows: 3,321 cols: 3,322 width: 1600,323 height: 1050,324 h_spacing: 32,325 v_spacing: 36,326 padding: 34,327 theme,328 ..Default::default()329 });330 fig.title("OA Plot, GPU-composed ML diagnostics");331 training_plot(fig.ax(0, 0));332 roc_plot(fig.ax(0, 1));333 precision_recall_plot(fig.ax(0, 2));334 score_histogram(fig.ax(1, 0));335 calibration_scatter(fig.ax(1, 1));336 throughput_bars(fig.ax(1, 2));337 confusion_heatmap(fig.ax(2, 0));338 loss_landscape(fig.ax(2, 1));339 gradient_basin(fig.ax(2, 2));340 fig341}342343fn evaluation_figure() -> oa::plot::Figure {344 let mut fig = oa::plot::Figure::new(FigureConfig {345 title: "OA model evaluation".to_owned(),346 rows: 1,347 cols: 2,348 width: 1280,349 height: 560,350 h_spacing: 36,351 padding: 34,352 ..Default::default()353 });354 fig.title("Model evaluation: ROC and precision-recall");355 roc_plot(fig.ax(0, 0));356 precision_recall_plot(fig.ax(0, 1));357 fig358}359360fn diagnostics_figure() -> oa::plot::Figure {361 let mut fig = oa::plot::Figure::new(FigureConfig {362 title: "OA model diagnostics".to_owned(),363 rows: 2,364 cols: 2,365 width: 1200,366 height: 900,367 h_spacing: 32,368 v_spacing: 36,369 padding: 34,370 ..Default::default()371 });372 fig.title("training and evaluation diagnostics");373 training_plot(fig.ax(0, 0));374 score_histogram(fig.ax(0, 1));375 calibration_scatter(fig.ax(1, 0));376 confusion_heatmap(fig.ax(1, 1));377 fig378}379380fn landscapes_figure() -> oa::plot::Figure {381 let mut fig = oa::plot::Figure::new(FigureConfig {382 title: "OA projected landscapes".to_owned(),383 rows: 1,384 cols: 2,385 width: 1280,386 height: 560,387 h_spacing: 36,388 padding: 34,389 ..Default::default()390 });391 fig.title("scalar-field projections, explicit-X wireframes");392 loss_landscape(fig.ax(0, 0));393 gradient_basin(fig.ax(0, 1));394 fig395}396397// ── Entry point ───────────────────────────────────────────────────────────────398399fn usage(program: &str) {400 eprintln!("usage: {program} [--output DIR] [--headless]");401}402403fn main() -> anyhow::Result<()> {404 let mut output = std::path::PathBuf::from("artifact/plot");405 let mut show = true;406407 let args: Vec<String> = std::env::args().collect();408 let mut i = 1;409 while i < args.len() {410 match args[i].as_str() {411 "--headless" => {412 show = false;413 }414 "--output" if i + 1 < args.len() => {415 i += 1;416 output = std::path::PathBuf::from(&args[i]);417 }418 "--help" => {419 usage(&args[0]);420 return Ok(());421 }422 other => {423 eprintln!("unknown argument: {other}");424 usage(&args[0]);425 std::process::exit(1);426 }427 }428 i += 1;429 }430431 std::fs::create_dir_all(&output).map_err(|e| {432 eprintln!("could not create output dir: {e}");433 e434 })?;435436 let runtime = if show {437 let window = oa::SdlWindow::new("OA Plot presentation probe", 1, 1)?;438 let extensions = window.required_instance_extensions()?;439 Runtime::builder()440 .requirements(oa::RuntimeRequirements::default().presentation())441 .instance_extensions(extensions)442 .build()?443 } else {444 Runtime::current()?445 };446 Runtime::set_default(runtime.clone());447448 let mut dark = gallery(Theme::Dark);449 let mut light = gallery(Theme::Light);450 let mut intro = intro_figure();451 let mut evaluation = evaluation_figure();452 let mut diagnostics = diagnostics_figure();453 let mut landscapes = landscapes_figure();454455 println!("OA Plot walkthrough artifacts:");456457 let save = |fig: &mut oa::plot::Figure, name: &str| -> anyhow::Result<()> {458 let path = output.join(name);459 fig.save_to(path.to_str().unwrap_or(name))?;460 println!(" {}", path.display());461 Ok(())462 };463464 save(&mut intro, "oa-plot-intro-dark.png")?;465 save(&mut dark, "oa-plot-gallery-dark.png")?;466 save(&mut light, "oa-plot-gallery-light.png")?;467 save(&mut evaluation, "oa-plot-evaluation-dark.png")?;468 save(&mut diagnostics, "oa-plot-diagnostics-dark.png")?;469 save(&mut landscapes, "oa-plot-landscapes-dark.png")?;470471 if show {472 dark.show()?;473 }474 Ok(())475}476
Run Rust tutorials from the OA SDK checkout with cargo run --release --example <name>. Run Python with the environment containing the OA native extension. Consult each program's arguments and capability checks before running it.