plotpx 0.1.7

Pixel-focused plotting engine that renders magnitude grids, heatmaps, and spectra to RGBA buffers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
#![deny(warnings)]

#[cfg(test)]
use plotpx::*;
#[cfg(test)]
use std::time::Instant;

const EXAMPLES_DIR: &str = "docs/examples";

#[cfg(test)]
fn output_path(file: &str) -> String {
    format!("{}/{}", EXAMPLES_DIR, file)
}

#[cfg(test)]
fn magnitude_test() {
    println!("Running magnitude_test...");
    let start = Instant::now();

    const W: u32 = 512;
    const H: u32 = 512;

    let mut plot = Magnitude::new(W, H);

    for y in 0..H {
        for x in 0..W {
            let magnitude = (x + y) as f32 / (W + H) as f32;
            plot.add_point(x, y, magnitude);
        }
    }

    let image = plot.render();
    write_png(output_path("magnitude.png"), &image, W, H).unwrap();

    let elapsed = start.elapsed();
    println!("  Rust magnitude_test completed in {:?}", elapsed);
}

#[cfg(test)]
fn magnitude_test2() {
    println!("Running magnitude_test2...");
    let start = Instant::now();

    const WIDTH: u32 = 512;
    const HEIGHT: u32 = 512;

    let mut plot = Magnitude::new(WIDTH, HEIGHT);

    let center_x = WIDTH as f32 / 2.0;
    let center_y = HEIGHT as f32 / 2.0;
    let frequency = 20.0;

    for y in 0..HEIGHT {
        for x in 0..WIDTH {
            let dx = x as f32 - center_x;
            let dy = y as f32 - center_y;
            let distance = (dx * dx + dy * dy).sqrt();

            let max_distance = (center_x * center_x + center_y * center_y).sqrt();
            let normalized_distance = distance / max_distance;

            let magnitude = ((normalized_distance * frequency).sin() + 1.0) / 2.0;
            plot.add_point(x, y, magnitude);
        }
    }

    let image = plot.render();
    write_png(output_path("magnitude2.png"), &image, WIDTH, HEIGHT).unwrap();

    let elapsed = start.elapsed();
    println!("  Rust magnitude_test2 completed in {:?}", elapsed);
}

#[cfg(test)]
fn magnitude_mapped_test() {
    println!("Running magnitude_mapped_test...");
    let start = Instant::now();

    const W_DATA: u32 = 128;
    const H_DATA: u32 = 128;
    const W: u32 = 640;
    const H: u32 = 480;

    let mut plot = MagnitudeMapped::new(W_DATA, H_DATA, W, H);

    for y in 0..H_DATA {
        for x in 0..W_DATA {
            let magnitude = (x + y) as f32 / (W_DATA + H_DATA) as f32;
            plot.add_point(x, y, magnitude);
        }
    }

    let image = plot.render();
    write_png(output_path("magnitude_mapped.png"), &image, W, H).unwrap();

    let elapsed = start.elapsed();
    println!("  Rust magnitude_mapped_test completed in {:?}", elapsed);
}

#[cfg(test)]
fn magnitude_mapped_shrink_test() {
    println!("Running magnitude_mapped_shrink_test...");
    let start = Instant::now();

    const W_DATA: u32 = 512;
    const H_DATA: u32 = 512;
    const W: u32 = 256;
    const H: u32 = 256;

    let mut plot = MagnitudeMapped::new(W_DATA, H_DATA, W, H);

    for y in 0..H_DATA {
        for x in 0..W_DATA {
            let magnitude = (x + y) as f32 / (W_DATA + H_DATA) as f32;
            plot.add_point(x, y, magnitude);
        }
    }

    let image = plot.render();
    write_png(
        output_path("magnitude_mapped_shrink.png"),
        &image,
        W,
        H,
    )
    .unwrap();

    let elapsed = start.elapsed();
    println!(
        "  Rust magnitude_mapped_shrink_test completed in {:?}",
        elapsed
    );
}

#[cfg(test)]
fn magnitude_with_annotations_demo() {
    println!("Running magnitude_with_annotations_demo...");
    let start = Instant::now();

    const WIDTH: u32 = 1024;
    const HEIGHT: u32 = 576;

    let mut plot = Magnitude::new(WIDTH, HEIGHT);

    for y in 0..HEIGHT {
        for x in 0..WIDTH {
            let fx = x as f32 / WIDTH as f32;
            let fy = y as f32 / HEIGHT as f32;
            let magnitude =
                (fx * std::f32::consts::PI * 4.0).sin() * (fy * std::f32::consts::PI * 2.0).cos();
            plot.add_point(x, y, magnitude);
        }
    }

    let mut annotations = ChartAnnotations::default();
    annotations.border_color = BorderColor::White;
    annotations.title = Some(ChartTitle::new("Sine Wave Interference"));
    annotations.x_axis = Some(
        AxisConfig::new("Horizontal Position", 0.0, WIDTH as f32)
            .with_units("px")
            .with_tick_count(6)
            .with_decimal_places(0),
    );
    annotations.y_axis = Some(
        AxisConfig::new("Vertical Position", 0.0, HEIGHT as f32)
            .with_units("px")
            .with_tick_count(5)
            .with_decimal_places(0),
    );

    let chart = plot.render_default_with_annotations(&annotations);
    write_png(
        output_path("magnitude_annotated.png"),
        &chart.pixels,
        chart.width,
        chart.height,
    )
    .unwrap();

    let elapsed = start.elapsed();
    println!(
        "  Rust magnitude_with_annotations_demo completed in {:?}",
        elapsed
    );
}

#[cfg(test)]
fn generate_spiral(width: u32, height: u32, num_points: usize, turns: f32) -> Vec<(f32, f32)> {
    let mut data = Vec::with_capacity(num_points);

    let center_x = width as f32 / 2.0;
    let center_y = height as f32 / 2.0;
    let max_radius = (width.min(height) as f32) / 2.0;

    for i in 0..num_points {
        let t = i as f32 / num_points as f32;
        let angle = turns * 2.0 * std::f32::consts::PI * t;
        let radius = max_radius * t;

        let x = center_x + radius * angle.cos();
        let y = center_y + radius * angle.sin();

        data.push((x, y));
    }

    data
}

#[cfg(test)]
fn plot_spiral(plot: &mut MagnitudeMapped, spiral_points: &[(f32, f32)], intensity: f32) {
    plot.reset();

    for &(x, y) in spiral_points {
        let x = x as u32;
        let y = y as u32;

        if x < plot.input_width && y < plot.input_height {
            plot.add_point(x, y, intensity);
        }
    }
}

#[cfg(test)]
fn magnitude_grid_plot() {
    println!("Running magnitude_grid_plot...");
    let start = Instant::now();

    const INPUT_SIZE: u32 = 200;
    const PLOT_SIZE: u32 = 150;
    const GRID_SIZE: usize = 4;

    let mut grid = MagnitudeMappedGrid::new(GRID_SIZE, INPUT_SIZE, INPUT_SIZE, PLOT_SIZE, PLOT_SIZE);

    for row in 0..GRID_SIZE {
        for col in 0..GRID_SIZE {
            let plot = grid.get_plot(row, col);

            let num_points = 150 + (row * 40) + (col * 30);
            let turns = 1.5 + (row as f32 * 0.4) + (col as f32 * 0.2);

            let spiral_points = generate_spiral(INPUT_SIZE, INPUT_SIZE, num_points, turns);

            let intensity = 1.0;
            plot_spiral(plot, &spiral_points, intensity);
        }
    }

    let spiral_color_scheme: Vec<Rgba> = vec![
        [20, 0, 100, 255],  // Deep blue
        [50, 0, 200, 255],  // Royal blue
        [0, 100, 255, 255], // Azure
        [0, 200, 200, 255], // Cyan
        [0, 255, 100, 255], // Teal
        [100, 255, 0, 255], // Green
        [200, 255, 0, 255], // Chartreuse
        [255, 200, 0, 255], // Yellow
        [255, 100, 0, 255], // Orange
        [255, 0, 100, 255], // Red
        [200, 0, 200, 255], // Magenta
    ];

    let colors = make_color_scheme(&spiral_color_scheme, 128);
    let image = grid.render(&colors);

    let total_width = PLOT_SIZE * GRID_SIZE as u32;
    let total_height = PLOT_SIZE * GRID_SIZE as u32;
    write_png(
        output_path("spiral_grid.png"),
        &image,
        total_width,
        total_height,
    )
    .unwrap();

    let elapsed = start.elapsed();
    println!("  Rust magnitude_grid_plot completed in {:?}", elapsed);
}

#[cfg(test)]
fn heatmap_test() {
    println!("Running heatmap_test...");
    let start = Instant::now();

    const W: u32 = 512;
    const H: u32 = 512;
    const NPOINTS: usize = 600;

    let mut hm = Heatmap::new(W, H);

    // Generate spiral data
    let data = generate_spiral(W, H, NPOINTS, 10.0);

    for point in &data {
        hm.add_point(point.0 as u32, point.1 as u32);
    }

    let image = hm.render();
    write_png(output_path("heatmap.png"), &image, W, H).unwrap();

    let elapsed = start.elapsed();
    println!("  Rust heatmap_test completed in {:?}", elapsed);
}

#[cfg(test)]
fn spectrum_test_sine() {
    println!("Running spectrum_test_sine...");
    let start = Instant::now();

    const BINS: u32 = 256;
    const W: u32 = 640;
    const H: u32 = 360;

    let mut plot = Spectrum::new(BINS, W, H);
    plot.style = BarStyle::Gradient;
    plot.show_peaks = true;
    plot.bar_width_factor = 0.8;

    // Create a simple spectrum with a single frequency spike
    let mut magnitudes = vec![0.0f32; BINS as usize];

    // Add a peak at bin 64
    let peak_bin = 64;
    magnitudes[peak_bin] = 1.0;

    // Add spectral leakage
    for i in 1..=10 {
        if peak_bin >= i {
            magnitudes[peak_bin - i] = 1.0 / (i * i) as f32;
        }
        if peak_bin + i < BINS as usize {
            magnitudes[peak_bin + i] = 1.0 / (i * i) as f32;
        }
    }

    plot.update(&magnitudes);

    let image = plot.render();
    write_png(output_path("spectrum_sine.png"), &image, W, H).unwrap();

    let elapsed = start.elapsed();
    println!("  Rust spectrum_test_sine completed in {:?}", elapsed);
}

#[cfg(test)]
fn spectrum_test_complex() {
    println!("Running spectrum_test_complex...");
    let start = Instant::now();

    const BINS: u32 = 256;
    const W: u32 = 640;
    const H: u32 = 360;

    let mut plot = Spectrum::new(BINS, W, H);
    plot.style = BarStyle::Solid;
    plot.show_peaks = true;
    plot.bar_width_factor = 0.9;

    let mut magnitudes = vec![0.0f32; BINS as usize];

    // Add several frequency peaks
    let peaks = [32, 64, 96, 128, 192];
    let amplitudes = [0.5, 1.0, 0.7, 0.3, 0.8];

    for p in 0..5 {
        let peak_bin = peaks[p];
        let amplitude = amplitudes[p];

        magnitudes[peak_bin] = amplitude;

        // Add spectral leakage
        for i in 1..=5 {
            if peak_bin >= i {
                magnitudes[peak_bin - i] = amplitude / (i * i) as f32;
            }
            if peak_bin + i < BINS as usize {
                magnitudes[peak_bin + i] = amplitude / (i * i) as f32;
            }
        }
    }

    plot.update(&magnitudes);

    let image = plot.render_with_colors(&make_color_scheme(INFERNO_KEY_COLORS, 128));
    write_png(output_path("spectrum_complex.png"), &image, W, H).unwrap();

    let elapsed = start.elapsed();
    println!("  Rust spectrum_test_complex completed in {:?}", elapsed);
}

#[cfg(not(test))]
fn main() {
    println!(
        "Plotpx test images are only generated during `cargo test`. \
Run `cargo test -- --nocapture` to regenerate the PNG outputs in `{}`.",
        EXAMPLES_DIR
    );
}

#[cfg(test)]
mod tests {
    use super::*;

    fn ensure_examples_dir() {
        if let Err(err) = std::fs::create_dir_all(EXAMPLES_DIR) {
            panic!("failed to create examples directory: {}", err);
        }
    }

    #[test]
    fn generates_example_gallery() {
        ensure_examples_dir();

        let total_start = Instant::now();

        magnitude_test();
        magnitude_test2();
        magnitude_mapped_test();
        magnitude_mapped_shrink_test();
        magnitude_with_annotations_demo();
        magnitude_grid_plot();
        heatmap_test();
        spectrum_test_sine();
        spectrum_test_complex();

        let total_elapsed = total_start.elapsed();
        println!("\nTotal Rust execution time: {:?}", total_elapsed);
    }
}