pyrucast 0.1.0

Finite-element library in Rust, inspired by cast3m, exposed to Python
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
//! Field-coloured rendering overlay — the "current component" button.
//!
//! Drawn on top of the rendered scene whenever a node field is supplied
//! (file export AND interactive window). In the interactive window the
//! same rectangle doubles as a **clickable button** that cycles through
//! the field's components — click detection uses `button_rect` so the
//! geometry stays in one place.

use crate::error::Result;
use crate::viz::drawable::pl_err;
use plotters::coord::Shift;
use plotters::prelude::*;

const BUTTON_MARGIN: i32 = 10;
const BUTTON_WIDTH: i32 = 260;
const BUTTON_HEIGHT: i32 = 26;
const BUTTON_FILL: RGBColor = RGBColor(245, 245, 245);
const BUTTON_BORDER: RGBColor = RGBColor(110, 110, 110);
const BUTTON_TEXT: RGBColor = RGBColor(20, 20, 20);

// ─── Colorbar geometry (right edge of the canvas) ───────────────────────────
const BAR_WIDTH: i32 = 16;
/// Space reserved to the right of the bar for tick marks + value labels.
const BAR_RIGHT_MARGIN: i32 = 58;
const BAR_TOP_MARGIN: i32 = 48;
const BAR_BOTTOM_MARGIN: i32 = 36;
const BAR_TICKS: usize = 5;

/// Pixel-space rectangle `(x, y, width, height)` of the button, in the
/// drawing area's local coordinate system (top-left origin). Centred at
/// the top of the area.
pub(crate) fn button_rect(area_width: u32) -> (i32, i32, i32, i32) {
    let x = (area_width as i32 - BUTTON_WIDTH) / 2;
    let y = BUTTON_MARGIN;
    (x.max(BUTTON_MARGIN), y, BUTTON_WIDTH, BUTTON_HEIGHT)
}

/// Is the pixel `(px, py)` inside the button on a canvas of size `(w, h)`?
#[cfg(any(test, feature = "viz-interactive"))]
pub(crate) fn click_hits_button(px: f64, py: f64, area_width: u32) -> bool {
    let (bx, by, bw, bh) = button_rect(area_width);
    let inside_x = px >= bx as f64 && px <= (bx + bw) as f64;
    let inside_y = py >= by as f64 && py <= (by + bh) as f64;
    inside_x && inside_y
}

/// Draw the labelled button (component name + value range) onto `area`.
pub(crate) fn draw_field_overlay<DB: DrawingBackend>(
    area: &DrawingArea<DB, Shift>,
    component: &str,
    vmin: f64,
    vmax: f64,
) -> Result<()>
where
    DB::ErrorType: 'static,
{
    let (w, _) = area.dim_in_pixel();
    let (bx, by, bw, bh) = button_rect(w);

    // Filled background.
    let fill = ShapeStyle::from(&BUTTON_FILL).filled();
    area.draw(&Rectangle::new(
        [(bx, by), (bx + bw - 1, by + bh - 1)],
        fill,
    ))
    .map_err(pl_err)?;
    // Border (un-filled rectangle = stroke).
    let border = ShapeStyle::from(&BUTTON_BORDER);
    area.draw(&Rectangle::new(
        [(bx, by), (bx + bw - 1, by + bh - 1)],
        border,
    ))
    .map_err(pl_err)?;

    // Label centred vertically — plotters draws text with its top-left at
    // `pos`, so we shift down by ~6 px to feel centred for a 14-pt font.
    let label = format!("[{}]  min={:.3}  max={:.3}", component, vmin, vmax);
    let text_style = TextStyle::from(("sans-serif", 13).into_font()).color(&BUTTON_TEXT);
    area.draw_text(&label, &text_style, (bx + 10, by + 5))
        .map_err(pl_err)?;
    Ok(())
}

/// Draw a vertical colorbar on the right edge of `area`: the `cmap`
/// gradient (same one painting the cells) annotated with evenly spaced
/// value ticks. `vmin` maps to the bottom, `vmax` to the top.
///
/// No-op on a canvas too small to host the bar with its labels.
pub(crate) fn draw_colorbar<DB: DrawingBackend>(
    area: &DrawingArea<DB, Shift>,
    cmap: crate::viz::Colormap,
    vmin: f64,
    vmax: f64,
) -> Result<()>
where
    DB::ErrorType: 'static,
{
    let (w, h) = area.dim_in_pixel();
    let (w, h) = (w as i32, h as i32);
    let bar_x = w - BAR_RIGHT_MARGIN - BAR_WIDTH;
    let bar_top = BAR_TOP_MARGIN;
    let bar_bottom = h - BAR_BOTTOM_MARGIN;
    let bar_h = bar_bottom - bar_top;
    if bar_x <= 0 || bar_h <= 1 {
        return Ok(());
    }

    // Gradient: one filled row per pixel. `colormap` with the same
    // `cmap` / `(vmin, vmax)` as the cells keeps the bar and the mesh
    // consistent, including the degenerate (vmax ≤ vmin) → midpoint case.
    for py in 0..bar_h {
        let t = 1.0 - py as f64 / (bar_h - 1) as f64; // 1 at top, 0 at bottom
        let value = vmin + t * (vmax - vmin);
        let c = crate::viz::field_color::colormap(cmap, value, vmin, vmax);
        let style = ShapeStyle::from(&RGBColor(c.r, c.g, c.b)).filled();
        let y = bar_top + py;
        // 1-px-tall row: a zero-height rectangle (y..y) fills nothing,
        // so span y..y+1.
        area.draw(&Rectangle::new(
            [(bar_x, y), (bar_x + BAR_WIDTH - 1, y + 1)],
            style,
        ))
        .map_err(pl_err)?;
    }
    // Border around the bar.
    area.draw(&Rectangle::new(
        [(bar_x, bar_top), (bar_x + BAR_WIDTH - 1, bar_bottom - 1)],
        ShapeStyle::from(&BUTTON_BORDER),
    ))
    .map_err(pl_err)?;

    // Ticks + value labels, bottom (vmin) → top (vmax).
    let text_style = TextStyle::from(("sans-serif", 12).into_font()).color(&BUTTON_TEXT);
    let tick_style = ShapeStyle::from(&BUTTON_BORDER);
    for i in 0..BAR_TICKS {
        let frac = i as f64 / (BAR_TICKS - 1) as f64;
        let value = vmin + frac * (vmax - vmin);
        let y = bar_bottom - 1 - (frac * (bar_h - 1) as f64).round() as i32;
        area.draw(&PathElement::new(
            vec![(bar_x + BAR_WIDTH, y), (bar_x + BAR_WIDTH + 4, y)],
            tick_style,
        ))
        .map_err(pl_err)?;
        area.draw_text(
            &format!("{value:.3}"),
            &text_style,
            (bar_x + BAR_WIDTH + 8, y - 7),
        )
        .map_err(pl_err)?;
    }
    Ok(())
}

// ─── View readout (interactive window only) ─────────────────────────────────

#[cfg(any(test, feature = "viz-interactive"))]
const READOUT_WIDTH: i32 = 210;
#[cfg(any(test, feature = "viz-interactive"))]
const READOUT_HEIGHT: i32 = 26;

/// Draw the current `(yaw, pitch, scale)` — same order as the `view=`
/// tuple accepted by `plot()` — as small text pinned to the top-right
/// corner. Interactive window only: it lets the user read back a camera
/// angle they rotated/zoomed to, to reuse as `view=(...)` later.
#[cfg(any(test, feature = "viz-interactive"))]
pub(crate) fn draw_view_readout<DB: DrawingBackend>(
    area: &DrawingArea<DB, Shift>,
    view: &crate::viz::View,
) -> Result<()>
where
    DB::ErrorType: 'static,
{
    let (w, _) = area.dim_in_pixel();
    let x = (w as i32 - READOUT_WIDTH - BUTTON_MARGIN).max(BUTTON_MARGIN);
    let y = BUTTON_MARGIN;

    // Filled background + border, same look as the field button, so the
    // text stays legible over any mesh colour behind it.
    area.draw(&Rectangle::new(
        [(x, y), (x + READOUT_WIDTH - 1, y + READOUT_HEIGHT - 1)],
        ShapeStyle::from(&BUTTON_FILL).filled(),
    ))
    .map_err(pl_err)?;
    area.draw(&Rectangle::new(
        [(x, y), (x + READOUT_WIDTH - 1, y + READOUT_HEIGHT - 1)],
        ShapeStyle::from(&BUTTON_BORDER),
    ))
    .map_err(pl_err)?;

    let label = format!(
        "view=({:.1}, {:.1}, {:.2})",
        view.yaw, view.pitch, view.scale
    );
    let text_style = TextStyle::from(("sans-serif", 13).into_font()).color(&BUTTON_TEXT);
    area.draw_text(&label, &text_style, (x + 6, y + 5))
        .map_err(pl_err)?;
    Ok(())
}

// ─── Frame slider (evolution plots) ─────────────────────────────────────────
//
// The slider is drawn and grabbed only in the interactive window (file export
// shows a single static frame), so its helpers are gated like the rest of the
// interactive path — plus `test` so the unit tests below stay reachable.

#[cfg(any(test, feature = "viz-interactive"))]
const SLIDER_MARGIN_X: i32 = 60;
#[cfg(any(test, feature = "viz-interactive"))]
const SLIDER_BOTTOM_MARGIN: i32 = 20;
#[cfg(any(test, feature = "viz-interactive"))]
const SLIDER_HEIGHT: i32 = 8;
#[cfg(any(test, feature = "viz-interactive"))]
const SLIDER_KNOB_R: i32 = 7;
/// Vertical tolerance (px) around the track that still grabs the slider.
#[cfg(any(test, feature = "viz-interactive"))]
const SLIDER_HIT_PAD: i32 = 12;
#[cfg(any(test, feature = "viz-interactive"))]
const SLIDER_TRACK: RGBColor = RGBColor(210, 210, 210);
#[cfg(any(test, feature = "viz-interactive"))]
const SLIDER_FILL: RGBColor = RGBColor(70, 130, 200);

/// Pixel-space track rectangle `(x, y, width, height)` of the frame slider,
/// a horizontal bar near the bottom of a canvas of size `(w, h)`.
#[cfg(any(test, feature = "viz-interactive"))]
pub(crate) fn slider_rect(area_w: u32, area_h: u32) -> (i32, i32, i32, i32) {
    let x = SLIDER_MARGIN_X;
    let w = (area_w as i32 - 2 * SLIDER_MARGIN_X).max(1);
    let y = area_h as i32 - SLIDER_BOTTOM_MARGIN - SLIDER_HEIGHT;
    (x, y, w, SLIDER_HEIGHT)
}

/// The frame index a click at `(px, py)` selects on the slider, or `None`
/// if the click is outside the slider's grab band. With a single frame the
/// slider always reports frame 0.
#[cfg(any(test, feature = "viz-interactive"))]
pub(crate) fn slider_frame_at(
    px: f64,
    py: f64,
    area_w: u32,
    area_h: u32,
    n_frames: usize,
) -> Option<usize> {
    if n_frames == 0 {
        return None;
    }
    let (x, y, w, h) = slider_rect(area_w, area_h);
    let in_x = px >= (x - SLIDER_KNOB_R) as f64 && px <= (x + w + SLIDER_KNOB_R) as f64;
    let in_y = py >= (y - SLIDER_HIT_PAD) as f64 && py <= (y + h + SLIDER_HIT_PAD) as f64;
    if !in_x || !in_y {
        return None;
    }
    if n_frames == 1 {
        return Some(0);
    }
    let frac = ((px - x as f64) / w as f64).clamp(0.0, 1.0);
    Some((frac * (n_frames - 1) as f64).round() as usize)
}

/// Draw the frame slider (track, filled portion, knob) plus a label
/// `frame k/n   x=…` just above it. No-op on a canvas too small.
#[cfg(any(test, feature = "viz-interactive"))]
pub(crate) fn draw_slider<DB: DrawingBackend>(
    area: &DrawingArea<DB, Shift>,
    frame: usize,
    n_frames: usize,
    abscissa_label: &str,
    abscissa: f64,
) -> Result<()>
where
    DB::ErrorType: 'static,
{
    if n_frames == 0 {
        return Ok(());
    }
    let (w, h) = area.dim_in_pixel();
    let (x, y, tw, th) = slider_rect(w, h);
    if tw < 4 * SLIDER_KNOB_R {
        return Ok(());
    }
    let frac = if n_frames > 1 {
        frame as f64 / (n_frames - 1) as f64
    } else {
        0.0
    };
    let knob_x = x + (frac * tw as f64).round() as i32;
    let cy = y + th / 2;

    // Track.
    area.draw(&Rectangle::new(
        [(x, y), (x + tw, y + th)],
        ShapeStyle::from(&SLIDER_TRACK).filled(),
    ))
    .map_err(pl_err)?;
    // Filled portion up to the knob.
    area.draw(&Rectangle::new(
        [(x, y), (knob_x, y + th)],
        ShapeStyle::from(&SLIDER_FILL).filled(),
    ))
    .map_err(pl_err)?;
    // Knob.
    area.draw(&Circle::new(
        (knob_x, cy),
        SLIDER_KNOB_R,
        ShapeStyle::from(&SLIDER_FILL).filled(),
    ))
    .map_err(pl_err)?;
    area.draw(&Circle::new(
        (knob_x, cy),
        SLIDER_KNOB_R,
        ShapeStyle::from(&BUTTON_BORDER),
    ))
    .map_err(pl_err)?;

    // Label above the track.
    let label = format!(
        "frame {}/{}   {}={:.4}",
        frame + 1,
        n_frames,
        abscissa_label,
        abscissa
    );
    let text_style = TextStyle::from(("sans-serif", 13).into_font()).color(&BUTTON_TEXT);
    area.draw_text(&label, &text_style, (x, y - 20))
        .map_err(pl_err)?;
    Ok(())
}

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

    #[test]
    fn button_rect_centred() {
        let (x, _y, w, _h) = button_rect(800);
        // Centred horizontally on an 800-px canvas.
        assert_eq!(x, (800 - BUTTON_WIDTH) / 2);
        assert_eq!(w, BUTTON_WIDTH);
    }

    #[test]
    fn click_hits_button_inside_and_outside() {
        let (bx, by, bw, bh) = button_rect(800);
        let cx = (bx + bw / 2) as f64;
        let cy = (by + bh / 2) as f64;
        assert!(click_hits_button(cx, cy, 800));
        // Far away: not inside.
        assert!(!click_hits_button(0.0, 0.0, 800));
        assert!(!click_hits_button(799.0, 599.0, 800));
    }

    #[test]
    fn draw_overlay_renders_label_in_svg() {
        let mut buf = String::new();
        {
            let backend = SVGBackend::with_string(&mut buf, (400, 100));
            let area = backend.into_drawing_area();
            area.fill(&WHITE).unwrap();
            draw_field_overlay(&area, "T", 0.0, 1.5).unwrap();
            area.present().unwrap();
        }
        // The label text should appear in the SVG output.
        assert!(buf.contains("[T]"));
        assert!(buf.contains("min=0.000"));
        assert!(buf.contains("max=1.500"));
    }

    #[test]
    fn draw_colorbar_renders_value_ticks() {
        let mut buf = String::new();
        {
            let backend = SVGBackend::with_string(&mut buf, (400, 300));
            let area = backend.into_drawing_area();
            area.fill(&WHITE).unwrap();
            draw_colorbar(&area, crate::viz::Colormap::Viridis, 0.0, 2.0).unwrap();
            area.present().unwrap();
        }
        // 5 evenly spaced ticks over [0, 2]: endpoints and midpoint.
        assert!(buf.contains("0.000"));
        assert!(buf.contains("1.000"));
        assert!(buf.contains("2.000"));
    }

    #[test]
    fn slider_frame_at_maps_position_to_index() {
        let (x, y, w, h) = slider_rect(800, 600);
        let cy = (y + h / 2) as f64;
        // Far left → frame 0, far right → last, middle → middle.
        assert_eq!(slider_frame_at(x as f64, cy, 800, 600, 5), Some(0));
        assert_eq!(slider_frame_at((x + w) as f64, cy, 800, 600, 5), Some(4));
        assert_eq!(
            slider_frame_at((x + w / 2) as f64, cy, 800, 600, 5),
            Some(2)
        );
        // Click far above the track → no grab.
        assert_eq!(slider_frame_at((x + w / 2) as f64, 10.0, 800, 600, 5), None);
        // Single frame always reports 0.
        assert_eq!(slider_frame_at(x as f64, cy, 800, 600, 1), Some(0));
    }

    #[test]
    fn draw_slider_renders_label_in_svg() {
        let mut buf = String::new();
        {
            let backend = SVGBackend::with_string(&mut buf, (640, 480));
            let area = backend.into_drawing_area();
            area.fill(&WHITE).unwrap();
            draw_slider(&area, 1, 4, "x", 2.5).unwrap();
            area.present().unwrap();
        }
        assert!(buf.contains("frame 2/4"));
        assert!(buf.contains("x=2.5000"));
    }

    #[test]
    fn draw_view_readout_renders_values_in_svg() {
        let mut buf = String::new();
        {
            let backend = SVGBackend::with_string(&mut buf, (400, 100));
            let area = backend.into_drawing_area();
            area.fill(&WHITE).unwrap();
            let view = crate::viz::View {
                yaw: 45.0,
                pitch: 35.264_389_682_754_654,
                scale: 1.0,
                target: None,
                show_axes: true,
            };
            draw_view_readout(&area, &view).unwrap();
            area.present().unwrap();
        }
        assert!(buf.contains("view=(45.0, 35.3, 1.00)"));
    }

    #[test]
    fn draw_colorbar_skips_tiny_canvas() {
        // Too small to host the bar + labels — must be a no-op, not panic.
        let mut buf = String::new();
        {
            let backend = SVGBackend::with_string(&mut buf, (20, 20));
            let area = backend.into_drawing_area();
            area.fill(&WHITE).unwrap();
            draw_colorbar(&area, crate::viz::Colormap::Viridis, 0.0, 1.0).unwrap();
            area.present().unwrap();
        }
    }
}